<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once(PATH_MODELS . "campaign/CampaignClass.php");
require_once(PATH_MODELS . "campaign/CampaignDetailClass.php");
require_once(PATH_MODELS . "campaign/CampaignHeaderImageClass.php");
require_once(PATH_MODELS . "campaign/CampaignDeliveryClass.php");
require_once(PATH_MODELS . "campaign/CampaignRecipientClass.php");
require_once(PATH_LIB    . 'ImageResize.php');
require '../vendor/autoload.php';

class CampaignMaster 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() ;
			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::CampaignMasterView:
					$this->getView($params) ;
					break ;
                case Command::CampaignMasterListView:
                    $this->getCampaignList($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params);
                    break;
                case REQ_DELETE:
                    $this->deleteRecord($params);
                    break;
                case "DELETE_CAMPAIGN_PROFILE_LOGO":
                    $this->deleteCampaignlogo($params);
                    break;
                case Command::CampaignProfileEntryUpload:
                    $this->uploadCampaignAttachment($params);
                    break;
                case Command::CampaignDeleteAttachment:
                    $this->deleteDocument($params);
                    break;
                case Command::CampaignDownloadAttachment:
                    $this->processDownloadFile($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() ;
		include (PATH_VIEWS . "campaign/CampaignMasterView.php") ;

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

    private function getCampaignList($params) {
        $cls = new CampaignClass($this->db);

        $sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                case "col_name":
                    $orderby = CampaignTable::C_NAME . " " . $sort[1];
                    break;
                case "col_status":
                    $orderby = CampaignTable::C_STATUS . " " . $sort[1];
                    break;
                default:
                    $orderby = CampaignTable::C_NAME . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = CampaignTable::C_NAME . " asc";
        }

        $rows  = $cls->getCampaignList($orderby);
        $lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $list = [
                    "id"        => $row[CampaignTable::C_ID],
                    "name"      => htmlentities($row[CampaignTable::C_NAME]),
                    "status"    => ($row[CampaignTable::C_STATUS] == 1 ? 'Active' : 'Inactive'),
                ];

                array_push($lists, $list);
            }
        }
        $lists = json_encode($lists);

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

    private function addRecord($params) {
        $cls            = new CampaignClass($this->db);
        $clsHeaderImage = new CampaignHeaderImageClass($this->db);

        $datas        = array();
        $modifyby     = $_SESSION[SE_USERID];
        $modifydate   = date_create('now')->format('Y-m-d H:i:s');
        $ws           = $_SESSION[SE_REMOTE_IP];
        $datas[] = $this->db->fieldValue(CampaignTable::C_NAME, $this->getParam($params, 'name', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_STATUS, $this->getParamInt($params, 'active', 0));
        $datas[] = $this->db->fieldValue(CampaignTable::C_EMAIL_SUBJECT, $this->getParam($params, 'email_subject', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_EMAIL_CONTENT, $this->getParam($params, 'email_content', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_EMAIL_THANKS, $this->getParam($params, 'email_footer', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_DELIVERY_DATE_FROM, $this->getParam($params, 'date_from', NULL_DATE));
        $datas[] = $this->db->fieldValue(CampaignTable::C_DELIVERY_DATE_TO, $this->getParam($params, 'date_to', NULL_DATE));

        $datas[] = $this->db->fieldValue(CampaignTable::C_WS_ID, $ws);
        $datas[] = $this->db->fieldValue(CampaignTable::C_MODIFY_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CampaignTable::C_CREATE_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CampaignTable::C_MODIFY_DATE, $modifydate);
        $datas[] = $this->db->fieldValue(CampaignTable::C_CREATE_DATE, $modifydate);

        try {
            $this->db->beginTran();
            $exist          = $cls->getExistingRecords($this->getParam($params, 'code', ""));
            if (!is_null($exist)) {
                $this->sendJsonResponse(Status::Error, "campaign already exist.", "", $this->type);
            } else {                
                $id = $cls->addRecord($datas);
                if($id > 0){
                    if(isset($params['header_images'])){
                        $header_images = json_decode($params['header_images'], true);
                        foreach($header_images as $header_image){
                            $datas_header   = [];
                            $datas_header[] = $this->db->fieldValue(CampaignHeaderImageTable::C_ID, $id);
                            $datas_header[] = $this->db->fieldValue(CampaignHeaderImageTable::C_COMPANY_ID, $header_image['comp_id']);
                            $header_data    = $this->saveCampaignImage($id, $header_image['header_file_base64'], $header_image['header_file_ext'], PATH_CORPORATE_GIFT_HEADER, 'campaign_header_' . $id . $header_image['comp_id']);
                            $datas_header[] = $this->db->fieldValue(CampaignHeaderImageTable::C_IMAGE_PATH, str_replace(PATH_CODE,"",$header_data ?? ''));
                            $clsHeaderImage->addRecord($datas_header);
                        }
                    }
                }
                $content['id']       = $id;
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok, "Successfully inserted into system", $content, $this->type);
            }
        } catch (Exception $e) {
            $this->db->rollbackTran() ;	
            Log::write('[Campaign]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error, "Sorry, there is a error in database operation.", "", $this->type);
        }
        unset($cls);
    }

    private function updateRecord($params) {
        $cls            = new CampaignClass($this->db);
        $clsHeaderImage = new CampaignHeaderImageClass($this->db);

        $datas                      = array();
        $modifyby                   = $_SESSION[SE_USERID];
        $modifydate                 = date_create('now')->format('Y-m-d H:i:s');
        $ws                         = $_SESSION[SE_REMOTE_IP];

        $datas[] = $this->db->fieldValue(CampaignTable::C_NAME, $this->getParam($params, 'name', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_STATUS, $this->getParamInt($params, 'active', 0));
        $datas[] = $this->db->fieldValue(CampaignTable::C_EMAIL_SUBJECT, $this->getParam($params, 'email_subject', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_EMAIL_CONTENT, $this->getParam($params, 'email_content', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_EMAIL_THANKS, $this->getParam($params, 'email_footer', ''));
        $datas[] = $this->db->fieldValue(CampaignTable::C_DELIVERY_DATE_FROM, $this->getParam($params, 'date_from', NULL_DATE));
        $datas[] = $this->db->fieldValue(CampaignTable::C_DELIVERY_DATE_TO, $this->getParam($params, 'date_to', NULL_DATE));

        $datas[] = $this->db->fieldValue(CampaignTable::C_WS_ID, $ws);
        $datas[] = $this->db->fieldValue(CampaignTable::C_MODIFY_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CampaignTable::C_CREATE_BY, $modifyby);
        $datas[] = $this->db->fieldValue(CampaignTable::C_MODIFY_DATE, $modifydate);
        $datas[] = $this->db->fieldValue(CampaignTable::C_CREATE_DATE, $modifydate);

        try {
            $this->db->beginTran();
            $exist  = $cls->getExistingRecords($this->getParam($params, 'code', ""), $params['id']);
            if (!is_null($exist)) {
                $this->sendJsonResponse(Status::Error, "campaign already exist.", "", $this->type);
            } else {                
                $id = $params['id'];
                $cls->updateRecord($id,$datas);
                $exist_header = $clsHeaderImage->getCampaignIDHaveHeaderImage($id) ?? [];
                if(isset($params['header_images'])){
                    $header_images = json_decode($params['header_images'], true);
                    foreach($header_images as $header_image){
                        if(!in_array($header_image['comp_id'], $exist_header)){
                            $datas_header   = [];                        
                            $header_data    = $this->saveCampaignImage($id, $header_image['header_file_base64'], $header_image['header_file_ext'], PATH_CORPORATE_GIFT_HEADER, 'campaign_header_' . $id . $header_image['comp_id']);
                            $datas_header[] = $this->db->fieldValue(CampaignHeaderImageTable::C_ID, $id);
                            $datas_header[] = $this->db->fieldValue(CampaignHeaderImageTable::C_COMPANY_ID, $header_image['comp_id']);
                            $datas_header[] = $this->db->fieldValue(CampaignHeaderImageTable::C_IMAGE_PATH, str_replace(PATH_CODE,"",$header_data ?? ''));
                            $clsHeaderImage->addRecord($datas_header);
                        }else{
                            if($header_image['header_file_base64'] != "" && $header_image['header_filename'] != ""){
                                $header_data    = $this->saveCampaignImage($id, $header_image['header_file_base64'], $header_image['header_file_ext'], PATH_CORPORATE_GIFT_HEADER, 'campaign_header_' . $id . $header_image['comp_id']);
                                $clsHeaderImage->updateHeaderImageByCompIDAndGiftID(str_replace(PATH_CODE,"",$header_data ?? ''), $id, $header_image['comp_id']);
                            }
                        }
                    }
                }
            }
            $this->db->commitTran();
            $this->sendJsonResponse(Status::Ok, "Successfully updated into system", '', $this->type);
        } catch (Exception $e) {
            $this->db->rollbackTran() ;	
            Log::write('[Campaign]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error, "Sorry, there is a error in database operation.", "", $this->type);
        }
        unset($cls);
    }

    private function deleteRecord($params) {
        $cls        = new CampaignClass($this->db);
        $clsDetail  = new CampaignDetailClass($this->db);
        $clsHeader  = new CampaignHeaderImageClass($this->db);

        $id =  $this->getParamInt($params, 'id', 0);
        if ($id == 0) {
            $this->sendJsonResponse(Status::Error, "Invalid ID.", "", $this->type);
            return;
        }
        try {
            $this->db->beginTran();
            $cls->deleteRecord($id);
            $clsDetail->deleteCampaignDetailByGiftID($id);
            $clsHeader->deleteCampaignHeaderImageByGiftID($id);
            $this->db->commitTran();
            $this->sendJsonResponse(Status::Ok, "Successfully delete campaign from system.", "", $this->type);
            return;
        } catch (Exception $e) {
            $this->db->rollbackTran() ;
            if($e->getMessage() == Message::DB_ERR_DELETE_USED){
                $this->sendJsonResponse(Status::Error, Message::DB_ERR_DELETE_USED,"",$this->type);
            }else{
                Log::write('[Campaign] ' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting campaign from the system.","",$this->type);
            }
            return;
        }

        unset($cls);
    }

    public function saveCampaignImage($id, $base64file, $extension, $image_path, $image_name)
    {
		$newfile = "";
        if($base64file!="" || $base64file!=null){
            $path = $image_path . $id . "/";
            $newfile = $image_name.".".$extension;

            if (!file_exists($path)) {
                mkdir($path, 1777, true);
            }
            if (file_exists($path.$newfile)) {
                if (file_exists($path.$newfile))
                    unlink($path.$newfile) ;
            }

            $data= $base64file;
            $type= $extension;
            if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
                $data = substr($data, strpos($data, ',') + 1);
                $type = strtolower($type[1]); // jpg, png, gif

                if (!in_array($type, [ 'jpg', 'jpeg', 'png', 'gif' ])) {
                    Log::write('invalid image type');
					$mesg = "invalid image type";
                    return "";
                }
                $data = str_replace( ' ', '+', $data );
                $data = base64_decode($data);

                if ($data === false) {
                    Log::write('base64_decode failed');
					$mesg = "base64_decode failed.";
                    return "";
                }

                file_put_contents($path . $newfile, $data);
            } else {
                Log::write('did not match data URI with image data');
				$mesg = "did not match data URI with image data.";
                return "";
            }
            try {
                return  $path . $newfile ;
            } catch (Exception $e){
                Log::write('[attachment]' . $e->getMessage());
				$mesg = $e->getMessage();
				throw new Exception($mesg, 1);
            }
        }
	}

    private function deleteCampaignlogo($params)
	{
        $path = PATH_CODE.$params['path'];

        if (file_exists($path))
				unlink($path) ;

		$assetpicturepath = "../web/picture/default/default.png";
		$data=[];
		$data['src'] = $assetpicturepath;

		$this->sendJsonResponse(Status::Ok,"Picture successfully removed from the system.",$data,$this->type) ;
	}

    function deleteFolder($path) {
        if (!is_dir($path)) {
            return false;
        }

        $files = array_diff(scandir($path), ['.', '..']);

        foreach ($files as $file) {
            $fullPath = $path . DIRECTORY_SEPARATOR . $file;

            if (is_dir($fullPath)) {
                $this->deleteFolder($fullPath);
            } else {
                unlink($fullPath);
            }
        }

        return rmdir($path);
    }

    private function uploadCampaignAttachment($params) {//this function is shared by upload attachment during issue nad Attachment tab
        $cls             = new CampaignDetailClass($this->db) ;
        $clsHeader       = new CampaignClass($this->db);

        $id              = $_REQUEST["campaign_id"];
        $idx             = $_REQUEST["idx"];
        $attach_field    = isset($_REQUEST["attach_field"]) ? $_REQUEST["attach_field"] : "";
        $err             = "";
        $centreDocReturn = "";

        $limitFilesize  = 5000 * 1024;   //5000kb
        if (!isset($_FILES)) {
            $err_temp = "No upload file found." ;
            echo Status::Error . "|" . $_REQUEST['type'] . "|" . $err_temp ;
            return ;
        }

        $fileNames = "";
        $size      = 0;
        $fileNames = $_FILES[$attach_field]["name"];
        $tmpNames  = $_FILES[$attach_field]["tmp_name"];
        $size      = $_FILES[$attach_field]['size'];

        //check size
        if($size <= 0) {
            $err = "Missing upload file.";

            echo Status::Error . "**" . $err;
            Log::write("[CampaignMaster]" . $err);
            return;
        }

        $docfile = "" ;
        $docfile       = basename($fileNames);

        $pi      = pathinfo($docfile);
        $ext     = $pi['extension'];
        $exts    = array("png","jpg","jpeg","doc","docx","xls","xlsx","xlsb","pdf") ;
        if (Util::validFileExt($ext,$exts) == false) {
            $err = "Unsupported upload file type" ;
            echo Status::Error . "**" . $err;
            Log::write("[CampaignMaster]" . $err);
            return;
        }

        log::write($size);
        log::write($limitFilesize);
        $imgExts = array("png","jpg","jpeg");
        $docExts = array("doc","docx","xls","xlsx","xlsb","pdf");
        if (Util::validFileExt($ext,$docExts) && $size > $limitFilesize) {
            $err = "Upload file over limit. Upload file size must be less than ". $limitFilesize ."KB." ;
            
            echo Status::Error . "**" . $err;
            Log::write("[CampaignMaster]" . $err);
            return;
        }

        $docfile =  "";
        $docfile =  basename($fileNames);
        $pi = pathinfo($docfile);

        if (!file_exists(PATH_CAMPAIGN)) {
            mkdir(PATH_CAMPAIGN, 0777, true);
        }

        $directory = PATH_CAMPAIGN . "/" . $id. "/";
        $newfile   = $directory . $fileNames;

        $fileUpload= "";
        $fileUpload= $tmpNames;

        if (!file_exists($directory)) {
            mkdir($directory, 0777, true);

        }

        $uploadResult = true;
        //resize image if image is too big
        if (Util::validFileExt($ext,$imgExts)) {
            $imageTemp      = "";
            $imageTemp      = $tmpNames;

            $imageSizeInfo    = getimagesize($imageTemp);

            if($imageSizeInfo == false){
                $err = "Make sure image file is valid!." ;

                echo Status::Error . "**" . $err;
                Log::write("[CampaignMaster]" . $err);
                return;
            }

            $image_width  = $imageSizeInfo[0];
            $image_height = $imageSizeInfo[1];
            $image_type   = $imageSizeInfo['mime'];
            $image_res    = ImageResize::createImageResource($image_type, $imageTemp);

            if($image_res == null){
                $err = "Cannot create image resource." ;

                echo Status::Error . "**" . $err;
                Log::write("[CampaignMaster]" . $err);
                return;
            }

            $uploadResult = ImageResize::normalResizeImage($image_res, $newfile, $image_type, $limitFilesize, $image_width, $image_height);
        } else {
            $uploadResult = move_uploaded_file($fileUpload, $newfile);
        }

        if ($uploadResult) {
            //save Sales Quotation Document here
            $datas = array() ;
            $datas[] = $this->db->fieldValue(CampaignDetailTable::C_ID ,$id);
            $datas[] = $this->db->fieldValue(CampaignDetailTable::C_DOC_NAME , $fileNames);
            $detail_id = $cls->addRecord($datas) ;
            $centreDocReturn .= $fileNames . "|" . $fileNames ."|". $idx . "|" . $id . "|" . $detail_id;
            
            echo Status::Ok . "*" . $centreDocReturn . "*";
        } else {
            $err = "Error in processing uploaded file" ;
            echo Status::Error . "*" . $centreDocReturn . "*" . $err;
        }

        unset($cls);
        unset($clsHeader);
    }

        private function processDownloadFile($params) {
        $expfile = $this->getParam($params,"fn","") ;
        $id = $this->getParam($params,'id',"") ;
        // Log::write(print_r($params,true));

        if (!file_exists(PATH_CAMPAIGN)) {
            mkdir(PATH_CAMPAIGN, 0777, true);
        }

        $dir = PATH_CAMPAIGN . "/" . $id . "/";
        $fn = $expfile;
        if ($expfile != "") {
            $docfile = $dir . $fn;

            if (file_exists($docfile)) {
                $filename = basename($expfile);
                $file_extension = strtolower(substr(strrchr($filename,"."),1));
                switch( $file_extension ) {
                    case "gif":
                        header('Content-type: image/gif');
                        break;
                    case "png":
                        header('Content-type: image/png');
                        break;
                    case "jpeg":
                    case "jpg":
                        header('Content-type: image/jpeg');
                        break;
                    case "pdf":
                        header('Content-type: application/pdf');
                        break;
                    default:
                        header('Content-disposition: attachment; filename='. $expfile);
                        header('Content-type: application/octet-stream');
                        break;
                }

                header('Content-Description: View File');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($docfile));

                ob_clean();
                flush();
                readfile($docfile);
                exit;

            } else {
                echo "<tr><td colspan='12'>Document file not found.</td></tr>" ;
                return;
            }
        } else {
            echo "<tr><td colspan='12'>Missing document file info.</td></tr>" ;
            return;
        }
    }

    private function deleteDocument($params) {
        $id         = $params["campaign_id"];
        $doc_id     = $params["doc_id"];
        $idx        = $params["idx"];
        $cls        = new CampaignDetailClass($this->db) ;

        try{
            $filter = CampaignDetailTable::C_ID." = ".$id." and ".CampaignDetailTable::C_DETAIL_ID." = ".$doc_id;
            $docsItem    = $cls->getTable($filter);

            if(!is_null($docsItem) && count($docsItem)>0) {
                foreach($docsItem as $docItem) {
                    if(trim($docItem[CampaignDetailTable::C_DOC_NAME]) != "") {
                        $directory   = PATH_CAMPAIGN . "/" . $id. "/";

                        $filePath   = $directory.$docItem[CampaignDetailTable::C_DOC_NAME];
                        if(file_exists($filePath))
                            unlink($filePath);
                    }
                    $cls->deleteAttachmentByID($doc_id);
                }
            }

            $this->sendJsonResponse(Status::Ok,"Campaign Attachment successfully deleted to the system.",$idx,$this->type);
        } catch (Exception $ex) {
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting new Campaign Attachment to the system.","", $this->type) ;
        }
    }
}
