<?php
//SELECT * FROM `oc_cireview_invite` WHERE DATE_FORMAT(date_added,'%Y-%m-%d') <= CURRENT_DATE() - INTERVAL 2 DAY
class ControllerCiReviewProCiReviewCron extends Controller {
    private $disableMail = false;
    /*21112019 start*/
    private $useTestEmail;
    private $testEmail;
    /*21112019 end*/
    private $disableMailQueryLog = array(
    	'num_rows' => true,
    	'row' => true,
    	'rows' => true,
    );

    public function __construct($registry) {
    	parent :: __construct($registry);

    	/*20-june-2019 order products design start*/
		/*26-Agu-2019 add code*/
		require_once DIR_SYSTEM . 'library/cireviewpro/simple_html_dom.php';
		/*20-june-2019 order products design end*/

    	$this->disableMail = (bool) $this->config->get('cireviewpro_cronlog_is_maildisable');
    	/*21112019 start*/
    	$this->useTestEmail = (bool) $this->config->get('cireviewpro_cronlog_use_testemail');

    	if ($this->useTestEmail && $this->disableMail) {
    		// $this->testEmail = $this->config->get('config_email');
			if (utf8_strlen($this->config->get('cireviewpro_cronlog_testemail')) > 0 && filter_var($this->config->get('cireviewpro_cronlog_testemail'), FILTER_VALIDATE_EMAIL)) {
				$this->testEmail = $this->config->get('cireviewpro_cronlog_testemail');
			}
    	}
    	/*21112019 end*/
    	// echo $this->disableMail;die;

    	$this->disableMailQueryLog['num_rows'] = (bool) $this->config->get('cireviewpro_cronlog_resultcount');
    	$this->disableMailQueryLog['rows'] = (bool) $this->config->get('cireviewpro_cronlog_resultall');
    	$this->disableMailQueryLog['row'] = (bool) $this->config->get('cireviewpro_cronlog_result');

    	$dir = 'cireviewpro_logs/';

		$odir = $dir;
		$dirs = explode("/", $dir);
		$mkdir = '';
		foreach ($dirs as $key => $value) {
			$mkdir .= $value.'/';
			$this->makedir(DIR_LOGS . $mkdir);
		}

		if (empty($this->config->get('cireviewpro_cronlog_filename'))) {
			$this->config->set('cireviewpro_cronlog_filename', 'cronlog.log');
		}

    	$error_filename = $dir . $this->config->get('cireviewpro_cronlog_filename');

    	$this->ciloger = new Log($error_filename);

    }

    private function makedir($dir) {
		if(!is_dir($dir)) {
			$oldmask = umask(0);
			mkdir($dir, 0777);
			umask($oldmask);
		}
	}

	public function reviewInviteOnOrder($order_id) {
		/*25-04-2019*/
		/* here we may need to delete/add some records in cireview_invite table */

		if($order_id && $this->config->get('cireviewpro_cron_onorder') !=1 && !empty($order_id['order_id'])) {


			$this->load->model('tool/image');
			$this->load->model('checkout/order');


			$order_info = $this->model_checkout_order->getOrder($order_id['order_id']);

			// 16-march-2020 seems following query is not utilize anywhere, please checking properly remove it.
			$as = $this->db->query("SELECT * FROM `". DB_PREFIX . "order` WHERE order_id='". (int)$order_id['order_id'] ."'");

			if($order_info) {

				$query1 = $this->db->query("SELECT * FROM ". DB_PREFIX . "order_product WHERE order_id='". $order_info['order_id'] ."' ");
				$order_products = $query1->rows;
				$orderproducts = array();
				foreach ($order_products as $key => $order_product) {
					$product_image = false;
					$query2 = $this->db->query("SELECT * FROM ". DB_PREFIX . "product WHERE product_id='". $order_product['product_id'] ."'");
					$product_info = $query2->row;
					if($product_info) {
						if(!empty($product_info['image']) && file_exists(DIR_IMAGE . $product_info['image'])) {
							$product_image = $this->model_tool_image->resize($product_info['image'], 100, 100);
						}
					}

					$orderproducts[] = array(
						/*31-10-2018*/
						'order_product_id' => $order_product['order_product_id'],
						/*31-10-2018*/
						'product_id' => $order_product['product_id'],
						'product_name' => $order_product['name'],
						'product_image' => $product_image,
						'product_link' => $this->url->link('product/product', 'product_id=' . $order_product['product_id']),
					);

				}

				/*first invite email*/
				// $firstmail_sql = "SELECT * FROM " . DB_PREFIX . "cireview_invite WHERE order_id='". (int)$order_info['order_id'] ."' AND firstmail=1";

				// $firstmail_query = $this->db->query($firstmail_sql);

				// $this->ciLog($this->queryLog($firstmail_sql, 'reviewInviteOnOrder().firstmail_sql : '));
				// $this->ciLog($this->queryResultLog($firstmail_query, 'reviewInviteOnOrder().firstmail_query : '));
				/*first invite email*/

				$store_logo = false;
				if($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {

					$store_logo = $this->model_tool_image->resize($this->config->get('config_logo'), 200,200);
				}

				/*20-june-2019 order products design start*/
				/*17-july-2019 First invite email is always false, we are just adding record, no invite email go as soon as order placed*/
				$mail_data = array(
					'store_logo' => $store_logo,
					/*first invite email*/
					'firstmail' => false,//!$firstmail_query->num_rows > 0,
					/*first invite email*/
					'order_products' => $orderproducts,
					'order_info' => $order_info,
				);

				// do not merge order_info with mail_data. will remove below line code on 21-08-2019
				// $mail_data = array_merge($mail_data, $order_info);
				/*20-june-2019 order products design end*/
				$this->manageCiReviewInvite($mail_data, false);

			}
		}

		if($order_id && $this->config->get('cireviewpro_cron_onorder') && $this->config->get('cireviewpro_cron_status') && !empty($order_id['order_id'])) {
			$this->load->model('tool/image');
			$this->load->model('checkout/order');

			$order_info = $this->model_checkout_order->getOrder($order_id['order_id']);

			if($order_info) {

				// get new orders and send invite emails
				$orderstatuses = (array)$this->config->get('cireviewpro_cron_orderstatuses');
				$ignore_customer_groups = (array)$this->config->get('cireviewpro_cron_customer_groups');

				if((!empty($orderstatuses) && in_array($order_info['order_status_id'], $orderstatuses)) && (!in_array($order_info['customer_group_id'], $ignore_customer_groups))) {
					$this->orderData($order_info);
				}
			}
		}
	}

	private function queryLog($string, $pre_string='', $post_string='') {
		$str = '';
		// cireviewpro_cronlog_logquery
		if ((bool) $this->config->get('cireviewpro_cronlog_querylog')) {
			$str .= $pre_string;
			$str .= $string;
			$str .= $post_string;
		}
		return $str;
	}

	private function queryResultLog($query, $pre_string='', $post_string='', $loger=array()) {
		if ($query instanceof stdClass) {
			$str1 = '';
			$str = '';
			$loger = array_merge(array(
			'num_rows'=>true,
			'row'=>true,
			'rows'=>true,
			'force_num_rows'=>false,
			'force_row'=>false,
			'force_rows'=>false), $loger);



			if (($this->disableMailQueryLog['num_rows'] === true && $loger['num_rows'] === true && $loger['force_num_rows'] === false) || $loger['force_num_rows'] === true) {
				$str1 .= "\n"."[num_rows] => " . $query->num_rows;
			}
			if (($this->disableMailQueryLog['row'] === true && $loger['row'] === true && $loger['force_row'] === false) || $loger['force_row'] === true) {
				$str1 .= "\n"."[row] => " . print_r($query->row, 1);
			}
			if (($this->disableMailQueryLog['rows'] === true && $loger['rows'] === true && $loger['force_rows'] === false) || $loger['force_rows'] === true) {
				$str1 .= "\n"."[rows] => " . print_r($query->rows, 1);
			}

			if ($str1) {
				$str .= $pre_string;
				$str .= $str1;
				$str .= "\n" . $post_string;
			}
			return $str;
		} else {
			return false;
		}
	}

	public function cron() {
		// https://webmasters.stackexchange.com/questions/20306/how-to-set-up-a-403-forbidden
		if($this->config->get('cireviewpro_cron_status')) {

			$this->ciLog('cron job call');

			$cron_croncode = $this->config->get('cireviewpro_cron_croncode');
			$getvar = utf8_substr($cron_croncode, 0, 4).base64_encode('mysecretcode').utf8_substr($cron_croncode, -6);
			if(!isset($this->request->get[$getvar]) || (isset($this->request->get[$getvar]) && $this->request->get[$getvar]!==$cron_croncode)) {
				$this->ciLog('cron job code not found!');
				return;
			}

			// we clear all the reminders, in order to test. this is temporary and remove code after testing.
			// $this->db->query("TRUNCATE TABLE ". DB_PREFIX . "cireview_invitereminder");
			// $this->db->query("UPDATE ". DB_PREFIX ."cireview_invite SET firstmail=0");
			// $this->db->query("UPDATE ". DB_PREFIX ."cireview_invite SET firstmail=0");
			// $this->db->query("UPDATE ". DB_PREFIX . "cireview_invite SET status='0' WHERE order_id != '36784'");

			// 36459 oder which product was removed from admin by edit order. no need to worry about it

			/*20-june-2019 order products design start*/
			/*26-Agu-2019 remove this code and put it in constructure*/
			// require_once DIR_SYSTEM . 'library/cireviewpro/simple_html_dom.php';
			/*20-june-2019 order products design end*/

			$this->load->model('tool/image');
			$this->load->model('checkout/order');

			// get new orders and send invite emails

			$orderstatuses = (array)$this->config->get('cireviewpro_cron_orderstatuses');

			// send invites only, when we have new order after install the extension. Ignore past orders
			$hasinvite_sql_sql = "SELECT COUNT(*) AS total FROM ". DB_PREFIX . "cireview_invite WHERE status=1";

			$hasinvite_sql = $this->db->query($hasinvite_sql_sql);

			$this->ciLog('cron().orderstatuses: ' . print_r($orderstatuses, 1));

			$this->ciLog($this->queryLog($hasinvite_sql_sql, 'cron().hasinvite_sql_sql: '));
			$this->ciLog($this->queryResultLog($hasinvite_sql, 'cron().hasinvite_sql_result: '));


			// 05-06-2019, 05/june/2019 in case $orderstatuses is empty and no rows foud in invite table, then during resend invite query, $order_statuses can goes undefined.
			$order_statuses = implode(",", $orderstatuses);

			/*first invite email*/
			/*get order id from cireview_invite whose firstmail invites has been send*/
			$firstmail_order_ids = array();
			$firstmail_invite_sql = "SELECT cri.* FROM ". DB_PREFIX . "cireview_invite cri LEFT JOIN `". DB_PREFIX . "order` o on (o.order_id=cri.order_id) WHERE o.order_id=cri.order_id AND cri.status=1 AND cri.review=0 AND o.order_status_id IN(". $order_statuses .") AND cri.firstmail=1";
			$firstmail_invite_query = $this->db->query($firstmail_invite_sql);


			$this->ciLog($this->queryLog($firstmail_invite_sql, 'cron().firstmail_invite_sql: '));
			$this->ciLog($this->queryResultLog($firstmail_invite_query, 'cron().firstmail_invite_query: '));

			foreach ($firstmail_invite_query->rows as $value) {
				if (!in_array($value['order_id'], $firstmail_order_ids)) {
					$firstmail_order_ids[] = $value['order_id'];
				}
			}
			/*first invite email*/

			if(!empty($orderstatuses) && $hasinvite_sql->row['total'] > 0) {

				/*first invite email*/
				/*get order id from cireview_invite whose firstmail invites has not been send and time interval has been reached. (i.e 10 days passed that order status is shipped)*/
				$nfirstmail_order_ids = array();
				$chkorder_ids = array();
				$nfirstmail_invite_sql = "SELECT cri.* FROM ". DB_PREFIX . "cireview_invite cri LEFT JOIN `". DB_PREFIX . "order` o on (o.order_id=cri.order_id) WHERE o.order_id=cri.order_id AND cri.status=1 AND cri.review=0 AND o.order_status_id IN(". $order_statuses .") AND cri.firstmail=0";
				$nfirstmail_invite_query = $this->db->query($nfirstmail_invite_sql);

				$this->ciLog($this->queryLog($nfirstmail_invite_sql, 'cron().not_firstmail_invite_sql: '));
				$this->ciLog($this->queryResultLog($nfirstmail_invite_query, 'cron().not_firstmail_invite_query: '));


				foreach ($nfirstmail_invite_query->rows as $value) {

					if (!isset($chkorder_ids[$value['order_id']])) {
						// check from order history that how much days has been passed since the order status changed to shipped. If days are more than first invite email after x days (i.e:10). Then add them in list to send first invite mailling list.

						$nfirstmail_interval_sql = "SELECT * FROM ". DB_PREFIX . "order_history oh WHERE oh.order_id='". (int)$value['order_id'] ."' AND oh.order_status_id IN(". $order_statuses .") ORDER BY oh.date_added DESC LIMIT 0,1";
						$nfirstmail_interval_query = $this->db->query($nfirstmail_interval_sql);

						$this->ciLog($this->queryLog($nfirstmail_interval_sql, 'cron().each(nfirstmail_invite_query->rows).not_firstmail_interval_sql: '));
						$this->ciLog($this->queryResultLog($nfirstmail_interval_query, 'cron().each(nfirstmail_invite_query->rows).not_firstmail_interval_query: '));

						// add xx days in order history date_added

						$date_added_plus = date('Y-m-d H:i:s', strtotime('+ '. (int)$this->config->get('cireviewpro_cron_firstmail_dayinterval') .' DAYS' . $nfirstmail_interval_query->row['date_added']));
						// $date_added_plus = strtotime($date_added_plus);
						$today = date('Y-m-d H:i:s');

						$chkorder_ids[$value['order_id']] = array(
							'order_id' => $value['order_id'],
							'today' => $today,
							'today_str' => strtotime($today),
							'date_added_plus' => $date_added_plus,
							'date_added_plus_str' => strtotime($date_added_plus),
						);
					}

					if ($chkorder_ids[$value['order_id']]['today_str'] > $chkorder_ids[$value['order_id']]['date_added_plus_str']) {
						// grab order_ids which are ready for first invite emails
						if (!in_array($value['order_id'], $nfirstmail_order_ids)) {
							$nfirstmail_order_ids[] = $value['order_id'];
						}

					}
				}

				/*first invite email*/

				$sql = "SELECT o.order_id FROM `". DB_PREFIX . "order` as `o` WHERE ( o.order_id > (IFNULL((SELECT cri.order_id FROM ". DB_PREFIX . "cireview_invite cri WHERE cri.status=1 ORDER BY cri.order_id DESC LIMIT 0, 1 ),0))";

				// we include cireview_invite order ID. only when record has no reminder. this is the case when customer add order but no invite email send. when cron run, we must include last order as it does not get reminder at all
				$invite_orderids = array();

				/*first invite email*/
				/*05-06-2019, 05/june/2019 */
				// due to first email reminder feature, we grab those order ids which are ready to send for first email, thus there is no point we will collect the orderIDs which has no reminder at all. So we are going to comment following code and update $invite_orderids with those order ids which are ready for first email.


				// $invite_sql_sql = "SELECT cri.* FROM ". DB_PREFIX . "cireview_invite cri LEFT JOIN `". DB_PREFIX . "order` o on (o.order_id=cri.order_id) WHERE o.order_id=cri.order_id AND cri.status=1 AND cri.review=0 AND o.order_status_id IN(". $order_statuses .")";
				// $invite_sql_query = $this->db->query($invite_sql_sql);

				// $this->ciLog($this->queryLog($invite_sql_sql, 'cron().invite_sql_sql: '));
				// $this->ciLog($this->queryResultLog($invite_sql_query, 'cron().invite_sql_query: '));

				// foreach ($invite_sql_query->rows as $key => $value) {
				// 	$reminder_sql = $this->db->query("SELECT COUNT(*) AS total FROM ". DB_PREFIX . "cireview_invitereminder crir WHERE crir.cireview_invite_id='". $value['cireview_invite_id'] ."' ");
				// 	if($reminder_sql->row['total'] <= 0) {
				// 		$invite_orderids[] = $value['order_id'];
				// 	}
				// }
				$invite_orderids = array_merge($invite_orderids, $nfirstmail_order_ids);
				/*first invite email*/

				/*update*/

				if($invite_orderids) {
					$invite_orderids = array_unique($invite_orderids);
					$sql .= " OR o.order_id IN (". implode(",", $invite_orderids) .")";
				}

				$sql .= " )";
				$sql .= " AND o.store_id='". (int)$this->config->get('config_store_id') ."' AND o.order_status_id IN(". $order_statuses .")";

				$ignore_customer_groups = (array)$this->config->get('cireviewpro_cron_customer_groups');


				if(!empty($ignore_customer_groups)) {
					$ignorecustomergroups = implode(",", $ignore_customer_groups);
					$sql .= " AND o.customer_group_id NOT IN (". $ignorecustomergroups .") ";
				}

				$orders_query = $this->db->query($sql);

				// we just collect user information and product information.
				$this->ciLog('cron().send invites only, when we have new order after install the extension. Ignore past orders ');

                $this->ciLog($this->queryLog($sql, 'cron().orders_query sql : '));
				$this->ciLog($this->queryResultLog($orders_query, 'cron().orders_query records : '));

                $maxreminders = (int)$this->config->get('cireviewpro_cron_maxreminders') ? (int)$this->config->get('cireviewpro_cron_maxreminders') : 1;

                $this->ciLog('cron().maxreminders : '. print_r($maxreminders,1) );

				foreach($orders_query->rows as $order) {

					$order_info = $this->model_checkout_order->getOrder($order['order_id']);
					if($order_info) {

						$invite_sql_sql2 = "SELECT cri.* FROM ". DB_PREFIX . "cireview_invite cri LEFT JOIN `". DB_PREFIX . "order` o on (o.order_id=cri.order_id) WHERE o.order_id=cri.order_id AND cri.status=1 AND cri.review=0 AND o.order_id = '". (int)$order['order_id'] ."' ";
						$invite_sql_query2 = $this->db->query($invite_sql_sql2);

						$this->ciLog($this->queryLog($invite_sql_sql2, 'cron().each(orders_query->rows).invite_sql_sql2 : '));
						$this->ciLog($this->queryResultLog($invite_sql_query2, 'cron().each(orders_query->rows).invite_sql_query2 : '));

						$cireviewinvites_order = array();

						foreach ($invite_sql_query2->rows as &$row2) {
							$query4_sql = "SELECT COUNT(*) AS total, cireview_invite_id FROM `" . DB_PREFIX . "cireview_invitereminder` WHERE cireview_invite_id='". $row2['cireview_invite_id'] ."'";
							$query4 = $this->db->query($query4_sql);

							$this->ciLog($this->queryLog($query4_sql, 'cron().each(orders_query->rows).each(invite_sql_query2->rows).query4_sql : '));
							$this->ciLog($this->queryResultLog($query4, 'cron().each(orders_query->rows).each(invite_sql_query2->rows).query4 : '));
							/*first invite email*/
							$row2['total_reminders'] = $query4->row['total'];
							/*first invite email*/
							if($query4->row['total'] < $maxreminders) {

								/*Issue detection and opportunity On 25-04-2019*/

								/*Previously it send xx times for review invites for particular order if particular order has xx products. We need to prevent it and send order products review invite email accordingly.

								OR

								We can send email as per single order product wise as well. If a order has 5 different products then send 5 times. This give us ability to use product short codes and for some users who want separate invite email of each order product. But we will develop this on demand.*/
								// $this->orderData($order_info, $row2);
								$cireviewinvites_order[] = $row2;
							}
						}
						if(!empty($cireviewinvites_order)) {
							/*first invite email*/
							$this->orderData($order_info, $cireviewinvites_order,$cron_call = true);
							/*first invite email*/
						}
					}
				}
			}

			// resend invite emails to already invited customers who still not give review over product of their order

			if($this->config->get('cireviewpro_cron_resendold')) {

				$this->ciLog("cron().cireviewpro_cron_resendold : " . $this->config->get('cireviewpro_cron_resendold'));

				$days = (int)$this->config->get('cireviewpro_cron_dayinterval') ? (int)$this->config->get('cireviewpro_cron_dayinterval') : 1;
				$maxreminders = (int)$this->config->get('cireviewpro_cron_maxreminders') ? (int)$this->config->get('cireviewpro_cron_maxreminders') : 1;

				$this->ciLog("cron().days interval : " . $days);

				$this->ciLog("cron().maxreminders : " . $maxreminders);

				//SELECT * FROM `oc_cireview_invite` WHERE DATE_FORMAT(	date_added,'%Y-%m-%d') <= CURRENT_DATE() - INTERVAL 2 DAY

				/*Issue detection On 25-04-2019*/
				/*Old interval query was faulty, we are going to disable and use another approach*/
				/*$interval_query = "SELECT cri.* FROM `" . DB_PREFIX . "cireview_invite` cri LEFT JOIN `". DB_PREFIX . "order` o on (o.order_id=cri.order_id) WHERE cri.status=1 AND cri.review=0 AND o.order_status_id IN(". $order_statuses .") AND DATE_FORMAT(cri.last_reminder_date_added,'%Y-%m-%d') <= CURRENT_DATE() - INTERVAL ". $days ." DAY GROUP BY cri.order_id";*/
				/*first invite email*/
				// 05-06-2019, 05/june/2019 update $invite_orderids_sql by including order_ids which already has send first email. this will ignore those orders to whome first invte email need to be send. First invite email only send during cron run, not in resend ivit.
				// $invite_orderids_sql = "SELECT cri.* FROM `" . DB_PREFIX . "cireview_invite` cri LEFT JOIN `". DB_PREFIX . "order` o on (o.order_id=cri.order_id) WHERE cri.status=1 AND cri.review=0 AND o.order_status_id IN (". $order_statuses .") GROUP BY cri.order_id";
				$invite_orderids_sql = "SELECT cri.* FROM `" . DB_PREFIX . "cireview_invite` cri LEFT JOIN `". DB_PREFIX . "order` o on (o.order_id=cri.order_id) WHERE cri.status=1 AND cri.review=0 AND o.order_status_id IN (". $order_statuses .") AND cri.order_id IN ('". implode("','", $firstmail_order_ids) ."') GROUP BY cri.order_id";
				/*first invite email*/

				$invite_orderids_query = $this->db->query($invite_orderids_sql);

				$this->ciLog($this->queryLog($invite_orderids_sql, 'cron().invite_orderids_sql : '));
				$this->ciLog($this->queryResultLog($invite_orderids_query, 'cron().invite_orderids_query : '));

				foreach ($invite_orderids_query->rows as $invite_query_value) {

					$order_info = $this->model_checkout_order->getOrder($invite_query_value['order_id']);

					if($order_info) {

						$interval_query = "SELECT cri.* FROM `" . DB_PREFIX . "cireview_invite` cri WHERE cri.order_id='". (int)$invite_query_value['order_id'] ."' AND cri.status=1 AND cri.review=0 AND DATE_FORMAT(cri.last_reminder_date_added,'%Y-%m-%d') <= CURRENT_DATE() - INTERVAL ". $days ." DAY";

						$query3 = $this->db->query($interval_query);

		                $this->ciLog('cron().resend invite emails to already invited customers who still not give review over product of their order');

		                $this->ciLog($this->queryLog($interval_query, 'cron().each(invite_orderids_query->rows).interval_query : '));
						$this->ciLog($this->queryResultLog($query3, 'cron().each(invite_orderids_query->rows).records found : '));

		                $cireviewinvites_order_resend = array();

						/*Issue detection and opportunity On 25-04-2019*/

						/*Previously it send xx times for review invites for particular order if particular order has xx products. We need to prevent it and send order products review invite email accordingly.

						OR

						We can send email as per single order product wise as well. If a order has 5 different products then send 5 times. This give us ability to use product short codes and for some users who want separate invite email of each order product. But we will develop this on demand.*/

						foreach ($query3->rows as $key => &$order) {
							$query5_sql = "SELECT COUNT(*) AS total, cireview_invite_id FROM `" . DB_PREFIX . "cireview_invitereminder` WHERE cireview_invite_id='". $order['cireview_invite_id'] ."'";
							$query5 = $this->db->query($query5_sql);

							$this->ciLog($this->queryLog($query5_sql, 'cron().each(query3->rows).query5_sql : '));
							$this->ciLog($this->queryResultLog($query5, 'cron().each(query3->rows).query5 : '));

							/*first invite email*/
							$order['total_reminders'] = $query5->row['total'];
							/*first invite email*/

							if($query5->row['total'] < $maxreminders) {
								$cireviewinvites_order_resend[] = $order;
								// $this->orderData($order_info, $order);
							}
						}

						if(!empty($cireviewinvites_order_resend)) {
							/*first invite email*/
							$this->orderData($order_info, $cireviewinvites_order_resend, $cron_call = true);
							/*first invite email*/
						}
					}
				}
			}
		}
	}
	/*first invite email*/
	private function orderData($order_info, $cireviewinvites=array(), $cron_call = false) {

		$order_products = array();

		$product_ids = array();
		// leave for now. start here 04062019
		foreach ((array)$cireviewinvites as $key => $cireviewinvite) {
			$product_ids[] = $cireviewinvite['product_id'];
		}

		$order_products_sql = "SELECT * FROM ". DB_PREFIX . "order_product WHERE order_id='". $order_info['order_id'] ."' ";

		if(!empty($product_ids)) {
			$order_products_sql .=  " AND product_id IN ('". implode("','", $product_ids) ."')";
		}

		$query1 = $this->db->query($order_products_sql);

		$this->ciLog($this->queryLog($order_products_sql, 'orderData().order_products_sql : '));
		$this->ciLog($this->queryResultLog($query1, 'orderData().order_products_query : '));

		$order_products = $query1->rows;

		if($order_products) {
			$orderproducts = array();
			foreach ($order_products as $key => $order_product) {
				$product_image = false;
				$order_productinfo_sql = "SELECT * FROM ". DB_PREFIX . "product WHERE product_id='". $order_product['product_id'] ."'";
				$query2 = $this->db->query($order_productinfo_sql);

				$this->ciLog($this->queryLog($order_productinfo_sql, 'orderData().order_products.each.order_productinfo_sql : '));
				$this->ciLog($this->queryResultLog($query2, 'orderData().order_products.each.order_productinfo_query : '));

				$product_info = $query2->row;
				if($product_info) {
					if(!empty($product_info['image']) && file_exists(DIR_IMAGE . $product_info['image'])) {
						$product_image = $this->model_tool_image->resize($product_info['image'], 100, 100);
					}
				}

				$orderproducts[] = array(
					/*31-10-2018*/
					'order_product_id' => $order_product['order_product_id'],
					/*31-10-2018*/
					'product_id' => $order_product['product_id'],
					'product_name' => $order_product['name'],
					'product_image' => $product_image,
					'product_link' => $this->url->link('product/product', 'product_id=' . $order_product['product_id']),
				);

			}

			/*first invite email*/
			$firstmail_sql = "SELECT * FROM " . DB_PREFIX . "cireview_invite WHERE order_id='". (int)$order_info['order_id'] ."' AND firstmail=1";
			$firstmail_query = $this->db->query($firstmail_sql);

			$this->ciLog($this->queryLog($firstmail_sql, 'orderData().firstmail_sql : '));
			$this->ciLog($this->queryResultLog($firstmail_query, 'orderData().firstmail_query : '));
			/*first invite email*/


			$store_logo = false;
			if($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {

				$store_logo = $this->model_tool_image->resize($this->config->get('config_logo'), 200,200);
			}


			/*20-june-2019 order products design start*/
			$mail_data = array(
				'store_logo' => $store_logo,
				/*first invite email*/
				'firstmail' => !$firstmail_query->num_rows > 0,
				/*first invite email*/
				'order_products' => $orderproducts,
				'order_info' => $order_info,
			);

			// do not merge order_info with mail_data. will remove below line code on 21-08-2019
			// $mail_data = array_merge($mail_data, $order_info);
			/*20-june-2019 order products design start*/
			$this->sendMail($mail_data, $cireviewinvites, $cron_call);

		}

	}


	private function sendMail($mail_data, $cireviewinvites=array(), $cron_call = false) {


		// get langauge id from langauge code
		$lang_code_sql = "SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $this->db->escape($mail_data['order_info']['language_code']) . "'";

		$lang_code_query = $this->db->query($lang_code_sql);

		$this->ciLog($this->queryLog($lang_code_sql, 'sendMail().lang_code_sql : '));
		$this->ciLog($this->queryResultLog($lang_code_query, 'sendMail().lang_code_query : '));

		/*first invite email*/
		if (isset($mail_data['firstmail']) && $mail_data['firstmail'] === true) {
			$this->ciLog('sendMail().first mail didn\'t send yet, use firstmail content : ');
			// first mail didn't send yet, use firstmail content
			$mail_content = $this->config->get('cireviewpro_cron_firstmail');
		} else {
			$this->ciLog('sendMail().first mail already send, use default mail content : ');
			// first mail already send, use default mail content
			$mail_content = $this->config->get('cireviewpro_cron_mail');
		}
		/*first invite email*/

		// $mail_data['order_info']['email'] = 'karan1251@gmail.com';

		$mailcontent = array();

		 if(!empty($lang_code_query->row) && isset($mail_content[$lang_code_query->row['language_id']])) {
			$mailcontent = $mail_content[$lang_code_query->row['language_id']];
		} else if (!empty($lang_code_query->row) && !empty($mail_content) && is_array($mail_content)) {
			reset($mail_content);
			$first_key = key($mail_content);
			if (isset($mail_content[$first_key])) {
				$mailcontent = $mail_content[$first_key];
			}
		}

		// $this->ciLog('sendMail().$mailcontent : ' . print_r($mailcontent, 1));

		if ($mailcontent) {

		$find = array(
			'{FIRSTNAME}',
			'{LASTNAME}',
			'{EMAIL}',
			'{STORE_NAME}',
			'{LOGO}',
			/*20-june-2019 order products design start*/
			'{ORDER_ID}',
			// '{ORDER_PRODUCTS}',
			/*20-june-2019 order products design end*/
		);
		/*20-june-2019 order products design end*/
		$or = array();
		foreach ($mail_data['order_info'] as $order_variable => $order_value) {
			if ($order_variable == 'order_id') {
				continue;
			}
			if (strstr($order_variable, 'custom_field')) {
				continue;
			}
			$or[] = '{ORDER_'. $order_variable .'}';

		}
		$find = array_merge($find, $or);
		/*20-june-2019 order products design end*/
		$replace = array(
			'FIRSTNAME' => $mail_data['order_info']['firstname'],
			'LASTNAME'  => $mail_data['order_info']['lastname'],
			'EMAIL'  => $mail_data['order_info']['email'],
			'STORE_NAME' => $this->config->get('config_name'),
			'LOGO' => $mail_data['store_logo'] ? '<img src="'. $mail_data['store_logo'] .'" alt="'. $this->config->get('config_name') .'">' : '',
			/*20-june-2019 order products design start*/
			'ORDER_ID' => $mail_data['order_info']['order_id'],
			// 'ORDER_PRODUCTS' => $this->orderProducts($mail_data),
			/*20-june-2019 order products design end*/
		);
		/*20-june-2019 order products design end*/
		$ro = array();
		foreach ($mail_data['order_info'] as $order_variable => $order_value) {
			if ($order_variable == 'order_id') {
				continue;
			}
			if (strstr($order_variable, 'custom_field')) {
				continue;
				// $order_value = json_encode($order_value);
			}
			$ro['ORDER_'. $order_variable .''] = $order_value;
		}

		$replace = array_merge($replace, $ro);
		/*20-june-2019 order products design end*/

		$message = html_entity_decode($mailcontent['message'], ENT_QUOTES, 'UTF-8');
		$subject = html_entity_decode($mailcontent['subject'], ENT_QUOTES, 'UTF-8');


		$subject = str_replace(array("\r\n", "\r", "\n"), ' ', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), ' ', trim(str_replace($find, $replace, $subject))));

		$message = str_replace(array("\r\n", "\r", "\n"), ' ', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), ' ', trim(str_replace($find, $replace, $message))));

		/*20-june-2019 order products design start*/
		$this->orderProducts($mail_data, $message);
		/*20-june-2019 order products design end*/

		$html = $this->header($subject);
		$html .= $message;
		$html .= $this->footer();

		$this->manageCiReviewInvite($mail_data);

		// temporary
		/*21112019 start*/
		if($this->testEmail && $this->useTestEmail && $this->disableMail) {
			$this->ciLog("In Test mode Using Test Email");
			$mail_data['order_info']['email'] = $this->testEmail;
		}
		/*21112019 end*/
		// $mail_data['order_info']['email'] = 'karan1251@gmail.com';

		if(VERSION >= '3.0.0.0') {
			$mail = new Mail($this->config->get('config_mail_engine'));
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
			$mail->smtp_username = $this->config->get('config_mail_smtp_username');
			$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
			$mail->smtp_port = $this->config->get('config_mail_smtp_port');
			$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
		} else if(VERSION <= '2.0.1.1') {
	     	$mail = new Mail($this->config->get('config_mail'));
	    } else {
			$mail = new Mail();
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
			$mail->smtp_username = $this->config->get('config_mail_smtp_username');
			$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
			$mail->smtp_port = $this->config->get('config_mail_smtp_port');
			$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
		}

		$mail->setTo($mail_data['order_info']['email']);
		// $mail->setTo('karan1251@gmail.com');
		$mail->setFrom($this->config->get('config_email'));
		$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
		$mail->setSubject( html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
		$mail->setHtml($html);
		$this->ciLog("mail data");
		$this->ciLog(print_r($mail_data,1));
		/*21112019 start*/
		if (!$this->disableMail || ($this->testEmail && $this->useTestEmail && $this->disableMail) ) {
			if (!$this->disableMail) {
				$this->ciLog("Mail is enable");
			}
			if ($this->testEmail && $this->useTestEmail && $this->disableMail) {
				$this->ciLog("Test Mail is enable");
			}
			/*21112019 end*/
        	$mail->send();
        } else {
        	$this->ciLog("Mail is disble");
        }

        /*first invite email*/
        if ((int)$this->config->get('cireviewpro_cronlog_is_maillog')) {
        	$this->ciLog(print_r($mail,1));
        }
        /*first invite email*/

        }
	}
	/*first invite email*/
    private function ciLog($text, $write=true) {
        if($write) {
           $write = (bool) $this->config->get('cireviewpro_cronlog_status');
        }
        if($write && !empty($text)) {
            $this->ciloger->write($text);
        }
    }
	private function header($title) {
		return '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>'.$title.'</title></head><body style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #000000;"><div style="width: 680px;">';
	}

	private function footer() {
		return  '</div></body></html>';
	}
	/*20-june-2019 order products design start*/
	// private function orderProducts($mail_data) {
	// 	// Load the language for any mails that might be required to be sent out
	// 	$language = new Language($mail_data['order_info']['language_code']);
	// 	$language->load($mail_data['order_info']['language_code']);
	// 	$language->load('cireviewpro/cireviewcron');

	// 	$html = '<table style="border-collapse: collapse; width: 100%; border-top: 1px solid #DDDDDD; border-left: 1px solid #DDDDDD; margin-bottom: 20px;">';
	// 	$html .= '	<thead>';
	// 	$html .= '		<tr>';
	// 	$html .= '			<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; background-color: #EFEFEF; font-weight: bold; text-align: left; padding: 7px; color: #222222;">'. $language->get('text_product') .'</td>';
	// 	$html .= '			<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; background-color: #EFEFEF; font-weight: bold; text-align: left; padding: 7px; color: #222222;">'. $language->get('text_image') .'</td>';
	// 	$html .= '			<td style="font-size: 12px; border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; background-color: #EFEFEF; font-weight: bold; text-align: left; padding: 7px; color: #222222;">'. $language->get('text_link') .'</td>';
	// 	$html .= '		</tr>';
	// 	$html .= '	</thead>';
	// 	$html .= '	<tbody>';
	// 	foreach ($mail_data['order_products'] as $key => $order_product) {
	// 	$html .= '		<tr>';
	// 	$html .= '			<td style="font-size: 12px;	border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: left; padding: 7px;"><a href="'. $order_product['product_link'] .'#tab-review">'. $order_product['product_name'] .'</a></td>';
	// 	$html .= '			<td style="font-size: 12px;	border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: left; padding: 7px;"><a href="'. $order_product['product_link'] .'#tab-review">'. '<img src="'. $order_product['product_image'] .'" alt="'. $order_product['product_name'] .'" />' .'</a></td>';
	// 	$html .= '			<td style="font-size: 12px;	border-right: 1px solid #DDDDDD; border-bottom: 1px solid #DDDDDD; text-align: left; padding: 7px;"><a href="'. $order_product['product_link'] .'#tab-review">'. $language->get('text_product_link') .'</a></td>';
	// 	$html .= '		</tr>';
	// 	}
	// 	$html .= '	</tbody>';
	// 	$html .= '</table>';

	// 	return $html;
	// }
	private function orderProducts($mail_data, &$message) {

		$html = new simple_html_dom();

		$html->load($message);

		//get all order_products
		$order_products = $html->find('.order_products');

		foreach($order_products as $order_product) {
			$a = '';
			foreach ($mail_data['order_products'] as $mail_order_products) {

				$orderproduct = $order_product;

				$orderproduct = str_replace('{PRODUCT_NAME}', $mail_order_products['product_name'], $orderproduct);
				$orderproduct = str_replace('{PRODUCT_LINK}', $mail_order_products['product_link'], $orderproduct);
				$orderproduct = str_replace('{PRODUCT_IMAGE}', '<img src="'. $mail_order_products['product_image'] .'" alt="'. $mail_order_products['product_name'] .'" />' , $orderproduct);

				$a .= $orderproduct;
			}
			$order_product->outertext = $a;
		}
		$message = $html;
	}
	/*20-june-2019 order products design end*/
	private function manageCiReviewInvite($mail_data, $reminder=true) {
		/*
		 * 06-feb-2020
		 * We found this function call in multiple situations
		 * 1: new order creation
		 * 2: order status update
		 * 3: order edit
		 * 4: order delete
		 * 5: cron job
		 */

		// check if we already have record
		$this->ciLog("manageCiReviewInvite().start mail_data.order_products loop . ORDER_ID :" . $mail_data['order_info']['order_id']);

		// print_r($mail_data);die;

		foreach ($mail_data['order_products'] as $key => $order_product) {

			/*
			 * 06-feb-2020
			 * We notice admin might can change customer from backend as well. So do not include customer_id caluse in select query.
			 * Admin might change store too. So we will update store_id accordingy. So do not include store_id caluse in select query
			 * There might be chances admin remove the product, but this is another what if
			 * There might be chances we send reminder to customers, but if admin change order customer and then redo. In this case customer again got reminders.
			 */


			do {
				$continue_do = false;

				$query = $this->db->query("SELECT * FROM ". DB_PREFIX ."cireview_invite WHERE order_id='". $mail_data['order_info']['order_id'] ."' AND product_id='". $order_product['product_id'] ."' ");
				// AND customer_id='". $mail_data['order_info']['customer_id'] ."' AND store_id='". $mail_data['order_info']['store_id'] ."'

				foreach ($query->rows as $row) {

					if ($row['store_id'] != $mail_data['order_info']['store_id']) {
						$this->ciLog("manageCiReviewInvite(). table cireview_invite change on store Old store_id: " . $row['store_id'] . " New store_id: ". $mail_data['order_info']['store_id'] ." For  ORDER_ID:".$mail_data['order_info']['order_id'] . " AND Product_ID: ". $order_product['product_id'] .". So update record of cireview_invite_id: ". $row['cireview_invite_id'] ." ");
						$this->db->query("UPDATE ". DB_PREFIX ."cireview_invite SET store_id='". $mail_data['order_info']['store_id']."', date_modified=NOW() WHERE cireview_invite_id='". (int)$row['cireview_invite_id'] ."' ");
					}

					// admin change customer of order then we first disable status of cireview_invite for old customer or probably we should delete it. Then insert new record!!
					if ($row['customer_id'] != $mail_data['order_info']['customer_id']) {

						$this->ciLog("manageCiReviewInvite(). table cireview_invite change on customer Old customer_id: " . $row['customer_id'] . " New customer_id: ". $mail_data['order_info']['customer_id'] ." For  ORDER_ID:".$mail_data['order_info']['order_id'] . " AND Product_ID: ". $order_product['product_id'] .". So Delete record of cireview_invite_id: ". $row['cireview_invite_id'] ." ");
						$this->ciLog("manageCiReviewInvite(). table cireview_invite change on customer so delete records from cireview_invitereminder table too ");

						$this->db->query("DELETE FROM ". DB_PREFIX ."cireview_invite WHERE cireview_invite_id='". (int)$row['cireview_invite_id'] ."'");
						// also delete records in cireview_invitereminder table
						$this->db->query("DELETE FROM ". DB_PREFIX ."cireview_invitereminder WHERE cireview_invite_id='". (int)$row['cireview_invite_id'] ."'");

						$continue_do = true;
					}
				}

			} while ($continue_do);


			/*
			 * 28-08-2019
			 * Here we may have very interesting issue. found in dave website. Single order email send twice and in table cireview_invite same entry goes twice. So we will remove all except first
			 * also, prevent to insert record more than once.
			*/
			if ($query->num_rows > 1) {
				$cilog = 'cireview_invite_ids are as follow: ';
				foreach ($query->rows as $value) {
					if ($value['cireview_invite_id'] != $query->row['cireview_invite_id']) {
						$cilog .= '[cireview_invite_id :' . $query->row['cireview_invite_id'] . '],';
						$this->db->query("DELETE FROM ". DB_PREFIX ."cireview_invite WHERE cireview_invite_id='". (int)$value['cireview_invite_id'] ."'");
					}
				}

				$this->ciLog("manageCiReviewInvite(). table cireview_invite contain more than one entry for invites. Thus we delete them " . $cilog . " ORDER_ID :" . $mail_data['order_info']['order_id']);
			}

			if($query->num_rows) {
				$this->ciLog("manageCiReviewInvite(). find cireview_invite recrord, use invite id: " . $query->row['cireview_invite_id'] . " ORDER_ID :" . $mail_data['order_info']['order_id']);
				$cireview_invite_id = $query->row['cireview_invite_id'];
			} else {
				$this->ciLog("manageCiReviewInvite(). do not found cireview_invite recrord. ORDER_ID :".$mail_data['order_info']['order_id']);

				$this->db->query("INSERT INTO ". DB_PREFIX ."cireview_invite SET order_id='". $mail_data['order_info']['order_id'] ."', store_id='". $mail_data['order_info']['store_id'] ."', customer_id='". $mail_data['order_info']['customer_id'] ."', product_id='". $order_product['product_id'] ."', invite=1, status=1, date_added=NOW()");

				$cireview_invite_id = $this->db->getLastId();
				$this->ciLog("manageCiReviewInvite(). create cireview_invite recrord, invite id:" . $cireview_invite_id . " ORDER_ID :".$mail_data['order_info']['order_id']);
			}
			if($reminder) {
			$this->db->query("INSERT INTO ". DB_PREFIX ."cireview_invitereminder SET cireview_invite_id='". $cireview_invite_id ."', reminder=1, date_added=NOW()");
			$cireview_invitereminder_id = $this->db->getLastId();

			$this->ciLog("manageCiReviewInvite(). invite reminder is true. Add new invite reminde record. invite Reminder ID : " . $cireview_invitereminder_id . " ORDER_ID :".$mail_data['order_info']['order_id']);

			$this->db->query("UPDATE ". DB_PREFIX ."cireview_invite SET last_reminder_id='". $cireview_invitereminder_id ."' WHERE cireview_invite_id='". $cireview_invite_id ."'");

			$this->ciLog("manageCiReviewInvite(). update cireview_invite with recent invite Reminder ID : " . $cireview_invitereminder_id . " where invite ID : " . $cireview_invite_id . " ORDER_ID :".$mail_data['order_info']['order_id']);


			$this->db->query("UPDATE ". DB_PREFIX ."cireview_invite SET last_reminder_date_added=NOW() WHERE cireview_invite_id='". $cireview_invite_id ."'");

			$this->ciLog("manageCiReviewInvite(). update cireview_invite with current date and time where invite ID : " . $cireview_invite_id . " ORDER_ID :".$mail_data['order_info']['order_id']);
			} else {
				$this->ciLog("manageCiReviewInvite(). invite reminder is false . ORDER_ID :".$mail_data['order_info']['order_id']);
			}

			// 06-feb-2020 shift last_reminder_date_added query in $reminder variable true condition, because this function  in multiple situations, to at start of this functions


			/*first invite email*/
			if(!$this->disableMail) {
				// when in testing mode do not update firstmail column, it disturb the behaviour
				if (isset($mail_data['firstmail']) && $mail_data['firstmail'] === true) {
					$ciLog = "mail_data.firstmail is true";
					$this->db->query("UPDATE ". DB_PREFIX ."cireview_invite SET firstmail=1 WHERE cireview_invite_id='". $cireview_invite_id ."'");
				} else {
					$ciLog = "mail_data.firstmail is false";
				}
				$this->ciLog("manageCiReviewInvite(). mails are enable check if send first mail is true or false. " . $ciLog . " ORDER_ID :".$mail_data['order_info']['order_id']);
			} else {
				$this->ciLog("manageCiReviewInvite(). mails are disable and treated as testing mode. In testing mode do not update firstmail column, it disturb the behaviour. ORDER_ID :".$mail_data['order_info']['order_id']);
			}
			/*first invite email*/
			/*31-10-2018 verify purchase info start*/

			/*
			 * 06-feb-2020
			 * We notice admin might can change customer from backend as well. So do not include customer_id caluse in select query.
			 * Admin might change store too. So we will update store_id accordingy. So do not include store_id caluse in select query
			 * There might be chances admin remove the product, but this is another what if
			 * There might be chances we send reminder to customers, but if admin change order customer and then redo. In this case old given review get unverified. New review will show verfied
			 */

			do {
				$continue_do = false;

				$query = $this->db->query("SELECT * FROM ". DB_PREFIX ."cireview_verify WHERE order_id='". $mail_data['order_info']['order_id'] ."' AND product_id='". $order_product['product_id'] ."' ");
				/*
				 * 06-FEB-2020
				 * when admin edit order then new order_product_id generated. So we didn't use order_product_id for search
				 * Admin migh be can change customer too. So we must update customer_id accordingl.
				 */
				// AND customer_id='". $mail_data['order_info']['customer_id'] ."' AND order_product_id='". $order_product['order_product_id'] ."' AND store_id='". $mail_data['order_info']['store_id'] ."'

				// here we will update order_product_id if old order_product_id didn't match with new one


				foreach ($query->rows as $row) {
					if ($row['store_id'] != $mail_data['order_info']['store_id']) {
						$this->ciLog("manageCiReviewInvite(). table cireview_verify change on store Old store_id: " . $row['store_id'] . " New store_id: ". $mail_data['order_info']['store_id'] ." For  ORDER_ID:".$mail_data['order_info']['order_id'] . " AND Product_ID: ". $order_product['product_id'] .". So update record of cireview_verify_id: ". $row['cireview_verify_id'] ." ");
						$this->db->query("UPDATE ". DB_PREFIX ."cireview_verify SET store_id='". $mail_data['order_info']['store_id']."', date_modified=NOW() WHERE cireview_verify_id='". (int)$row['cireview_verify_id'] ."' ");
					}

					if ($row['order_product_id'] != $order_product['order_product_id']) {

						$this->ciLog("manageCiReviewInvite(). table cireview_verify change on order_product_id Old order_product_id: " . $row['order_product_id'] . " New order_product_id: ". $order_product['order_product_id'] ." For  ORDER_ID:".$mail_data['order_info']['order_id'] . " AND Product_ID: ". $order_product['product_id'] ." ");

						$this->db->query("UPDATE ". DB_PREFIX ."cireview_verify SET order_product_id='". $order_product['order_product_id'] ."', date_modified=NOW() WHERE cireview_verify_id='". (int)$row['cireview_verify_id'] ."'");
					}

					// admin change customer of order then we first disable status of cireview_verify for old customer or probably we should delete it. Then insert new record!! It is because the old review is not from new customer. So old customer review is not treated as verified

					if ($row['customer_id'] != $mail_data['order_info']['customer_id']) {

						$this->ciLog("manageCiReviewInvite(). table cireview_verify change on customer Old customer_id: " . $row['customer_id'] . " New customer_id: ". $mail_data['order_info']['customer_id'] ." For  ORDER_ID:".$mail_data['order_info']['order_id'] . " AND Product_ID: ". $order_product['product_id'] .". So Delete record of cireview_verify_id: ". $row['cireview_verify_id'] ." ");

						$this->db->query("DELETE FROM ". DB_PREFIX ."cireview_verify WHERE cireview_verify_id='". (int)$row['cireview_verify_id'] ."'");
						$continue_do = true;
					}
				}

			} while ($continue_do);

			/*
			 * 28-08-2019
			 * Here we may have very interesting issue. Single order email send twice and in table cireview_invite same entry goes twice. So we will remove all except first
			 * also, prevent to insert record more than once.
			*/

			/*
	 		 * 06-FEB-2020
			 *before delete any record we must be aware if no review is given over product
			 * first detect on which cireview_verify_ids we have review
	 		 */
			if ($query->num_rows > 1) {

				$cireview_verify_ids_with_review = array();
				$cilog = 'cireview_verify_ids are as follow: ';
				foreach ($query->rows as $value) {
					if ($value['review_id']) {
						$cireview_verify_ids_with_review[] = $query->row['cireview_verify_id'];
					}
				}

				// only delete records which has no review
				foreach ($query->rows as $value) {
					if ($value['cireview_verify_id'] != $query->row['cireview_verify_id'] && !$value['review_id']) {
						$cilog .= '[cireview_verify_id :' . $query->row['cireview_verify_id'] . '],';

						$this->db->query("DELETE FROM ". DB_PREFIX ."cireview_verify WHERE cireview_verify_id='". (int)$value['cireview_verify_id'] ."' AND review=0");
					}
				}

				$this->ciLog("manageCiReviewInvite(). table cireview_verify contain more than one entry for verification. Thus we delete them " . $cilog . " ORDER_ID :".$mail_data['order_info']['order_id']);
			}

			if($query->num_rows) {
				$this->ciLog("manageCiReviewInvite(). find cireview_verify recrord, use verify id: " . $query->row['cireview_verify_id'] . " ORDER_ID :".$mail_data['order_info']['order_id']);

				$cireview_verify_id = $query->row['cireview_verify_id'];
			} else {
				$this->ciLog("manageCiReviewInvite(). do not found cireview_verify recrord. ORDER_ID :".$mail_data['order_info']['order_id'] . " Product_ID: ". $order_product['product_id'] ." ");

				$this->db->query("INSERT INTO ". DB_PREFIX ."cireview_verify SET order_id='". $mail_data['order_info']['order_id'] ."', store_id='". $mail_data['order_info']['store_id'] ."', customer_id='". $mail_data['order_info']['customer_id'] ."', order_product_id='". $order_product['order_product_id'] ."', product_id='". $order_product['product_id'] ."', status=1, date_added=NOW()");
				$cireview_verify_id = $this->db->getLastId();

				$this->ciLog("manageCiReviewInvite(). create cireview_verify recrord, verify id:" . $cireview_verify_id . " ORDER_ID :".$mail_data['order_info']['order_id']);
			}

			// here we disable verify, when order is deleted
			// 06-feb-2020
			// no need because when edit order then first order get void also even if order get deleted the verify statusmust stay
			// we will manage delete or disable records after delete the order query. which will be do later on

			// if($mail_data['order_info']['order_status_id'] == 0) {
			// 	$this->ciLog("manageCiReviewInvite(). order is deleted. So update status to disable. ORDER_ID :".$mail_data['order_info']['order_id']);

			// 	$this->db->query("UPDATE ". DB_PREFIX ."cireview_verify SET status='0', date_modified=NOW() WHERE order_id='". (int)$mail_data['order_info']['order_id'] ."'");
			// }
			/*31-10-2018 verify purchase info end*/
		}
		$this->ciLog("manageCiReviewInvite().end mail_data.order_products loop . ORDER_ID :".$mail_data['order_info']['order_id']);
	}
}
