<?php
include (PATH_CONTROLLERS . "Common.php") ;
include (PATH_MODELS . "customer/CustomerContactClass.php");
include (PATH_MODELS . "campaign/CampaignClass.php") ;
include (PATH_MODELS . "campaign/CampaignDetailClass.php") ;
include (PATH_MODELS . "campaign/CampaignHeaderImageClass.php") ;
include (PATH_MODELS . "campaign/CampaignProfileClass.php") ;
include (PATH_MODELS . "campaign/CampaignDeliveryClass.php");
include (PATH_MODELS . "campaign/CampaignRecipientClass.php");

class CampaignMasterEntry 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::CampaignMasterEntryView:
					$this->getView($params) ;
					break ;
				case REQ_GET:
					$this->getCampaignRecord($params);
					break;
				case "SEND_EMAIL_TESTING":
					$this->sendTestingEmail($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 CampaignProfileClass($this->db);
        $rows   = $cls->getActiveCampaignProfileList();
        $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[CampaignProfileTable::C_CODE]."</label>
                                <input type='hidden' class='campaignId' value='".$row[CampaignProfileTable::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='txtCampaignHeaderImage' 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='txtCampaignHeaderImage".$row[CampaignProfileTable::C_ID]."' name='txtCampaignHeaderImage' onchange='encodeImageFileAsURLCampaignHeaderImage(event, ".$row[CampaignProfileTable::C_ID].");'><br>
                                                    <input type='hidden' class='form-control' id='txtCampaignHeaderImageFilename".$row[CampaignProfileTable::C_ID]."'>
                                                    <input type='hidden' class='form-control' id='txtCampaignHeaderImageFileExt".$row[CampaignProfileTable::C_ID]."'>
                                                    <textarea style='display: none;' id='txtCampaignHeaderImageFileBase64".$row[CampaignProfileTable::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='btnCampaignRemoveHeaderImage".$row[CampaignProfileTable::C_ID]."' onclick='removeCampaignHeaderImage(".$row[CampaignProfileTable::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='imgCampaignHeaderImage".$row[CampaignProfileTable::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 . "campaign/CampaignMasterEntryView.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']   = "Campaign Entry" ;
		$this->sendJsonResponse(Status::Ok,"Campaign Entry Info",$dataReturn,$this->type);
	}

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

        $id             = $params['id'];
        $cls            = new CampaignClass($this->db);
        $clsHeader      = new CampaignHeaderImageClass($this->db);
        $clsDetail      = new CampaignDetailClass($this->db);
        $row            = $cls->getRecord($id);
        $rowsHeader     = $clsHeader->getCampaignHeaderImageByGiftID($id);
        $rowsDetail     = $clsDetail->getCampaignDetailByGiftID($id);

        $datas          = array();
        if (!is_null($row) && count($row) > 0) {
            $datas['id']            = $row[CampaignTable::C_ID];
            $datas['name']          = $row[CampaignTable::C_NAME];
            $datas['active']        = $row[CampaignTable::C_STATUS];
            $datas['date_from']     = ($row[CampaignTable::C_DELIVERY_DATE_FROM] == NULL_DATE . ".000") ? '' : date_create($row[CampaignTable::C_DELIVERY_DATE_FROM])->format('Y-m-d');
            $datas['date_to']       = ($row[CampaignTable::C_DELIVERY_DATE_TO] == NULL_DATE . ".000") ? '' : date_create($row[CampaignTable::C_DELIVERY_DATE_TO])->format('Y-m-d');

            $datas['email_subject'] = $row[CampaignTable::C_EMAIL_SUBJECT];
            $datas['email_content'] = $row[CampaignTable::C_EMAIL_CONTENT];
            $datas['email_footer']  = $row[CampaignTable::C_EMAIL_THANKS];

            $html           = "";
            $html_attach    = "";
            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[CampaignProfileTable::C_CODE]."</label>
                                    <input type='hidden' class='campaignId' value='".$rowHeader[CampaignProfileTable::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='txtCampaignHeaderImage' 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='txtCampaignHeaderImage".$rowHeader[CampaignProfileTable::C_ID]."' name='txtCampaignHeaderImage' onchange='encodeImageFileAsURLCampaignHeaderImage(event, ".$rowHeader[CampaignProfileTable::C_ID].");'><br>
                                                        <input type='hidden' class='form-control' id='txtCampaignHeaderImageFilename".$rowHeader[CampaignProfileTable::C_ID]."'>
                                                        <input type='hidden' class='form-control' id='txtCampaignHeaderImageFileExt".$rowHeader[CampaignProfileTable::C_ID]."'>
                                                        <textarea style='display: none;' id='txtCampaignHeaderImageFileBase64".$rowHeader[CampaignProfileTable::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='btnCampaignRemoveHeaderImage".$rowHeader[CampaignProfileTable::C_ID]."' onclick='removeCampaignHeaderImage(".$rowHeader[CampaignProfileTable::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[CampaignHeaderImageTable::C_IMAGE_PATH] == NULL){
                                                        $html .= "<img id='imgCampaignHeaderImage".$rowHeader[CampaignProfileTable::C_ID]."' src='../web/picture/default/default.png' alt='logo' style='max-height: 160px;width:200px;object-fit: contain;'>";
                                                    }else{
                                                        $html .= "<img id='imgCampaignHeaderImage".$rowHeader[CampaignProfileTable::C_ID]."' src='".$rowHeader[CampaignHeaderImageTable::C_IMAGE_PATH]."' alt='logo' style='max-height: 160px;width:200px;object-fit: contain;'>";
                                                    }
                                                    $html .= "</div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>";
                }
            };
            if(!is_null($rowsDetail) && count($rowsDetail) > 0 ){
                $attach_idx = 0;
                foreach($rowsDetail as $key => $rowDetail){
                    $html_attach .= '<tr id="row_attach_'.($key + 1).'">
                                        <td id="col_attachment'.($key + 1).'">
                                            <a title="View Attachment" style="color:green; padding: 5px !important;" href="javascript:" onclick="downloadCampaignFile('.$rowDetail[CampaignDetailTable::C_ID].', \''.$rowDetail[CampaignDetailTable::C_DOC_NAME].'\')">'.$rowDetail[CampaignDetailTable::C_DOC_NAME].'</a>
                                        </td>
                                        <td id="col_action'.($key + 1).'" style="padding: 5px !important;">
                                            <button type="button" class="btn btn btn-icon btn-danger btn-sm btn-icon-md" onclick="removeCampaignAttachment('.$rowDetail[CampaignDetailTable::C_DETAIL_ID].', '.($key + 1).');"><i class="fa fa-trash-o"></i></button>
                                        </td>
                                    </tr>';
                    $attach_idx = $key + 1;
                }
                $attach_idx++;
            }
            $attach_idx = 1;
            $html_attach .= '<tr id="row_attach_'.$attach_idx.'">
                                <td id="col_attachment'.$attach_idx.'">
                                    <input type="file" class="form-control" id="txtCampaignAttachment'.$attach_idx.'" name="txtCampaignAttachment'.$attach_idx.'" onchange="onCampaignAttachmentUpload(this, '.$attach_idx.');" />
                                            <input type="hidden" class="form-control" id="txtCampaignAttachmentFilename'.$attach_idx.'"/>
                                </td>
                                <td id="col_action'.$attach_idx.'" style="padding: 5px !important;">
                                    <button type="button" class="btn btn btn-icon btn-success btn-sm btn-icon-md" onclick="uploadCampaignAttachment('.$attach_idx.');"><i class="fa fa-upload"></i></button>
                                </td>
                            </tr>';

            $datas['header']    = $html;
            $datas['attach']    = $html_attach;
        }
        include(PATH_VIEWS . "campaign/CampaignMasterEntryView.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 sendTestingEmail($params) {
		$clsComp        = new CompanyProfileClass($this->db) ;
		$clsGift        = new CampaignClass($this->db) ;
		$clsGiftDetail  = new CampaignDetailClass($this->db) ;
		$clsImg         = new CampaignHeaderImageClass($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);
            $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]);

			$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
			$shortlisted_url = $this->getBaseURL() . "*";

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

			$email_body = file_get_contents(PATH_LIB . "emailCampaign.txt");
			$email_body = str_replace("{EMAIL_CONTENT}", $email_content, $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);

            $unsubscribe_url = "*";
            $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 testing email to " . $to_email);
			$sendMessage = 1;
			$sendMessage = $this->sendEmail($email_subject,
									$email_body,
									$fromEmails,
									null,
									explode(";",$to_email),
									$attachment,
									$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;
		}
	}
}
