<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once(PATH_MODELS . "campaign/CampaignProfileClass.php");
require '../vendor/autoload.php';

class CampaignProfile 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::CampaignProfileView:
					$this->getView($params) ;
					break ;
                case Command::CampaignProfileListView:
                    $this->getCampaignProfileList($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params);
                    break;
                case REQ_DELETE:
                    $this->deleteCampaignProfileRecord($params);
                    break;
                case "DELETE_CAMPAIGN_PROFILE_SIGNATURE":
                case "DELETE_CAMPAIGN_PROFILE_LOGO":
                    $this->deleteCampaignLogo($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/CampaignProfileView.php") ;

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

    private function getCampaignProfileList($params) {
        $cls = new CampaignProfileClass($this->db);

        $sorts  = $params['sorts'];

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

        $rows = $cls->getCampaignProfileList($orderby);

        $lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $list = [
                    "id" => $row[CampaignProfileTable::C_ID],
                    "code" => htmlentities($row[CampaignProfileTable::C_CODE]),
                    "name" => htmlentities($row[CampaignProfileTable::C_NAME]),
                    "status" => ($row[CampaignProfileTable::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 CampaignProfileCLass($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(CampaignProfileTable::C_CODE, $this->getParam($params, 'code', ''));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_NAME, $this->getParam($params, 'name', ''));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_URL, $this->getParam($params, 'url', ''));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_STATUS, $this->getParamInt($params, 'active', 0));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_SERVER, $this->getParam($params, 'mail_server', ''));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_PORT, $this->getParam($params, 'port', ''));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_SENDER, $this->getParam($params, 'mail_sender', ''));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_PASSWORD, $this->getParam($params, 'mail_password', ''));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_EA, $this->getParamInt($params, 'ea', 0));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_SSL, $this->getParamInt($params, 'ssl', 0));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_OAUTH, $this->getParam($params, 'oauth', 'NO'));
        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_TENANT_ID, $this->getParam($params, 'tenant_id', ''));

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

        try {
            $this->db->beginTran();
            $exist  = $cls->getExistingRecords($this->getParam($params, 'code', ""));
            $result = array();

            if (!is_null($exist)) {
                $this->sendJsonResponse(Status::Error, "Campaign Profile code already exist.", "", $this->type);
            } else {                
                $id = $cls->addRecord($datas);
                if($id > 0){
                    //logo
                    $base64file = $this->getParam($params,'base64file',"");
                    $extension  = $this->getParam($params,'extension',"");
                    $filename   = $this->getParam($params,'filename',"");

                    if($base64file  != ""){
                        $filename  = 'campaign_profile_logo_' . date_create('now')->format('Ymd_hisv');
                        $doc_datas = $this->saveCampaignProfileLogo($base64file, $extension, $filename);

                        $result['logo'] = $filename;
                        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_LOGO_PATH, str_replace(PATH_CODE,"",$doc_datas));
                    }else {
                        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_LOGO_PATH, "");
                    }
                    
                    //signature
                    $sig_base64file = $this->getParam($params,'sig_base64file',"");
                    $sig_extension  = $this->getParam($params,'sig_extension',"");
                    $sig_filename   = $this->getParam($params,'sig_filename',"");

                    if($sig_base64file  != ""){
                        $sig_filename  = 'campaign_profile_signature_' . date_create('now')->format('Ymd_hisv');
                        $doc_datas = $this->saveCampaignProfileLogo($sig_base64file, $sig_extension, $sig_filename);
                        
                        $result['signature'] = $sig_filename;
                        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_SIGNATURE_PATH, str_replace(PATH_CODE,"",$doc_datas));
                    }else {
                        $datas[] = $this->db->fieldValue(CampaignProfileTable::C_SIGNATURE_PATH, "");
                    }
                    $result['id'] = $id;
                    $cls->updateRecord($id,$datas);
                }
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok, "Successfully inserted into system", $result, $this->type);
            }
        } catch (Exception $e) {
            $this->db->rollbackTran() ;	
            Log::write('[CampaignProfile]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error, "Sorry, there is a error in database operation.", "", $this->type);
        }
        unset($cls);
    }

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

		if (isset($params['id'])) {
            $id = $params['id'] ;

            $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(CampaignProfileTable::C_CODE, $this->getParam($params, 'code', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_NAME, $this->getParam($params, 'name', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_URL, $this->getParam($params, 'url', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_STATUS, $this->getParam($params, 'active', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_SERVER, $this->getParam($params, 'mail_server', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_PORT, $this->getParam($params, 'port', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_SENDER, $this->getParam($params, 'mail_sender', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_PASSWORD, $this->getParam($params, 'mail_password', ''));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_EA, $this->getParamInt($params, 'ea', 0));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_SSL, $this->getParamInt($params, 'ssl', 0));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_OAUTH, $this->getParam($params, 'oauth', 'NO'));
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MAIL_TENANT_ID, $this->getParam($params, 'tenant_id', ''));
           
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_WS_ID,$ws) ;
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MODIFY_BY,$modifyby) ;
            $datas[] = $this->db->fieldValue(CampaignProfileTable::C_MODIFY_DATE,$modifydate) ;
            //log
            $base64file = $this->getParam($params,'base64file',"");
			$extension  = $this->getParam($params,'extension',"");
			$filename   = $this->getParam($params,'filename',"");
            if($filename != ""){
                $filename = explode("/", $filename);
                $filename = explode(".", end($filename))[0];
            }else{
                $filename = 'campaign_profile_logo_' . date_create('now')->format('Ymd_hisv');
            }
            $result['logo'] = $filename;

            if($filename != ""){
                if($base64file  != ""){
                    $doc_datas = $this->saveCampaignProfileLogo($base64file, $extension, $filename);
                    $datas[] = $this->db->fieldValue(CampaignProfileTable::C_LOGO_PATH, str_replace(PATH_CODE,"",$doc_datas));
                }
            }else {
                $datas[] = $this->db->fieldValue(CampaignProfileTable::C_LOGO_PATH, "");
            }

            //signature 
            $sig_base64file = $this->getParam($params,'sig_base64file',"");
			$sig_extension  = $this->getParam($params,'sig_extension',"");
			$sig_filename   = $this->getParam($params,'sig_filename',"");
            if($sig_filename != ""){
                $sig_filename = explode("/", $sig_filename);
                $sig_filename = explode(".", end($sig_filename))[0];
            }else{
                $sig_filename = 'campaign_profile_signature_' . date_create('now')->format('Ymd_hisv');
            }
            $result['signature'] = $sig_filename;

            if($filename != ""){
                if($sig_base64file  != ""){
                    $doc_datas    = $this->saveCampaignProfileLogo($sig_base64file, $sig_extension, $sig_filename);
                    $datas[] = $this->db->fieldValue(CampaignProfileTable::C_SIGNATURE_PATH, str_replace(PATH_CODE,"",$doc_datas));
                }
            }else {
                $datas[] = $this->db->fieldValue(CampaignProfileTable::C_SIGNATURE_PATH, "");
            }

			try {
                $this->db->beginTran();
                $mesg   = "";
                $exist = $cls->getExistingRecords($this->getParam($params, 'code', ""), $id);
                if (!is_null($exist)) {
                    $this->sendJsonResponse(Status::Error, "Campaign Profile code already exist.", "", $this->type);
                } else {
                    $cls->updateRecord($id,$datas);

                    $mesg = "Campaign Profile successfully updated to the system.";

                    $this->db->commitTran();
                    $this->sendJsonResponse(Status::Ok, $mesg, $result, $this->type) ;
                }
			} catch (Exception $e) {
                $this->db->rollbackTran() ;	
				Log::write('[Customer]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating campaign profile detail to the system.","",$this->type) ;
			}
			unset($cls) ;
		}else {
			$this->sendJsonResponse(Status::Error,"You must supply the customer id you wish to update. Please try again.","",$this->type);
		}
    }

    private function deleteCampaignProfileRecord($params) {
        $cls        = new CampaignProfileClass($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);

            $this->db->commitTran();
            $this->sendJsonResponse(Status::Ok, "Successfully delete campaign profile 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 Profile] ' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting campaign profile from the system.","",$this->type);
            }
            return;
        }

        unset($cls);
    }

    public function saveCampaignProfileLogo($base64file, $extension, $image_name)
    {
		$newfile = "";
        if($base64file!="" || $base64file!=null){
            $path = PATH_CAMPAIGN_PROFILE_LOGO . "/";
            $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 $mesg;
                }
                $data = str_replace( ' ', '+', $data );
                $data = base64_decode($data);

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

                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 $mesg;
            }
            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) ;
	}
}
