<?php
include (PATH_CONTROLLERS . "Common.php") ;
include (PATH_MODELS . "customer/CustomerContactClass.php");
include (PATH_MODELS . "corporate_gift/CorporateGiftClass.php") ;
include (PATH_MODELS . "corporate_gift/CorporateGiftDetailClass.php") ;
include (PATH_MODELS . "corporate_gift/CorporateGiftHeaderImageClass.php") ;
include (PATH_MODELS . "corporate_gift/CompanyProfileClass.php") ;
include (PATH_MODELS . "corporate_gift/CorporateGiftDeliveryClass.php");
include (PATH_MODELS . "corporate_gift/CorporateGiftRecipientClass.php");

class CorporateGiftMasterEntry extends GLBase {
	private $type = "" ;
	private $user ;

	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->user) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$this->loadSetting() ;
			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::CorporateGiftMasterEntryView:
					$this->getView($params) ;
					break ;
				case REQ_GET:
					$this->getCorporateGiftRecord($params);
					break;
				case "SEND_EMAIL_TESTING":
					$this->sendTestingEmail($params) ;
					break ;	
				case "C_GET_CUSTOMER_CONTACTS":
					$this->getCustomerContact($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 getView($params) {
		ob_start() ;
        $cls    = new CompanyProfileClass($this->db);
        $rows   = $cls->getActiveCompanyProfileList();
        $html   = "";
        if(!is_null($rows) && count($rows) > 0 ){
            foreach($rows as $row){
                $html .= "<div class='col-lg-4 companyEmailHeaderImage'>
                            <div class='form-group row'>
                                <label class='col-lg-2 col-form-label'>".$row[CompanyProfileTable::C_CODE]."</label>
                                <input type='hidden' class='companyProfileId' value='".$row[CompanyProfileTable::C_ID]."'>
                                <div class='col-lg-10'>
                                    <form>
                                        <div class='form-group col-sm-12' style='padding-left:0px;margin-left:0px;'>
                                            <div class='col-sm-6' style='padding-left:0px;'>
                                                <label for='txtCorporateGiftHeaderImage' class='col-sm-12' style='padding: 0px;'>Email Header Image:</label>
                                                <div class='col-sm-12' style='padding: 0px;'>
                                                    <input type='file' class='form-control' id='txtCorporateGiftHeaderImage".$row[CompanyProfileTable::C_ID]."' name='txtCorporateGiftHeaderImage' onchange='encodeImageFileAsURLCorporateGiftHeaderImage(event, ".$row[CompanyProfileTable::C_ID].");'><br>
                                                    <input type='hidden' class='form-control' id='txtCorporateGiftHeaderImageFilename".$row[CompanyProfileTable::C_ID]."'>
                                                    <input type='hidden' class='form-control' id='txtCorporateGiftHeaderImageFileExt".$row[CompanyProfileTable::C_ID]."'>
                                                    <textarea style='display: none;' id='txtCorporateGiftHeaderImageFileBase64".$row[CompanyProfileTable::C_ID]."' cols='30' rows='10'></textarea>
                                                    <div class='row' style='margin-left: 0px;'>
                                                        <button class='col-sm-2 btn btn-secondary' style='background-color:grey;color:white;margin-right: 10px;min-width: 100px;max-width: 100px' type='button' id='btnCorporateGiftRemoveHeaderImage".$row[CompanyProfileTable::C_ID]."' onclick='removeCorporateGiftHeaderImage(".$row[CompanyProfileTable::C_ID].");'>Remove</button>
                                                    </div>
                                                    <div style='margin-top:10px;display:none;'>
                                                        <div><span id='setting_upload_mesg'>Uploading file .....</span></div>
                                                        <div style='margin-top:10px'><img src='image/uploading.gif'></div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class='col-sm-6' style='max-width: 200px;padding: 0;'>
                                                <div class='col-sm-12' style='padding: 0px;'>
                                                    <img id='imgCorporateGiftHeaderImage".$row[CompanyProfileTable::C_ID]."' src='../web/picture/default/default.png' alt='logo' style='max-height: 160px;width:200px;object-fit: contain;'>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>";
            }
        }


		include (PATH_VIEWS . "corporate_gift/CorporateGiftMasterEntryView.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['emailHeader'] = $html;
        $dataReturn['headTitle']   = "Corporate Gift Entry" ;
		$this->sendJsonResponse(Status::Ok,"Corporate Gift Entry Info",$dataReturn,$this->type);
	}

	private function getCorporateGiftRecord($params) {
        ob_start();

        $id             = $params['id'];
        $cls            = new CorporateGiftClass($this->db);
        $clsDetail      = new CorporateGiftDetailClass($this->db);
        $clsDelivery    = new CorporateGiftDeliveryClass($this->db);
        $clsHeader      = new CorporateGiftHeaderImageClass($this->db);
        $clsRecipient   = new CorporateGiftRecipientClass($this->db);
        $row            = $cls->getRecord($id);
        $rowsDetail     = $clsDetail->getCorporateGiftDetailByGiftID($id);
        $rowsDeliveries = $clsDelivery->getCorporateGiftDeliveryByGiftID($id);
        $rowsHeader     = $clsHeader->getCorporateGiftHeaderImageByGiftID($id);
        $rowsRecipient  = $clsRecipient->getRecipientByGiftID($id);
        $datas          = array();
        if (!is_null($row) && count($row) > 0) {
            $datas['id']            = $row[CorporateGiftTable::C_ID];
            $datas['name']          = $row[CorporateGiftTable::C_NAME];
            $datas['active']        = $row[CorporateGiftTable::C_STATUS];
            $datas['date_from']     = ($row[CorporateGiftTable::C_DELIVERY_DATE_FROM] == NULL_DATE . ".000") ? '' : date_create($row[CorporateGiftTable::C_DELIVERY_DATE_FROM])->format('Y-m-d');
            $datas['date_to']       = ($row[CorporateGiftTable::C_DELIVERY_DATE_TO] == NULL_DATE . ".000") ? '' : date_create($row[CorporateGiftTable::C_DELIVERY_DATE_TO])->format('Y-m-d');
            $datas['cut_off']       = ($row[CorporateGiftTable::C_CUTOFF_DATE] == NULL_DATE . ".000") ? '' : date_create($row[CorporateGiftTable::C_CUTOFF_DATE])->format('Y-m-d');

            $datas['email_subject'] = $row[CorporateGiftTable::C_EMAIL_SUBJECT];
            $datas['email_button']  = $row[CorporateGiftTable::C_EMAIL_BUTTON];
            $datas['email_content'] = $row[CorporateGiftTable::C_EMAIL_CONTENT];
            $datas['email_footer']  = $row[CorporateGiftTable::C_EMAIL_THANKS];
            $item_arrays    = [];
            if(!is_null($rowsDetail) && count($rowsDetail) > 0){
                foreach($rowsDetail as $rowDetail){
                    $datas_item = [];  
                    $datas_item['item_id']       = $rowDetail[CorporateGiftDetailTable::C_DETAIL_ID];
                    $datas_item['item_name']     = $rowDetail[CorporateGiftDetailTable::C_ITEM_NAME];
    
                    $picture_name                = explode("/", $rowDetail[CorporateGiftDetailTable::C_ITEM_IMAGE]);
                    $picture_name                = explode(".", end($picture_name))[0];
                    $datas_item['item_filename'] = $picture_name;
                    $datas_item['path_item']     = str_replace(PATH_CODE,"",$rowDetail[CorporateGiftDetailTable::C_ITEM_IMAGE]);
    
                    array_push($item_arrays, $datas_item);
                }
                $datas['items']         = $item_arrays;
            }

            $delivery_arrays    = [];
            if(!is_null($rowsDeliveries) && count($rowsDeliveries) > 0){
                foreach($rowsDeliveries as $rowDelivery){
                    $datas_delivery = [];  
                    $datas_delivery['delivery_id']      = $rowDelivery[CorporateGiftDeliveryTable::C_DELIVERY_ID];
                    $datas_delivery['delivery_date']    = $rowDelivery[CorporateGiftDeliveryTable::C_DATE];
                    $datas_delivery['delivery_time1']   = $rowDelivery[CorporateGiftDeliveryTable::C_TIME1];
                    $datas_delivery['delivery_time2']   = $rowDelivery[CorporateGiftDeliveryTable::C_TIME2];

                    array_push($delivery_arrays, $datas_delivery);
                }
                $datas['delivery']  = $delivery_arrays;
            }

            $html   = "";
            if(!is_null($rowsHeader) && count($rowsHeader) > 0 ){
                foreach($rowsHeader as $rowHeader){
                    $html .= "<div class='col-lg-4 companyEmailHeaderImage'>
                                <div class='form-group row'>
                                    <label class='col-lg-2 col-form-label'>".$rowHeader[CompanyProfileTable::C_CODE]."</label>
                                    <input type='hidden' class='companyProfileId' value='".$rowHeader[CompanyProfileTable::C_ID]."'>
                                    <div class='col-lg-10'>
                                        <form>
                                            <div class='form-group col-sm-12' style='padding-left:0px;margin-left:0px;'>
                                                <div class='col-sm-6' style='padding-left:0px;'>
                                                    <label for='txtCorporateGiftHeaderImage' class='col-sm-12' style='padding: 0px;'>Email Header Image:</label>
                                                    <div class='col-sm-12' style='padding: 0px;'>
                                                        <input type='file' class='form-control' id='txtCorporateGiftHeaderImage".$rowHeader[CompanyProfileTable::C_ID]."' name='txtCorporateGiftHeaderImage' onchange='encodeImageFileAsURLCorporateGiftHeaderImage(event, ".$rowHeader[CompanyProfileTable::C_ID].");'><br>
                                                        <input type='hidden' class='form-control' id='txtCorporateGiftHeaderImageFilename".$rowHeader[CompanyProfileTable::C_ID]."'>
                                                        <input type='hidden' class='form-control' id='txtCorporateGiftHeaderImageFileExt".$rowHeader[CompanyProfileTable::C_ID]."'>
                                                        <textarea style='display: none;' id='txtCorporateGiftHeaderImageFileBase64".$rowHeader[CompanyProfileTable::C_ID]."' cols='30' rows='10'></textarea>
                                                        <div class='row' style='margin-left: 0px;'>
                                                            <button class='col-sm-2 btn btn-secondary' style='background-color:grey;color:white;margin-right: 10px;min-width: 100px;max-width: 100px' type='button' id='btnCorporateGiftRemoveHeaderImage".$rowHeader[CompanyProfileTable::C_ID]."' onclick='removeCorporateGiftHeaderImage(".$rowHeader[CompanyProfileTable::C_ID].");'>Remove</button>
                                                        </div>
                                                        <div style='margin-top:10px;display:none;'>
                                                            <div><span id='setting_upload_mesg'>Uploading file .....</span></div>
                                                            <div style='margin-top:10px'><img src='image/uploading.gif'></div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class='col-sm-6' style='max-width: 200px;padding: 0;'>
                                                    <div class='col-sm-12' style='padding: 0px;'>";
                                                    if($rowHeader[CorporateGiftHeaderImageTable::C_IMAGE_PATH] == NULL){
                                                        $html .= "<img id='imgCorporateGiftHeaderImage".$rowHeader[CompanyProfileTable::C_ID]."' src='../web/picture/default/default.png' alt='logo' style='max-height: 160px;width:200px;object-fit: contain;'>";
                                                    }else{
                                                        $html .= "<img id='imgCorporateGiftHeaderImage".$rowHeader[CompanyProfileTable::C_ID]."' src='".$rowHeader[CorporateGiftHeaderImageTable::C_IMAGE_PATH]."' alt='logo' style='max-height: 160px;width:200px;object-fit: contain;'>";
                                                    }
                                                    $html .= "</div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>";
                }
            }

            $recipient_arrays    = [];
            if(!is_null($rowsRecipient) && count($rowsRecipient) > 0){
                foreach($rowsRecipient as $rowRecipient){
                    $datas_recipient = [];  
                    $datas_recipient['customer_name']   = $rowRecipient[CustomerTable::C_NAME];
                    $datas_recipient['customer_id']     = $rowRecipient[CorporateGiftRecipientTable::C_CUSTOMER_ID];
                    $datas_recipient['contact_name']    = $rowRecipient[CustomerContactTable::C_PREFER_NAME];
                    $datas_recipient['contact_id']      = $rowRecipient[CorporateGiftRecipientTable::C_CONTACT_ID];
                    $datas_recipient['gift_amount']     = $rowRecipient[CorporateGiftRecipientTable::C_GIFT_AMOUNT];

                    array_push($recipient_arrays, $datas_recipient);
                }
                $datas['recipient'] = $recipient_arrays;
            }
            $datas['header']    = $html;
        }
        include(PATH_VIEWS . "corporate_gift/CorporateGiftMasterEntryView.php");

        $var_screen = str_replace("[index]", $params['index'], Util::minifyHtml(ob_get_clean()));

        $dataReturn = array();
        $dataReturn['htmlContent']  = $var_screen;
        $dataReturn['headTitle']    = "Customer Entry";
        $dataReturn['headerData']   = $datas;

        $this->sendJsonResponse(Status::Ok, "Customer Entry", $dataReturn, $this->type);
        unset($cls);
	}

    private function getCustomerContact($params){
        $cls  = new CustomerContactClass($this->db);
        $rows = $cls->getActiveCustomerContact($params['id']);

        $vls[] = array ('code'=>"",'desc'=>"-- Select Contact --") ;
        foreach($rows as $row){
            $vls[] = array ('code'=>$row[CustomerContactTable::C_CONTACT_ID],'desc'=>$row[CustomerContactTable::C_PREFER_NAME]) ;
        }

        $option =  Util::createOptionValue($vls);
        $this->sendJsonResponse(Status::Ok,"Corporate Gift Entry Info",$option,$this->type);
    }

    private function sendTestingEmail($params) {
		$clsComp = new CompanyProfileClass($this->db) ;
		$clsGift = new CorporateGiftClass($this->db) ;
		$clsImg  = new CorporateGiftHeaderImageClass($this->db) ;

		if (isset($params['id'])) {
			$send_gift 	= $params['id'];
			$from_coy	= $params['email_from'];
			$to_email 	= $params['email_to'];

			//=================
			$row_comp 	= $clsComp->getRecord($from_coy);
			$row_gift 	= $clsGift->getRecord($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]);

			$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() . "*";

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

			$email_body = file_get_contents(PATH_LIB . "emailDiary.txt");
			$email_body = str_replace("{EMAIL_CONTENT}", nl2br($email_content), $email_body);
			$email_body = str_replace("{EMAIL_BUTTON}", $email_button, $email_body);
			$email_body = str_replace("{EMAIL_FOOTER}", nl2br($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 testing email to " . $to_email);
			$sendMessage = 1;
			$sendMessage = $this->sendEmail($email_subject,
									$email_body,
									$fromEmails,
									null,
									explode(";",$to_email),
									null,
									$coy_id);
			if($sendMessage==0){
				$this->sendJsonResponse(Status::Error, "Failed in sending mail.", "", $this->type);
                return;
			} else if($sendMessage==1){
				$this->sendJsonResponse(Status::Ok, "Email is successfully sent", "", $this->type);
                return;
			}
		} else {
			$this->sendJsonResponse(Status::Error, "Failed in sending mail.", "", $this->type);
            return;
		}
	}
}
