<?php
include (PATH_CONTROLLERS . "Common.php") ;
include (PATH_MODELS . "admin/DepartmentGroupClass.php") ;
include (PATH_MODELS . "admin/SoftwareClass.php") ;
include (PATH_MODELS . "corporate_gift/CompanyProfileClass.php") ;

class CompanyProfileEntry 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::CompanyProfileEntryView:
					$this->getView($params) ;
					break ;
				case REQ_GET:
					$this->getCompanyProfileEntryRecord($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() ;
		include (PATH_VIEWS . "corporate_gift/CompanyProfileEntryView.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']  = "Company Profile Entry" ;
		$this->sendJsonResponse(Status::Ok,"Company Profile Entry Info",$dataReturn,$this->type);
	}

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

        $id     = $params['id'];
        $cls    = new CompanyProfileClass($this->db);
        $row    = $cls->getRecord($id);
        $datas = array();
        if (!is_null($row) && count($row) > 0) {
            $datas['id']            = $row[CompanyProfileTable::C_ID];
            $datas['code']          = $row[CompanyProfileTable::C_CODE];
            $datas['name']          = $row[CompanyProfileTable::C_NAME];
            $datas['url']           = $row[CompanyProfileTable::C_URL];
            $datas['status']        = $row[CompanyProfileTable::C_STATUS];

            $datas['mail_server']   = $row[CompanyProfileTable::C_MAIL_SERVER];
            $datas['port']          = $row[CompanyProfileTable::C_MAIL_PORT];
            $datas['mail_sender']   = $row[CompanyProfileTable::C_MAIL_SENDER];
            $datas['mail_password'] = $row[CompanyProfileTable::C_MAIL_PASSWORD];
            $datas['ea']            = $row[CompanyProfileTable::C_MAIL_EA];
            $datas['ssl']           = $row[CompanyProfileTable::C_MAIL_SSL];
            $datas['oauth']         = $row[CompanyProfileTable::C_MAIL_OAUTH];
            $datas['tenant_id']     = $row[CompanyProfileTable::C_MAIL_TENANT_ID];
            $datas["src"]           = $row[CompanyProfileTable::C_LOGO_PATH];

            $picture_name           = explode("/", $row[CompanyProfileTable::C_LOGO_PATH]);
            $picture_name           = explode(".", end($picture_name))[0];
            $datas["filename"]      = $picture_name;
            $datas["path_picture"]  = str_replace(PATH_CODE,"",$row[CompanyProfileTable::C_LOGO_PATH]);
            
            $sig_filename           = explode("/", $row[CompanyProfileTable::C_SIGNATURE_PATH]);
            $sig_filename           = explode(".", end($sig_filename))[0];
            $datas["signature"]     = $sig_filename;
            $datas["path_signature"]= str_replace(PATH_CODE,"",$row[CompanyProfileTable::C_SIGNATURE_PATH]);
        }
        include(PATH_VIEWS . "corporate_gift/CompanyProfileEntryView.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)
	{
        try{
			$id 	= $params['id'];
            $cls 	= new CompanyProfileClass($this->db);
            $comp 	= $cls->getRecord($id);

            if( is_null( $comp ) || count( $comp )==0 ){
                $this->sendJsonResponse(Status::Error,"Please save company profile before proceed.","",$this->type) ;
                return;
            }

            $fromEmail = $comp[CompanyProfileTable::C_MAIL_SENDER];
            $custEmail = $this->getParam($params,'to_email',"");

            $fromEmailStr = $fromEmail;
            $fromEmails   = explode(";", $fromEmailStr);

			$email_body = file_get_contents(PATH_LIB . "email_test.txt");
            $result =  $this->sendEmail("Testing Email",
									$email_body,
                                    $fromEmails,
                                    null,
                                    explode(";",$custEmail),
									null,
									$id);

            if($result){
                EmailLog::write("Email sent to --> ".$custEmail);
				$this->sendJsonResponse(Status::Ok,"Email Sent Successfully.","", $this->type);
            } else {
                EmailLog::write("Email failed sent to --> ".$custEmail);
                $this->sendJsonResponse(Status::Error,"There is an error in sending email.", "", $this->type);
            }
        } catch(Exception $e){
            Log::write("[SendEmailTesting]" . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Application Error","",$this->type) ;
        }
	}
}
