<?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 . "corporate_gift/CorporateGiftClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CompanyProfileClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftHeaderImageClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftRecipientClass.php") ;
require_once (PATH_MODELS . "admin/SoftwareClass.php") ;

class SendCorporateGiftList 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::SendCorporateGiftListView ;

		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::SendCorporateGiftListView:
					$this->processSendCorporateGiftListInfo($params) ;
					break ;
				case Command::SendCorporateGiftListFilter:
					$this->processSendCorporateGiftListFilter($params) ;
					break ;
				case "SEND_EMAIL_CORPORATE_GIFT":
					$this->sendEmailMooncakeMessage($params) ;
					break ;
				case "UPDATE_CUSTOMER_SCHEDULE":
					$this->processUpdateCustomerSchedule($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 processSendCorporateGiftListInfo($params) {
		ob_start() ;
		include (PATH_VIEWS . "corporate_gift/SendCorporateGiftListView.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 Corporate Gift List" ;
		$this->sendJsonResponse(Status::Ok,"Load Send Corporate Gift List Info",$dataReturn,$this->type);
    }

    private function processSendCorporateGiftListFilter($params) {
		$cls 			= new CustomerClass($this->db) ;

		$company_code	= $params['company_code'] ;
		$company_name	= $params['company_name'] ;
		$contact    	= $params['contact_name'] ;
		$gift    		= $params['gift'] ;

		$rows = $cls->getCorporateGiftList($company_code, $company_name, $contact, $gift);
		$htmlContent = $this->convertSendCorporateGiftListToHtmlTable($rows);
		$this->sendJsonResponse(Status::Ok,"",$htmlContent,$this->type);
		unset($list);
	}

	private function convertSendCorporateGiftListToHtmlTable($list) {
		// Define common padding style for table cells
		$cellStyle = "padding-left:8px!important;padding-right:3px!important;padding-top:5px!important;";
		
		$htmlStr = "<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(\'sendcorporategiftlist-row-filter\',this,true);"></i>' .
						'</th>' .
						"<th style='min-width:50px'>Customer Code</th>".
						"<th style='min-width:250px'>Customer Name</th>".
						"<th style='min-width:200px'>Address</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:100px'>Mobile</th>".
						"<th style='min-width:150px'>Email</th>".
						"<th style='min-width:30px'>Total Gift</th>".
						"<th style='min-width:30px'></th>".
						// "<th style='min-width:30px'></th>".
					"</tr>";
		$htmlStr .= '<tr style="left: 0px;" id="sendcorporategiftlist-row-filter">
						<td style="min-width:30px" data-field="filter" id="col_filter">&nbsp;</td>
						<td style="min-width:50px" data-field="type" id="txtcolcustomercode">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcolcustomercode" onkeyup="filterData(this,1);" />
						</td>
						<td style="min-width:50px" data-field="number" id="col_number">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcolcustomername" onkeyup="filterData(this,2);" />
						</td>
						<td style="min-width:100px" data-field="trans_date" id="col_trans_date">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcoladdress" onkeyup="filterData(this,5);" />
						</td>
						<td style="min-width:100px" data-field="allocation" id="col_allocation">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcolalcontactname" onkeyup="filterData(this,7);" />
						</td>
						<td style="min-width:200px" data-field="desc" id="col_desc">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcoldesignation" onkeyup="filterData(this,8);" />
						</td>
						<td style="min-width:200px" data-field="desc" id="col_desc">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcolphone" onkeyup="filterData(this,9);" />
						</td>
						<td style="min-width:200px" data-field="desc" id="col_desc">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcolmobile" onkeyup="filterData(this,10);" />
						</td>
						<td style="min-width:200px" data-field="desc" id="col_desc">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcolemail" onkeyup="filterData(this,11);" />
						</td>
						<td style="min-width:200px" data-field="desc" id="col_desc">
							<input type="text" class="form-control" name="sendcorporategiftlist-input-filter" id="txtcoltotalmooncake" onkeyup="filterData(this,12);" />
						</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>';
		$htmlStr .=	"</thead> <tbody>";

		foreach($list as $key=>$row) {
			if($row[CustomerContactTable::C_REF_ID] != ""){
				$ref_id = $row[CustomerContactTable::C_REF_ID];
			}else{
				$ref_id = Util::randomKey($row[CustomerContactTable::C_CONTACT_ID]);
			}
			$style = "";
			if($row['SCHEDULED_STATUS'] == 1){
				$style = "color:red;";
			}
			
			$htmlStr .= '<tr id="sendcorporategiftlist-row' . $row[CustomerTable::C_ID] . '_' . $row[CustomerContactTable::C_ID] . '">' .
							'<td style="display:none;">' . $row[CustomerTable::C_ID] . '_' . $row[CustomerContactTable::C_ID] . '</td>' .
							'<td></td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row[CustomerTable::C_CODE] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row[CustomerTable::C_NAME] ?? "") . '</td>' .
							'<td style="' . $cellStyle . 'white-space: pre-line;">' . htmlspecialchars($row[CustomerTable::C_ADDRESS] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row[CustomerContactTable::C_NAME] ?? "") . "</td>" .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row[CustomerContactTable::C_DESIGNATION] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row[CustomerContactTable::C_TELEPHONE] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row[CustomerContactTable::C_MOBILE] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . htmlspecialchars($row[CustomerContactTable::C_EMAIL] ?? "") . '</td>' .
							'<td style="' . $cellStyle . '">' . $row[CorporateGiftRecipientTable::C_GIFT_AMOUNT] . '</td>' .
							'<td style="' . $cellStyle .'"><a style="' . $style . '" id="linkSendEmail' . $row[CustomerContactTable::C_CONTACT_ID] . '" href="javascript:" onclick="popupSendEmailMessage(\'' . $row[CustomerContactTable::C_CONTACT_ID] . '\', \'' . $ref_id . '\',' . $row[CustomerContactTable::C_ID] . ',' . $row[CorporateGiftRecipientTable::C_GIFT_AMOUNT]. ',this);">Send Email</a></td>';
						'</tr>';
		}
		$htmlStr .= '</tbody>';
		return $htmlStr;
	}

	private function sendEmailMooncakeMessage($params) {
		log::write("SEND MOON CAKE");
		$cls 	 = new CustomerContactClass($this->db) ;
		$clsComp = new CompanyProfileClass($this->db) ;
		$clsGift = new CorporateGiftClass($this->db) ;
		$clsImg  = new CorporateGiftHeaderImageClass($this->db) ;
		if (isset($params['id'])) {
			$id 		= $params['id'];
			$ref_id 	= $params['ref_id'];
			$total_mc 	= $params['total_mc'];
			$from_coy 	= $params['from_coy'];//comp id
			$cc_email 	= $params['cc_email'];
			$send_gift 	= $params['send_gift'];//gift id

			//=================
			$row 		= $cls->getRecord($id);
			$row_comp 	= $clsComp->getRecord($from_coy);
			$row_gift 	= $clsGift->getRecord($send_gift);
			//=================

			$full_name 	= $row[CustomerContactTable::C_NAME];
			$email 		= $row[CustomerContactTable::C_EMAIL];

			$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[CorporateGiftTable::C_EMAIL_CONTENT];
			$email_button 	= $row_gift[CorporateGiftTable::C_EMAIL_BUTTON];
			$email_thanks 	= $row_gift[CorporateGiftTable::C_EMAIL_THANKS];
			$email_subject 	= $row_gift[CorporateGiftTable::C_EMAIL_SUBJECT];

			$header_path	= $this->getBaseURL() . str_replace("../", "/", $clsImg->getCorporateGiftHeaderImageByGiftIDAndCompID($send_gift, $from_coy));
			// $header_path	= str_replace("../", "/", $clsImg->getCorporateGiftHeaderImageByGiftIDAndCompID($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
			$shortlisted_url = $this->getBaseURL() . "/web/submitschedule.pzx?ref=" . trim($ref_id) . "&gift=" . $send_gift;

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

			$email_body = file_get_contents(PATH_LIB . "emailDiary.txt");
			$email_body = str_replace("{TO_NAME}", $full_name, $email_body);
			$email_body = str_replace("{EMAIL_CONTENT}", $email_content, $email_body);
			$email_body = str_replace("{EMAIL_BUTTON}", $email_button, $email_body);
			$email_body = str_replace("{EMAIL_FOOTER}", $email_thanks, $email_body);
			$email_body = str_replace("{WEB_URL}", $shortlisted_url, $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);

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

			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),
									null,
									$coy_id);

			if($sendMessage==0){
				$this->sendJsonResponse(Status::Error, "Failed in sending mail.", "", $this->type);
			} else if($sendMessage==1){
				//change status
				$cls->updateStatusSendEmail($id);

				$datas = array();
				$datas['id'] 		 = $id;
				$datas['coy_id'] 	 = $coy_id;
				$datas['ref_id'] 	 = $ref_id;
				$datas['total_mc'] 	 = $total_mc;
				$datas['gift_id']  	 = $send_gift;
				$datas['cc_email'] 	 = $cc_email;
				$datas['send_email'] = true;

				$this->sendJsonResponse(Status::Ok, "Email is successfully sent", $datas, $this->type);
				return;
			}
		} else {
			$this->sendJsonResponse(Status::Error, "Failed in sending mail.", "", $this->type);
			return;
		}
	}

	private function processUpdateCustomerSchedule($params) {
		$cls 		  = new CustomerContactClass($this->db) ;
		$clsSchedule  = new CustomerScheduleClass($this->db) ;
		$clsRecipient = new CorporateGiftRecipientClass($this->db);

		$id 		= $params['id'];
		$ref_id 	= $params['ref_id'];
		$total_mc 	= $params['total_mc'];
		$send_email = $params['send_email'];
		$coy_id 	= $params['coy_id'];
		$cc_email 	= $params['cc_email'];
		$gift_id 	= $params['gift_id'];

		$cls->updateReferenceID($id, $ref_id);

		$name 	= "";
		$phone 	= "";
		$email 	= "";

		$row 	= $cls->getRecord($id);
		$name  	= $row[CustomerContactTable::C_NAME];
		$phone	= $row[CustomerContactTable::C_TELEPHONE];
		$email 	= $row[CustomerContactTable::C_EMAIL];

		$is_exist  = $clsSchedule->isRecordExist($id, $gift_id);
		$recipient = $clsRecipient->getGiftRecipientByRefID($gift_id, $ref_id);
		$gift_amt  = 0;
		if($recipient != null){
			$gift_amt = $recipient[CorporateGiftRecipientTable::C_GIFT_AMOUNT];
		}


		if(!$is_exist) {
			$clsSchedule->insertCustomerSchedule($id, $ref_id, $name, $phone, $email, $total_mc, $send_email, $coy_id, $cc_email, $gift_id, $gift_amt);
		} else {
			if($send_email=="false") {
				$clsSchedule->updateCustomerSchedule($id, $ref_id, $gift_amt);
			} else {
				$clsSchedule->updateSendEmailCustomerSchedule($id, $ref_id, $email, $cc_email, $coy_id, $gift_id, $gift_amt, $total_mc);
			}
		}

		//change status
		if($send_email=="false") {
			$cls->updateStatusSendWhatsapp($id);
		}

		$this->sendJsonResponse(Status::Ok,"","",$this->type);
	}
}
?>