<?php

use GPBMetadata\Google\Protobuf\Wrappers;

require_once (PATH_CONTROLLERS 	. "Common.php") ;
require_once (PATH_LIB . "LicenseFile.php");
require_once (PATH_MODELS . "customer/CustomerClass.php") ;
require_once (PATH_MODELS . "customer/CustomerContactClass.php") ;
require_once (PATH_MODELS . "customer/CustomerScheduleClass.php") ;
require_once (PATH_MODELS . "campaign/CampaignClass.php") ;
require_once (PATH_MODELS . "campaign/CampaignProfileClass.php") ;
require_once (PATH_MODELS . "campaign/CampaignHeaderImageClass.php") ;
require_once (PATH_MODELS . "campaign/CampaignDetailClass.php") ;
require_once (PATH_MODELS . "campaign/CampaignRecipientClass.php") ;
require_once (PATH_MODELS . "prospect/ProspectClass.php") ;
require_once (PATH_MODELS . "admin/SoftwareClass.php") ;
require_once (PATH_MODELS . "prospect/PersonContactClass.php");
require_once (PATH_MODELS . "prospect/ProspectContactClass.php");

class SendCampaignList extends GLBase {
	private $type = "" ;
	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
		$this->orgid 	= $_SESSION[SE_ORGID] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = Command::SendCampaignListView ;

		try {
			$this->db->open() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			if (!$this->checkSessionTimeout($this->type)) {
				$this->db->close();
				return false;
			}
			switch ($this->type) {
				case Command::SendCampaignListView:
					$this->processSendCampaignListInfo($params) ;
					break ;
				case Command::SendCampaignListFilter:
					$this->processSendCampaignListFilter($params) ;
					break ;
				case "SEND_EMAIL_CAMPAIGN":
					$this->sendEmailCampaign($params) ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}
	private function processSendCampaignListInfo($params) {
		ob_start() ;
		include (PATH_VIEWS . "campaign/SendCampaignListView.php") ;

		$action_menu = "";

		$var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        $dataReturn	= [];
		$dataReturn['htmlContent'] = $var_screen;
		$dataReturn['action_menu'] = $action_menu;
        $dataReturn['headTitle']  = "Send Campaign List" ;
		$this->sendJsonResponse(Status::Ok,"Load Send Campaign List Info",$dataReturn,$this->type);
    }

    private function processSendCampaignListFilter($params) {
		$clsCustomer	= new CustomerClass($this->db) ;

		$company_type   = $params['company_type'] ;
		$company_name	= $params['company_name'] ;
		$contact    	= $params['contact_name'] ;
		$gift    		= $params['gift'] ;
		$htmlContent  	= "<thead style='background-color: grey;color:white;'>" .
							"<tr>" .
								'<th style="text-align: center;min-width:30px">' .
									'<i class="fa fa-filter" style="font-size:12px;cursor:pointer;" onclick="filterRow(\'sendcampaignlist-row-filter\',this,true);"></i>' .
								'</th>' .
								"<th style='min-width:250px'>Customer Name</th>".
								"<th style='min-width:200px'>Contact name</th>".
								"<th style='min-width:100px'>Designation</th>".
								"<th style='min-width:150px'>Phone</th>".
								"<th style='min-width:150px'>Email</th>".
								"<th style='min-width:30px'></th>".
							"</tr>
							<tr style='left: 0px;' id='sendcampaignlist-row-filter'>
								<td style='min-width:30px' data-field='filter' id='col_filter'>&nbsp;</td>
								<td style='min-width:50px' data-field='number' id='col_number'>
									<input type='text' class='form-control' name='sendcampaignlist-input-filter' id='txtcolcustomername' onkeyup='filterData(this,1);' />
								</td>
								<td style='min-width:100px' data-field='allocation' id='col_allocation'>
									<input type='text' class='form-control' name='sendcampaignlist-input-filter' id='txtcolalcontactname' onkeyup='filterData(this,2);' />
								</td>
								<td style='min-width:200px' data-field='desc' id='col_desc'>
									<input type='text' class='form-control' name='sendcampaignlist-input-filter' id='txtcoldesignation' onkeyup='filterData(this,3);' />
								</td>
								<td style='min-width:200px' data-field='desc' id='col_desc'>
									<input type='text' class='form-control' name='sendcampaignlist-input-filter' id='txtcolphone' onkeyup='filterData(this,4);' />
								</td>
								<td style='min-width:200px' data-field='desc' id='col_desc'>
									<input type='text' class='form-control' name='sendcampaignlist-input-filter' id='txtcolemail' onkeyup='filterData(this,5);' />
								</td>
								<td style='min-width:30px' data-field='filter' id='col_filter'>&nbsp;</td>
								<td style='min-width:30px' data-field='filter' id='col_filter'>&nbsp;</td>
							</tr>
							</thead>
						 <tbody>";
		$rows_cus 	  = $clsCustomer->getSendCampaignCustomerList($company_name, $contact, $gift, $company_type);
		$htmlContent .= $this->convertSendCampaignListToHtmlTable($rows_cus);
		$this->sendJsonResponse(Status::Ok,"",$htmlContent,$this->type);
		unset($list);
	}

	private function convertSendCampaignListToHtmlTable($list) {
		// Define common padding style for table cells
		$cellStyle = "padding-left:8px!important;padding-right:3px!important;padding-top:5px!important;";
		$htmlStr = "";
		foreach($list as $key=>$row) {
			$htmlStr .= '<tr id="sendcampaignlist-row' . $row['COMP_ID'] . '_' . $row['CONTACT_ID'] . '">' .
							'<td style="display:none;">' . $row['COMP_ID'] . '_' . $row['CONTACT_ID'] . '</td>' .
							'<td></td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row['COMP_NAME'] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row['PREFER_NAME'] ?? "") . "</td>" .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row['DESIGNATION'] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row['TELEPHONE'] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row['EMAIL'] ?? "") . '</td>';
			if($row['TYPE'] == 1){
				$htmlStr .= '<td style="' . $cellStyle .'"><a id="linkSendEmail' . $row['CONTACT_ID'] . '" href="javascript:" onclick="popupSendCampaignEmailMessage(\'' . $row['CONTACT_ID'] . '\',' . $row['COMP_ID'] . ', 0, 0, this);">Send Email</a></td>';

			}else{
				$htmlStr .= '<td style="' . $cellStyle .'"><a id="linkSendEmail' . $row['CONTACT_ID'] . '" href="javascript:" onclick="popupSendCampaignEmailMessage(0, 0, \'' . $row['CONTACT_ID'] . '\',' . $row['COMP_ID'] . ', this);">Send Email</a></td>';
			}
			'</tr>';
		}
		$htmlStr .= '</tbody>';
		return $htmlStr;
	}

	private function sendEmailCampaign($params) {
		$cls 	 		= new CustomerContactClass($this->db) ;
		$clsPro	 		= new ProspectContactClass($this->db) ;
		$clsRecp 		= new CampaignRecipientClass($this->db) ;
		$clsComp 		= new CompanyProfileClass($this->db) ;
		$clsGift 		= new CampaignClass($this->db) ;
		$clsGiftDetail  = new CampaignDetailClass($this->db) ;
		$clsImg  		= new CampaignHeaderImageClass($this->db) ;
		if (isset($params['pro_con_id']) && isset($params['pro_id']) && isset($params['cus_con_id']) && isset($params['cus_id'])) {
			$pro_con_id = $params['pro_con_id'];
			$pro_id 	= $params['pro_id'];
			$cus_con_id = $params['cus_con_id'];
			$cus_id 	= $params['cus_id'];
			$from_coy 	= $params['from_coy'];//comp id
			$cc_email 	= $params['cc_email'];
			$send_gift 	= $params['send_gift'];//gift id

			//=================
			if($pro_con_id != 0 && $pro_id != 0){
				$row_pro 	= $clsPro->getPersonContactByContactID($pro_con_id);
				$full_name 	= $row_pro[PersonContactTable::C_PREFER_NAME];
				$email 		= $row_pro[PersonContactTable::C_EMAIL];
				$token 		= $this->generateUnsubscribeToken($pro_con_id, 1) . "&comp_type=1";
				$comp_type  = 1;
				$row_id		= $pro_id . "_" . $pro_con_id;
			}

			if($cus_con_id != 0 && $cus_id != 0){
				$row 		= $cls->getRecord($cus_con_id);
				$full_name 	= $row[CustomerContactTable::C_NAME];
				$email 		= $row[CustomerContactTable::C_EMAIL];
				$token 		= $this->generateUnsubscribeToken($cus_con_id, 2) . "&comp_type=2";
				$comp_type  = 2;
				$row_id		= $cus_id . "_" . $cus_con_id;
			}
			$row_comp 	 = $clsComp->getRecord($from_coy);
			$row_gift 	 = $clsGift->getRecord($send_gift);
			$rows_attach = $clsGiftDetail->getCampaignDetailByGiftID($send_gift);
			//=================

			$coy_id		= $row_comp[CompanyProfileTable::C_ID];
			$coy_name	= $row_comp[CompanyProfileTable::C_NAME];
			$coy_url	= $row_comp[CompanyProfileTable::C_URL];
			$fromEmails	= $row_comp[CompanyProfileTable::C_MAIL_SENDER];
			$sign_path	= $this->getBaseURL() . str_replace("../", "/", $row_comp[CompanyProfileTable::C_SIGNATURE_PATH]);
			// $sign_path	= str_replace("../", "/", $row_comp[CompanyProfileTable::C_SIGNATURE_PATH]);
			$to_email 	= $email;

			$email_content 	= $row_gift[CampaignTable::C_EMAIL_CONTENT];
			$email_thanks 	= $row_gift[CampaignTable::C_EMAIL_THANKS];
			$email_subject 	= $row_gift[CampaignTable::C_EMAIL_SUBJECT];

			$header_path	= $this->getBaseURL() . str_replace("../", "/", $clsImg->getCampaignHeaderImageByGiftIDAndCompID($send_gift, $from_coy));
			// $header_path	= str_replace("../", "/", $clsImg->getCampaignHeaderImageByGiftIDAndCompID($send_gift, $from_coy));

			$lines = "Please visit the following URL to view your request.<br><br>";
			$lines .= $this->getWebPageURL();

			$header_image = '<img align="center" alt="Header Image" border="0" class="center fixedwidth " src="' . $header_path .'" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; display: block;" title="Header Image"/>';
			$sign_image   = '<img align="center" alt="Email Signature" border="0" class="center fixedwidth " src="' . $sign_path .'" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; display: block;" title="Email Signature"/>';

			//=========================================
			//WHATSAPP MESSAGE

			$now = new DateTime();
			$year = $now->format("Y");

			$email_body = file_get_contents(PATH_LIB . "emailCampaign.txt");
			$email_body = str_replace("{TO_NAME}", $full_name, $email_body);
			$email_body = str_replace("{EMAIL_CONTENT}", nl2br($email_content), $email_body);
			$email_body = str_replace("{EMAIL_FOOTER}", nl2br($email_thanks), $email_body);
			$email_body = str_replace("{COPY_RIGHT}", $coy_name, $email_body);
			$email_body = str_replace("{COY_URL}", $coy_url, $email_body);
			$email_body = str_replace("{YEAR}", $year, $email_body);
			$email_body = str_replace("{IMAGE}", $header_image, $email_body);
			$email_body = str_replace("{COMPANY_NAME}", $sign_image, $email_body);

			$unsubscribe_url = $this->getBaseUrl() . "/code/service.php?c=Unsubscribe&action=unsubscribe&turn_off=yes&email=" . urlencode($to_email) . "&token=" . urlencode($token) . '&comp_type=' . $comp_type;
            $email_body = str_replace("{UNSUBSCRIBE_URL}", $unsubscribe_url, $email_body);

			if( trim($to_email) == ""){
				return true;
			}

			$attachment = [];
            foreach($rows_attach as $row_attach){
                array_push($attachment, PATH_CAMPAIGN . "/" . $row_attach[CampaignDetailTable::C_ID] . "/" . $row_attach[CampaignDetailTable::C_DOC_NAME]);
            }

			EmailLog::write("Sending email to " . $full_name . " (" . $to_email . ")");
			$sendMessage = 1;
			$sendMessage = $this->sendEmail($email_subject,
									$email_body,
									$fromEmails,
									explode(";",$cc_email),
									explode(";",$to_email),
									$attachment,
									$coy_id);

			if($sendMessage==0){
				$this->sendJsonResponse(Status::Error, "Failed in sending mail.", "", $this->type);
			} else if($sendMessage==1){
				$datas = [];
				$datas[] = $this->db->fieldValue(CampaignRecipientTable::C_ID, $this->getParamInt($params, 'send_gift', 0));
				$datas[] = $this->db->fieldValue(CampaignRecipientTable::C_PROSPECT_ID, $this->getParamInt($params, 'pro_id', 0));
				$datas[] = $this->db->fieldValue(CampaignRecipientTable::C_PRO_CONTACT_ID, $this->getParamInt($params, 'pro_con_id', 0));
				$datas[] = $this->db->fieldValue(CampaignRecipientTable::C_CUSTOMER_ID, $this->getParamInt($params, 'cus_id', 0));
				$datas[] = $this->db->fieldValue(CampaignRecipientTable::C_CUS_CONTACT_ID, $this->getParamInt($params, 'cus_con_id', 0));
				
				$clsRecp->addRecord($datas);

				$dataReturn['id'] = $row_id;
				$this->sendJsonResponse(Status::Ok, "Email is successfully sent", $dataReturn, $this->type);
			}
		} else {
			$this->sendJsonResponse(Status::Error, "Failed in sending mail.", "", $this->type);
		}
	}

    public function generateUnsubscribeToken($contactId, $type)
    {
		if($type == 1){
			$token = bin2hex(random_bytes(16));
			$quotedToken = $this->db->getConnection()->quote($token);
			$sql = "UPDATE " . PersonContactTable::C_TABLE . " SET " .
				PersonContactTable::C_UNSUBSCRIBE_TOKEN . " = " . $quotedToken . " " .
				"WHERE " . PersonContactTable::C_ID . " = " . intval($contactId);
		}else{
			$token = bin2hex(random_bytes(16));
			$quotedToken = $this->db->getConnection()->quote($token);
			$sql = "UPDATE " . CustomerContactTable::C_TABLE . " SET " .
				CustomerContactTable::C_UNSUBSCRIBE_TOKEN . " = " . $quotedToken . " " .
				"WHERE " . CustomerContactTable::C_CONTACT_ID . " = " . intval($contactId);
		}

        $this->db->executeSql($sql);
        return $token;
    }
}
?>