<?php
/**
 * Reward Email Template Model
 *
 * @package Vite_Reward_Lite\Models\Database
 */

namespace Vite_Reward_Lite\Models\Database;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Vite_Reward_Lite\Core\Vite_Reward_Lite_Model;
use Sabberworm\CSS\Property\Charset;

/**
 * Class Mapbd_Reward_Email_Template
 *
 * @package Vite_Reward_Lite\Models\Database
 */
class Mapbd_Reward_Email_Template extends Vite_Reward_Lite_Model {

	/**
	 * Its property k_word
	 *
	 * @var String
	 */
	public $k_word;

	/**
	 * Its property grp
	 *
	 * @var String
	 */
	public $grp;

	/**
	 * Its property title
	 *
	 * @var String
	 */
	public $title;

	/**
	 * Its property status
	 *
	 * @var Charset
	 */
	public $status;

	/**
	 * Its property subject
	 *
	 * @var Charset
	 */
	public $subject;

	/**
	 * Its property content
	 *
	 * @var String
	 */
	public $content;    /**
						 * Its property props
						 *
						 * @var String
						 */
	public $props;

	/**
	 * Mapbd_Reward_Email_Template constructor.
	 */
	public function __construct() {
		parent::__construct();
		$this->set_validation();
		$this->table_name     = 'apbd_reward_email_templates';
		$this->primary_key    = 'k_word';
		$this->unique_key     = array();
		$this->multi_key      = array();
		$this->auto_inc_field = array( 'id' );
		$this->app_base_name  = 'reward-point';
	}


	/**
	 * The set validation is generated by appsbd
	 */
	public function set_validation() {
		$this->validations = array(
			'k_word'  => array(
				'Text' => 'Key Word',
				'Rule' => 'required|max_length:3',
			),
			'grp'     => array(
				'Text' => 'Group',
				'Rule' => 'required|max_length:20',
			),
			'title'   => array(
				'Text' => 'Title',
				'Rule' => 'required|max_length:100',
			),
			'status'  => array(
				'Text' => 'Status',
				'Rule' => 'required|max_length:1',
			),
			'subject' => array(
				'Text' => 'Subject',
				'Rule' => 'required|max_length:150',
			),
			'props'   => array(
				'Text' => 'Props',
				'Rule' => 'required',
			),
			'content' => array(
				'Text' => 'Content',
				'Rule' => 'required',
			),
		);
	}

	/**
	 * The create db table is generated by appsbd
	 */
	public static function create_db_table() {
		$this_obj = new static();
		$table    = $this_obj->db->prefix . $this_obj->table_name;
		if ( $this_obj->db->get_var( "show tables like '{$table}'" ) != $table ) {
			$sql = "CREATE TABLE $table (
  						`k_word` char(3) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '',
  						`grp` char(100) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '',
  						`title` char(100) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '',
  						`status` char(1) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT 'A' COMMENT 'bool(A=Active,I=Inactive)',
  						`subject` char(150) COLLATE utf8mb4_unicode_520_ci NOT NULL DEFAULT '',
  						`props` mediumtext COLLATE utf8mb4_unicode_520_ci NOT NULL,
  						`content` mediumtext COLLATE utf8mb4_unicode_520_ci NOT NULL,
  						PRIMARY KEY (`k_word`) USING BTREE
                    )";
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			dbDelta( $sql );
		}
	}

	/**
	 * The get details is generated by appsbd
	 */
	public function get_details() {
		$obj          = new \stdClass();
		$obj->k_word  = $this->k_word;
		$obj->subject = $this->subject;
		$obj->content = $this->content;
		$obj->props   = $this->get_props();

		return $obj;
	}

	/**
	 * The get props  is generated by appsbd
	 */
	public function get_props() {
		$props_list = explode( ',', $this->props );
		$props      = array();
		foreach ( $props_list as $prop ) {
			$prop_data = explode( '=', $prop );
			if ( count( $prop_data ) >= 2 ) {
				$prop_obj       = new \stdClass();
				$prop_obj->prop = $prop_data[0];
				$prop_obj->des  = $prop_data[1];
				$props[]        = $prop_obj;
			}
		}

		return $props;
	}

	/**
	 * The add new template is generated by appsbd
	 *
	 * @param mixed $k_word It is key word.
	 * @param mixed $grp It is key grp.
	 * @param mixed $title It is key title.
	 * @param mixed $status It is key status.
	 * @param mixed $subject It is key subject.
	 * @param mixed $props It is key props.
	 * @param mixed $content It is key content.
	 *
	 * @return bool
	 */
	public static function add_new_template( $k_word, $grp, $title, $status, $subject, $props, $content ) {
		$obj = new self();
		if ( ! $obj->is_exists( 'k_word', $k_word ) ) {
			$newobj = new self();
			$newobj->k_word( $k_word );
			$newobj->grp( $grp );
			$newobj->title( $title );
			$newobj->status( $status );
			$newobj->subject( $subject );
			$newobj->content( $content );
			$newobj->props( $props );
			return $newobj->Save();
		} else {
			return false;
		}
	}

	/**
	 * The send email templates is generated by appsbd
	 *
	 * @param mixed  $keyword It is keyword.
	 * @param mixed  $to_email It is mail.
	 * @param array  $params It is params.
	 * @param string $subject It is email subject.
	 *
	 * @return bool
	 */
	public static function send_email_templates( $keyword, $to_email, $params = array(), $subject = '' ) {
		if ( empty( $to_email ) ) {
			return true;
		}
		$obj = self::find_by( 'k_word', $keyword );

		if ( ! empty( $obj ) ) {
			if ( 'A' != $obj->status ) {
				return true;
			}
		}
		if ( ! isset( $params['site_name'] ) ) {
			$params['site_name'] = get_bloginfo( 'name' );
		}
		if ( ! isset( $params['site_url'] ) ) {
			$params['site_url'] = home_url();
		}
		$search  = array();
		$replace = array();
		foreach ( $params as $key => $value ) {
			$search[]  = '{{' . $key . '}}';
			$replace[] = $value;
		}
		$content = str_replace( $search, $replace, $obj->content );
		if ( in_array( $keyword, array( 'POP', 'SUP', 'ORP', 'ROR', 'ORR', 'BUP' ) ) && ! empty( $params['user_id'] ) && ! empty( $params['msg'] ) ) {
			$content = self::get_email_content( $content, $params['msg'] );
		}
		$subject = $obj->subject;
		$subject = str_replace( $search, $replace, $subject );
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );
		if ( ! wp_mail( $to_email, $subject, $content, $headers ) ) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * The get email content is generated by appsbd
	 *
	 * @param mixed  $content It is content.
	 * @param string $reward_title It is reward title.
	 *
	 * @return false|string
	 */
	public static function get_email_content( $content, $reward_title = '' ) {
		ob_start()?>
		<!DOCTYPE html>
		<html xmlns="http://www.w3.org/1999/xhtml">
			<head>
				<meta name="viewport" content="width=device-width" />
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
				<style>
					html{
						font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;
					}
					.em-d-none{
						display:none;
					}
					.em-reply-line{
						color:rgb(226, 223, 223); border-top: 1px dotted #ccc;font-size: 12px;
					}
				</style>
			</head>
			<body data-start="start-here" itemscope itemtype="http://schema.org/EmailMessage">
			<div id="full-email-body">
				<div class="em-d-none"><?php echo esc_html( $reward_title ); ?></div>
				<div class="em-d-none" >--start--</div>
				<div class="body-container">
					<!--<div class="replay-line em-reply-line"></div>-->
					<div class="mail-container">
						<div class="mail-content">
							<?php echo wp_kses_post( $content ); ?>
						</div>
					</div>
				</div>
				<div class="em-d-none">--end--</div>
			</div>
			</body>
		</html>
		<?php
		return ob_get_clean();
	}
}
