<?php

use Google\Cloud\Vision\Annotation\Web;
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/OrganizationClass.php") ;
//customer
require_once (PATH_MODELS . "customer/CustomerClass.php");
abstract class MobileBase extends ControllerBase {

    // protected $fontname = "garudabook";
    // protected $fontnamebold = "garudab";
	
	// set font
	protected $fontname = "lomabook";
	protected $fontnamebold = "lomab";
	protected $fontnameitalic = "lomai";
	protected $fontnamebolditalic = "lomabi";

	// protected $fontname = "cmprasanmit";
	// protected $fontnamebold = "cmprasanmitb";

	// protected $fontname = "jsprasoplarpnormal";
	// protected $fontnamebold = "jsprasoplarpnormal";

	// protected $fontname = "thkrub";
	// protected $fontnamebold = "thkrubb";

	// protected $fontname = "umpushbook";
	// protected $fontnamebold = "umpushb";

	/**
	 * Sends an HTML email
	 * @param String 	$subject
	 * @param String 	$message
	 * @param ArrayList $recipientEmails
	 */

	protected $orgId = -1;
	protected function sendEmailManual($subject, $message,$fromEmails, $ccEmails, $recipientEmails, $attachmentList, $companyId) {
		$mail             = new PHPMailer();
        $mail->SetLanguage( 'en', 'phpmailer/language/' );
        $mail->Timeout = 300;

		$mail->IsSMTP(); // telling the class to use SMTP
		$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)

		$emailSetting 	  = $this->getEmailConfig();
        if ($emailSetting['ssl'] == '1'){
            if (trim($emailSetting['mailserver']) == 'smtp.office365.com'){
                $mail->SMTPSecure = "tls";
            } else {
                $mail->SMTPSecure = "ssl";
            }
        }

        $mail->SMTPAuth   = ($emailSetting['ea'] == '1' ? true : false);                    // enable SMTP authentication
        $mail->Host       =	$emailSetting['mailserver'];                                    // sets the SMTP server
        $mail->Port       = $emailSetting['port'];                                          // set the SMTP port for the GMAIL server
        $mail->Username   = $emailSetting['mailuser'];                                      // SMTP account username
        $mail->Password   = $emailSetting['mailpwd'];                                       // SMTP account password
        $mail->SetFrom($emailSetting['mailuser']);

		//$mail->SetFrom($fromEmails[0]);
		if(!is_null($ccEmails) && count($ccEmails) > 0) {
			foreach ($ccEmails as $ccEmail) {
				$mail->AddCC($ccEmail);
			}
			$ccEmailStr = implode(";", $ccEmails);
			$mail->addCustomHeader("Cc: " . $ccEmailStr);
		}

		$mail->Subject    = $subject;
		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

		$mail->IsHTML(true);
		$mail->MsgHTML($message);

		if(!is_null($recipientEmails) && count($recipientEmails) > 0) {
			foreach ($recipientEmails as $recipientEmail) {
				if (isset($recipientEmail) && !empty($recipientEmail))
					$mail->AddAddress($recipientEmail);
			}
		}
		
		$toEmailStr = implode(",", $recipientEmails);
		$mail->addCustomHeader("to: " . $toEmailStr);
        if (!is_null($attachmentList) && count($attachmentList) > 0){
            foreach($attachmentList as $attachment){
                $mail->AddAttachment($attachment);      // attachment
            }
        }
		try {
            $result = $mail->Send();
            if (!$result){
                Log::write($mail->ErrorInfo);
            }
			return $result;
		} catch (Exception $e) {
			Log::write('[Send Email] :'.$e->getMessage());
			return false;
		}
	}

	protected function sendEmail($subject, $message,$fromEmails, $ccEmails = null, $recipientEmails=null, $attachmentList = null, $companyId = 0, $appType = 0, $appId = 0) {
		if ($companyId != 0){
            $emailSetting 	  = $this->getEmailConfigFromCompany($companyId);
        } else {
            $emailSetting 	  = $this->getEmailConfig();
        }


		$clsNc = new NotificationCentre();
		$result = $clsNc->sendEmail($subject, $message,$fromEmails, $recipientEmails, $ccEmails, $attachmentList, $companyId, $emailSetting, $appType, $appId);
		if (!$result) {
			$result = $this->sendEmailManual($subject, $message,$fromEmails, $ccEmails, $recipientEmails, $attachmentList, $companyId);
		}
		return $result;
	}

	private function getLogo($coyid = 0)
	{
		$userCls  = new UserClass($this->db);
		$coyid = $_SESSION[SE_ORGID];
		$fn = Util::getLogoFile(PATH_PICTURE, "company_" . $coyid);
		if ($fn == "") {
			return "";
		} else {
			$image = '<img align="center" alt="Alternate text" border="0" class="center fixedwidth " src="' . $this->getBaseURL() . '/web/picture/company_' . $coyid . '/' . $fn . '" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 175px; display: block;" title="Alternate text" width="175"/>';


			return $image;
		}
	}

	private function generateOptionsmsg($tableName, $keyField, $descField, $textHeading, $default="", $isDesciption = true, $orderby=null, $isnumber=false) {
		$filter 	= array();
		$filter[] 	= array('field'=>'ACTIVE_STATUS','value'=>1) ;
		$vls 		= $this->getValueList($tableName, $keyField, $descField,null,$filter, $keyField) ;
		if($isDesciption)
			$vls 	= $this->getValueList($tableName, $keyField, $descField,array('code'=>'','desc'=>$textHeading),$filter,$keyField) ;
		return Util::createOptionValue($vls, $default, $isnumber=false) ;
	}

	/**
	 * Filter by org, and generate to options combobox
	 * @param String $tableName		Table name
	 * @param String $keyField		key
	 * @param String $descField		value for that key
	 * @param unknown $textHeading	Text of combobox ( like 'select country')
	 * @param string $default		selected default value of combobox
	 * @param string $isDesciption	has description(text heading) or not
	 * @return string options
	 */
	protected function generateOptions($tableName, $keyField, $descField, $textHeading, $default="", $isDesciption = true, $orderby=null, $isnumber=false) {
		$filter 	= array();
		$filter[] 	= array('field'=>$this->fldorg,'value'=>0) ;
		$vls 		= $this->getValueList($tableName, $keyField, $descField,null,$filter, $orderby) ;
		if($isDesciption)
			$vls 	= $this->getValueList($tableName, $keyField, $descField,array('code'=>'','desc'=>$textHeading),$filter, $orderby) ;
		return Util::createOptionValue($vls, $default, $isnumber) ;
	}

    protected function dd($arr)
    {
    	echo "<pre>";
    	print_r($arr);
    	die();
    }

    protected function dump($arr)
    {
    	echo "<pre>";
    	print_r($arr);
    	echo "</pre>";
    }
    protected function getWebPageURL(){
        $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        if (strpos($pageURL, "?") !== false){
        	if(strpos($pageURL, "PortalWebView") !== false) {
				$pageURL = substr($pageURL, 0, strrpos($pageURL, "/")-4);
				$pageURL = $pageURL . "portal/index.pzx";
        	} else {
	            $pageURL = substr($pageURL, 0, strpos($pageURL, "?"));
	        }
        }
        return $pageURL;
    }

	protected function loadSetting() {
		$_SESSION[SE_PORT_ORGNAME] = "default company" ;
		$_SESSION[SE_ORGCODE] = "" ;
	}


	protected function deleteAdditionalDocument($reqId){

        $tempDirectory = PATH_CLAIM . "additional/" . $reqId. "/";

        $this->recursiveRemoveDirectory($tempDirectory);
    }

    protected function recursiveRemoveDirectory($directory)
    {
        foreach(glob("{$directory}/*") as $file)
        {
            if(is_dir($file)) {
                $this->recursiveRemoveDirectory($file);
            } else {
                unlink($file);
            }
        }
	}

	protected function copyLedgerDocument($oldFolderPath, $newFolderPath, $unlinkdoc=true, $array_doc = "")
	{		
		if (is_dir($oldFolderPath)) {
			$this->recurse_copy($oldFolderPath, $newFolderPath, $array_doc);

			if($unlinkdoc){ //to remove the files or not
				if($array_doc == ""){
					$files = glob($oldFolderPath . '*'); // get all file names
					foreach ($files as $file) { // iterate files
						if (is_file($file)) {
							unlink($file); // delete file
						}
					}				
				}else{
					$array_doc = explode(",", $array_doc);
					foreach ($array_doc as $doc) { // iterate files
						if (is_file($oldFolderPath . '/' . $doc)) {
							unlink($oldFolderPath . '/' . $doc);
						}
					}
				}
			}
			// return rmdir($oldFolderPath);
		}
	}

	protected function recurse_copy($src, $dst, $array_doc = "")
	{
		$dir = opendir($src);
		if (!file_exists($dst)) {
			mkdir($dst, 0777, true);
		}

		if($array_doc == ""){
			while (false !== ($file = readdir($dir))) {
				if (($file != '.') && ($file != '..')) {
					if (is_dir($src . '/' . $file)) {
						$this->recurse_copy($src . '/' . $file, $dst . '/' . $file);
					} else {
						copy($src . '/' . $file, $dst . '/' . $file);
					}
				}
			}
		}else{
			$array_doc = explode(",", $array_doc);
			foreach ($array_doc as $doc) {
				copy($src . $doc, $dst . $doc);
			}
		}
		closedir($dir);
	}
	protected function getCustomerCodeOpt($bu="", $code="") {
		$vls = array();
		$vls[] = array('code'=>'','desc'=>'') ;
		try {
			$cls = new CustomerClass($this->db);
			$lists = $cls->getTable();
			if(!is_null($lists) && count($lists)>0){
				foreach($lists as $list) {
					$vls[] = array('code'=>$list[CustomerTable::C_ID],'desc'=>$list[CustomerTable::C_CODE]." - ".$list[CustomerTable::C_NAME]) ;
				}
			}
		} catch (Exception $e) {
			Log::write($e->getMessage());
		}
		return Util::createOptionValue($vls);
	}
	protected function getProspectOpt($all=0) {
		$vls = array();
		$vls[] = array('code'=>'','desc'=>'') ;
		try {
			$cls = new ProspectClass($this->db);
			if($all == 1){
				$lists = $cls->getActiveAndConvertedProspect();
			}else{
				$lists = $cls->getActiveProspect();
			}
			// $lists = $cls->getTable();
			if(!is_null($lists) && count($lists)>0){
				foreach($lists as $list) {
					$vls[] = array('code'=>$list[ProspectTable::C_ID],'desc'=> ($list[ProspectTable::C_CODE] == "" ? "" : $list[ProspectTable::C_CODE]." - ").$list[ProspectTable::C_NAME]) ;
				}
			}
		} catch (Exception $e) {
			Log::write($e->getMessage());
		}
		return Util::createOptionValue($vls);
	}
	protected function getDebitCreditOption(){
		$vls = array() ;
		$vls[] = array ('code'=>'','desc'=>"" );
		$vls[] = array ('code'=>'D','desc'=>"Debit" );
		$vls[] = array ('code'=>'C','desc'=>"Credit" );
		return Util::createOptionValue($vls) ;
	}
	public function getCurrencyRateTypeOpt() {
		$arr = array() ;
		$arr[] = array ('code'=>'0','desc'=>"Default" );
		$arr[] = array ('code'=>'1','desc'=>"Monthend" );
		return Util::createOptionValue($arr) ;
	}
	protected function getAllUsers()
	{
		$cls =  new UserClass($this->db);

		$rows = $cls->getAllRecord();
		$vls = array();
		if(!is_null($rows) && count($rows)>0){
			foreach ($rows as $row) {
				$vls[] = array('code'=> $row[UserTable::C_ID],					'desc'=>$row[UserTable::C_FULL_NAME]) ;
			}
		}

		return Util::createOptionValue($vls);
	}

	protected function getUser($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select a User ---";
		// if($isChooseOne == false)
		// 	$textChooseHead = "All";
		return $this->generateOptions(UserTable::C_TABLE, UserTable::C_ID, UserTable::C_FULL_NAME,
									$textChooseHead, $default, $isDesciption);
	}

	protected function getBaseURL(){
        $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"];
			$strURL = explode('/',$_SERVER['PHP_SELF'])[1];
			if($strURL != "portal") {
				$pageURL .= "/".$strURL;
			}
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"];
        }
        if (strpos($pageURL, "?") !== false){
            $pageURL = substr($pageURL, 0, strpos($pageURL, "?"));
        }
        return $pageURL;
    }
	protected function getProspectContactOption($customer_id=0, $selected="")
	{
		$vls = array();
		$vls[] = array('code'=>"",'desc'=>"") ;
		try {
			$cls = new ProspectContactClass($this->db);
			$lists = $cls->getProspectContact($customer_id);
			if(!is_null($lists) && count($lists) > 0) {
				foreach ($lists as $list) {
					$vls[] = array('code'=>$list[ProspectContactTable::C_CONTACT_ID],'desc'=>$list[ProspectContactTable::C_NAME]) ;
				}
			}
		} catch (Exception $e) {
			Log::write($e->getMessage());
			return $vls;
		}

		if($selected=="") {
			return Util::createOptionValue($vls) ;
		} else {
			return Util::createOptionValue($vls, $selected) ;
		}
	}
	protected function getCustomerContactOption($customer_id=0, $selected="")
	{
		$vls = array();
		$vls[] = array('code'=>"",'desc'=>"") ;
		try {
			$cls = new CustomerContactClass($this->db);
			$lists = $cls->getCustomerContact($customer_id);
			if(!is_null($lists) && count($lists) > 0) {
				foreach ($lists as $list) {
					$vls[] = array('code'=>$list[CustomerContactTable::C_CONTACT_ID],'desc'=>$list[CustomerContactTable::C_NAME]) ;
				}
			}
		} catch (Exception $e) {
			Log::write($e->getMessage());
			return $vls;
		}

		if($selected=="") {
			return Util::createOptionValue($vls) ;
		} else {
			return Util::createOptionValue($vls, $selected) ;
		}
	}
	protected function getAuditLogTableOpt() {
		$cls = new AuditLogClass($this->db);

		$rows = $cls->getAuditLogTableList($_SESSION[SE_BU]);

		$vls   		= array();
		$vls[] 		= array('code' => "", 'desc' => "-- Select Table -- ");

		if (!is_null($rows) && count($rows) > 0) {
			foreach ($rows as $row) {
				$desc = $row['desc'];
				foreach (TableKeyList::C_LIST as $tk) {
					$tk = explode("|", $tk);
					if (strcmp($tk[0],  $row['code']) == 0) {
						$desc = $tk[1];
						break;
					}
				}

				$vls[] = array('code' => $row['code'], 'desc' => $desc);
			}
		}
		return Util::createOptionValue($vls);
	}

	public function getAuditLogActivityTypeOpt() {
		$arr = array() ;
		$arr[] = array ('code'=>"",'desc'=>"All" );
		$arr[] = array ('code'=>AuditLogActivityType::InsertRecord,'desc'=>"Insert" );
		$arr[] = array ('code'=>AuditLogActivityType::UpdateRecord,'desc'=>"Update" );
		$arr[] = array ('code'=>AuditLogActivityType::DeleteRecord,'desc'=>"Delete" );
		return Util::createOptionValue($arr) ;
	}

	public function getAuditLogActivityTypeDesc($code) {
		$desc = "";
		switch($code){
			case AuditLogActivityType::InsertRecord:
				$desc = "Insert Record";
				break;
			case AuditLogActivityType::UpdateRecord:
				$desc = "Update Record";
				break;
			case AuditLogActivityType::DeleteRecord:
				$desc = "Delete Record";
				break;
			default:
				$desc = "";
				break;
		}
		return $desc;
	}

	public function getAccountFlagsOptions() {
		$arr = array() ;
		$arr[] = array ('code'=>'','desc'=>"-- Select Flag --" );
		$arr[] = array ('code'=>AccountFlags::Customer,'desc'=>"Customer" );
		$arr[] = array ('code'=>AccountFlags::Supplier,'desc'=>"Supplier" );
		return Util::createOptionValue($arr) ;
	}

	public function getAccountFlagsDesc($code) {
		$desc = "";
		switch($code){
			case AccountFlags::Supplier:
				$desc = "Supplier";
				break;
			case AccountFlags::Customer:
				$desc = "Customer";
				break;
			default:
				$desc = "";
				break;
		}
		return $desc;
	}
	
	protected function getVersion() {
		$result 	= "";
		$file 		= "version.txt";
		$path 		= PATH_CODE.$file;

		if(file_exists($path)){
			$version 	= fgets(fopen($path, "r"));
			$result 	= "<a href=\"../code/".$file."\" download=\"changelog_".$version.".txt\">".$version."</a>";
		}

		return $result;
	}

	public function createMenuFunc($href, $desc, $type){
		return "javascript:showPage('" . Util::convertLink($href) . "','" . $desc . "'" . ",'" . "$type" . "')";
	}
}