<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "prospect/ProspectClass.php") ;
require_once (PATH_MODELS . "prospect/ProspectContactClass.php") ;
require_once (PATH_MODELS . "prospect/ProspectDocumentClass.php") ;
require_once (PATH_MODELS . "admin/OrganizationClass.php") ;
require_once (PATH_MODELS . "admin/OrganizationOptions.php") ;
require_once (PATH_CONTROLLERS . "base/EmailBase.php") ;

class AddProspect extends GLBase {
	private $type = "" ;
	private $records = array() ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->db) ;
		unset($this->records) ;
	}
	public function processRequest($params) {
		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 REQ_DOWNLOAD:
				// 	$this->downloadDoc($params) ;
				// 	break ;
				case REQ_ADD:
					$this->addRecord($params) ;
					break ;
				case REQ_VIEW:
					$this->getView($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 addRecord($params) {
		$cls = new ProspectClass($this->db) ;
		$cls_contact = new ProspectContactClass($this->db) ;

		$datas = array() ;
		$datasContact = array() ;
		$modifyby = 0 ;
		$modifydate = date_create('now')->format('Y-m-d H:i:s') ;

		$base64file = $this->getParam($params,'base64file',"");
        $extension 	= $this->getParam($params,'extension',"");
        $name 		= $this->getParam($params,'name',"");
		
		//code
		// $cls_coy 	= new CompanyClass($this->db) ;
        // $row_com    = $cls_coy->getRecord(1) ;
        // $opt        = new CompanyOptions() ;
        // $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
        // $op         = $opt->getOption() ;

		// $max_code    = intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_ENROLLMENT_CODE_RN]);
        // $result_code = $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_ENROLLMENT_CODE_PREFIX] . 
		// str_pad($max_code, intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_ENROLLMENT_CODE_LENGTH]), "0", STR_PAD_LEFT); 

		// $row = $cls->checkMembershipNumber($this->getParam($params,'number',""));

		// if(count($row) > 0){
		// 	$this->sendJsonResponse(Status::Ok,"This member number has already been registered","",$this->type);
		// 	return;
		// }
		$remarks_string = "Selling item: ".$this->getParam($params,'itemselling',"")." \nEvent duration: ".$this->getParam($params,'eventperiod',"")." \nEquipment requirement: ".$this->getParam($params,'equipment',"");

		$datas[] = $this->db->fieldValue(ProspectTable::C_NAME,$this->getParam($params,'companyname',""));
		$datas[] = $this->db->fieldValue(ProspectTable::C_UEN,$this->getParam($params,'companyuen',""));
		$datas[] = $this->db->fieldValue(ProspectTable::C_TELEPHONE,$this->getParam($params,'companyphone',""));

		$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_NAME,$this->getParam($params,'contactname',""));
		$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_MOBILE,$this->getParam($params,'contactnumber',""));
		$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_EMAIL,$this->getParam($params,'contactemail',""));

		$datas[] = $this->db->fieldValue(ProspectTable::C_SOFTWARE_INFO,'');
		$datas[] = $this->db->fieldValue(ProspectTable::C_BILLING_CYCLE,'');
		$datas[] = $this->db->fieldValue(ProspectTable::C_REMARKS,$remarks_string);

		$datas[] = $this->db->fieldValue(ProspectTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ProspectTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(ProspectTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ProspectTable::C_CREATE_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(ProspectTable::C_ACTIVE_STATUS,1) ;
		$datas[] = $this->db->fieldValue(ProspectTable::C_STATUS,1) ;

		$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_BY,$modifyby) ;
		$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_MODIFY_DATE,$modifydate) ;
		$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_CREATE_BY,$modifyby) ;
		$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_CREATE_DATE,$modifydate) ;

		try {
			$this->db->beginTran() ;

			$id = 0;
			$id_contact = 0;
			$id = $cls->addRecord($datas) ;			

			$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_ID, $id);
			$datasContact[] = $this->db->fieldValue(ProspectContactTable::C_ACTIVE, 1);
			$id_contact = $cls_contact->addRecord($datasContact) ;			

			$this->saveAddProspectAttachment($id, $base64file, $extension, $name);

			if ($id > 0 && $id_contact > 0) {
				//code
				// $max_code += 1;
				// $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_ENROLLMENT_CODE_RN] = $max_code;
				// $opt->setOption($op) ;
				
				// $code      = array() ;
				// $code[]    = $this->db->fieldValue(CompanyTable::C_OPTIONS,$opt->getXml());
				// $cls_coy->updateRecord(1,$code) ;
				
				//Upload document
				// $doc = $this->getParam($params,'doc',"") ;
				// $filename = $this->getParam($params,'filename',"") ;
				// if ($doc != "") {
				// 	if (file_exists($doc)) {
				// 		$newfile = PATH_DOC . "doc/" . $filename ;
				// 		if (file_exists($newfile)) {
				// 			unlink($newfile) ;
				// 		}
				// 		if (!copy($doc, $newfile)) {
				// 			log::write(" Error in copying doc file.") ;
				// 		}
				// 		unlink($doc) ;
				// 	} else {
				// 		log::write(" doc file not found in the upload directory.") ;
				// 	}
					
				// 	$cls->updateDoc($id,$filename);
				// }

				//Email
				// $fromEmail = "noreply@sbgsea.com";
				// $cls = new OrganizationClass($this->db) ;
				// $row = $cls->getRecord(0) ;
				
				// $opt = new OrganizationOptions() ;
				// $opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
				// $op = $opt->getOption() ;
				
				// $fromEmail 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_USER] ;
            	// $toEmail   	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_TO] ;
				
				// $email_body = file_get_contents(PATH_LIB . "email_contact_submission.txt");
				// $email_body = str_replace("{TITLE}", "New Membership Enrolments Submitted", $email_body);
				// $email_body = str_replace("{WEB_URL}", WEB_URL, $email_body);
				// $email_body = str_replace("{LOGO}", $this->getLogo(), $email_body);
				// $email_body = str_replace("{MEMBER_NAME}", $this->getParam($params,'name',""), $email_body);
				// $email_body = str_replace("{MEMBER_NUMBER}", $this->getParam($params,'number',""), $email_body);
				// $email_body = str_replace("{MEMBER_CONTACT}", $this->getParam($params,'contact',""), $email_body);
				// $email_body = str_replace("{MEMBER_EMAIL}", $this->getParam($params,'email',""), $email_body);
				// $email_body = str_replace("{MEMBER_FULL_NAME}", $this->getParam($params,'full',""), $email_body);
				// $email_body = str_replace("{MEMBER_PREFERRED_NAME}", $this->getParam($params,'preferred',""), $email_body);
			
				// $result =  $this->sendEmail("New Membership Enrolments Submitted",
				// 						$email_body,
				// 						$fromEmail,
				// 						null,
				// 						explode(";",$toEmail),
				// 						null,
				// 						0,
				// 						AppType::Enrollment);
				// if($result){
				// 	EmailLog::write("Email sent to --> ".$toEmail);
				// }
				
            	// $toEmail   	= $this->getParam($params,'email',"");
				
				// $email_ack_body = file_get_contents(PATH_LIB . "email_acknowledged_submission.txt");
				// $email_ack_body = str_replace("{TITLE}", "Membership Enrolments Received", $email_ack_body);
				// $email_ack_body = str_replace("{WEB_URL}", WEB_URL, $email_ack_body);
				// $email_ack_body = str_replace("{LOGO}", $this->getLogo(), $email_ack_body);
				// $email_ack_body = str_replace("{USER}", $this->getParam($params,'preferred',""), $email_ack_body);
				// $email_ack_body = str_replace("{MEMBER_NAME}", $this->getParam($params,'name',""), $email_ack_body);
				// $email_ack_body = str_replace("{MEMBER_NUMBER}", $this->getParam($params,'number',""), $email_ack_body);
				// $email_ack_body = str_replace("{MEMBER_CONTACT}", $this->getParam($params,'contact',""), $email_ack_body);
				// $email_ack_body = str_replace("{MEMBER_EMAIL}", $this->getParam($params,'email',""), $email_ack_body);
				// $email_ack_body = str_replace("{MEMBER_FULL_NAME}", $this->getParam($params,'full',""), $email_ack_body);
				// $email_ack_body = str_replace("{MEMBER_PREFERRED_NAME}", $this->getParam($params,'preferred',""), $email_ack_body);
				
				// $result =  $this->sendEmail("New Membership Enrolments Received",
				// 						$email_ack_body,
				// 						$fromEmail,
				// 						null,
				// 						explode(";",$toEmail),
				// 						null,
				// 						0,
				// 						AppType::Enrollment);
				// if($result){
				// 	EmailLog::write("Email acknowledgment sent to --> ".$toEmail);
				// }

				$this->db->commitTran();
				$this->sendJsonResponse(Status::Ok,"Thank you, we have received your quotation request.",15,$this->type);
			} else {
				$this->db->rollbackTran() ;
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new quotation request to the system.",$id, $this->type) ;
			}
		}  catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[NewEnrollment]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}

	private function getView($params) {
		include (PATH_VIEWS . "prospect/addprospectview.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}

	private function deleteDir($dirPath) {
        if ( !is_dir($dirPath) ) {
            // throw new InvalidArgumentException("$dirPath must be a directory");
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file) {
            if (is_dir($file)) {
                self::deleteDir($file);
            } else {
                unlink($file);
            }
        }
        // if( !rmdir($dirPath) ) {
        //     Log::write('[SalesInvoice]' . "Directory Not Found");
        // }

        if(file_exists($dirPath)){
            $this->recursiveRemoveDirectory($dirPath);
        }

    }

	public function saveAddProspectAttachment($id, $base64file, $extension, $filename)
    {
        $newfile = "";
        $doc_desc ="";
        // $id = $this->getParamInt($params,'id',0);

		$cls = new ProspectClass($this->db);
		$cls_Doc = new ProspectDocumentClass($this->db);

        if($base64file!="" || $base64file!=null){

            $path = PATH_PROSPECT_ATTACHMENT .(!isset($_SESSION[SE_BU]) ? "" : $_SESSION[SE_BU]."/"). $id . "/";
			//log::write($path);
            if (!file_exists($path)) {
                mkdir($path, 1777, true);
            }else{
                $this->deleteDir($path);
                mkdir($path, 1777, true);
            }

            $data= $base64file;
            $type= $extension;
			$encoded = substr($data, strpos($base64file, ',') + 1);
			//log::write(strlen($encoded));
            $newfile = $filename;

            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' ])) {
                    Log::write('invalid image type');
					$mesg = "invalid image type";
                    return $mesg;
                }
                $data = str_replace( ' ', '+', $data );
                $data = base64_decode($data);

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

                file_put_contents($path . $newfile, $data);
            } else if (preg_match('/^data:application\/(\w+);base64,/', $data, $type)) {
                $data = substr($data, strpos($data, ',') + 1);
                $type = strtolower($type[1]); // pdf

                if (!in_array($type, [ 'pdf' ])) {

                    Log::write('invalid file type');
                    $mesg = "invalid file type.";
                    return $mesg;
                }
                $data = str_replace( ' ', '+', $data );
                $data = base64_decode($data);
				//log::write($data);
                if ($data === false) {
                    //throw new \Exception('base64_decode failed');
                    Log::write('base64_decode failed');
					$mesg = "base64_decode failed.";
                    return $mesg;
                }

                file_put_contents($path . $newfile, $data);
            }else {
                //throw new \Exception('did not match data URI with image data');
                Log::write('did not match data URI with image data');
				$mesg = "did not match data URI with image data.";
                return $mesg;
            }

            try {
				//log::write($id);
                $datas_doc_to_save = array() ;
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_ID ,$id);
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_DOCUMENT_ID ,1);

                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_NAME , $filename);
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE , $encoded);
                $datas_doc_to_save[] = $this->db->fieldValue(ProspectDocumentTable::C_FILE_TYPE , $type);

                $cls_Doc->addRecord($datas_doc_to_save) ;
                return;

            } catch (Exception $e){
                Log::write('[attachment]' . $e->getMessage());
				$mesg = $e->getMessage();
                return $mesg;

            }

        }

    }
}
