<?php
require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "activity/CurrencyClass.php");
require_once (PATH_MODELS . "activity/PaymentTermsClass.php");
require_once (PATH_MODELS . "activity/invoice/InvoiceTitleClass.php");
require_once (PATH_MODELS . "admin/OrganizationClass.php") ;
require_once (PATH_MODELS . "admin/OrganizationOptions.php") ;
require_once (PATH_MODELS . "admin/CompanyClass.php") ;
require_once (PATH_MODELS . "admin/CompanyOptions.php") ;
require_once (PATH_MODELS . "admin/LanguageTypeClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/UserGroupClass.php");
require_once (PATH_MODELS . "admin/UserRight.php");
require_once (PATH_LIB . "class.phpmailer.php");
require_once (PATH_LIB . "NotificationCentre.php");
require_once (PATH_MODELS . "activity/salesquotation/SalesQuotationClass.php");

abstract class ActivityBase extends ControllerBase {
	/**
	 * Sends an HTML email
	 * @param String 	$subject
	 * @param String 	$message
	 * @param ArrayList $recipientEmails
	 */
	 
	protected $orgId = -1;
	protected function sendEmailManual($subject, $message,$fromEmails, $recipientEmails, $ccEmails = null, $attachmentList = null, $companyId = 0) {
		$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)
		// 1 = errors and messages
		// 2 = messages only
		
// 		$mail->SMTPSecure = "ssl";  
// 		$mail->CharSet    = 'UTF-8';                // sets the prefix to the servier
		
        if ($companyId != 0){
            $emailSetting 	  = $this->getEmailConfigFromCompany($companyId);
        } else {
            $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']);
		
		if(is_null($ccEmails) == false) {
			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);
		
		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, $recipientEmails, $ccEmails = null, $attachmentList = null, $companyId = 0, $appType = 0, $appId = 0) {
		
		if ($companyId != 0){
            $emailSetting 	  = $this->getEmailConfigFromCompany($companyId);
        } else {
            $emailSetting 	  = $this->getEmailConfig();
		}
		// log::write($emailSetting);
		$clsNc = new NotificationCentre();
		$result = $clsNc->sendEmail($subject, $message,$fromEmails, $recipientEmails, $ccEmails, $attachmentList, $companyId, $emailSetting, $appType, $appId);
		if (!$result) {
			$result = $this->sendEmailManual($subject, $message,$fromEmails, $recipientEmails, $ccEmails, $attachmentList, $companyId);
		}
		return $result;        
	}
	
	protected function loadSetting() {
		$_SESSION[SE_PORT_ORGNAME] = "default company" ;
		$_SESSION[SE_ORGCODE] = "" ;
	}
	
	protected function getEmailConfig() {
		$cls = new OrganizationClass($this->db) ;
		if($this->orgId == -1)
			$row = $cls->getRecord($_SESSION[SE_ORGID]) ;
		else
			$row = $cls->getRecord($this->orgId) ;
		if (is_null($row))
			return null;
		
		
		if (is_null($row[OrganizationTable::C_OPTIONS]) || $row[OrganizationTable::C_OPTIONS] == "") 
			return null;
		
		$opt = new OrganizationOptions() ;
		$opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
		$op = $opt->getOption() ;
		
		$datas = array();
		$datas['mailserver']= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SERVER] ;
		$datas['mailuser'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_USER] ;
		$datas['mailpwd'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PWD] ;
		$datas['ea'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_ENABLE_AUTHENTICATION] ;
		$datas['port'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PORT] ;
		$datas['ssl'] = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SSL] ;
		
		return $datas;
	}
	
	protected function getEmailConfigFromCompany($id) {
		$cls = new CompanyClass($this->db) ;
        $row_com = $cls->getRecord($id) ;
		
        $opt 		= new CompanyOptions() ;
        $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
        $op 		= $opt->getOption() ;
        
		$datas = array();
		$datas['mailserver']= $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_SERVER] ;
		$datas['mailuser'] 	= $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_SENDER] ;
		$datas['mailpwd'] 	= $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_PASSWORD] ;
		$datas['port'] 	= $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_PORT] ;
		$datas['ea'] = $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_AUTH] ;
		$datas['ssl'] = $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_SSL] ;
	
		return $datas;
	}
	
	protected function getSizeConfig() {
		$cls = new OrganizationClass($this->db) ;
		$row = $cls->getRecord($_SESSION[SE_ORGID]) ;
		if (is_null($row))
			return 5000;
		
		if (is_null($row[OrganizationTable::C_OPTIONS]) || $row[OrganizationTable::C_OPTIONS] == "") 
			return 5000;
		
		$opt = new OrganizationOptions() ;
		$opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
		$op = $opt->getOption() ;
		
		return floatval($op[OrganizationOptions::C_SETTING][OrganizationOptions::C_UPLOAD_SIZE_LIMT]) == 0 ? 5000 : floatval($op[OrganizationOptions::C_SETTING][OrganizationOptions::C_UPLOAD_SIZE_LIMT]);
	}
	
	protected function getClaimDayLastConfig() {
		$cls = new OrganizationClass($this->db) ;
		$row = $cls->getRecord($_SESSION[SE_ORGID]) ;
		if (is_null($row))
			return 30;
		
		if (is_null($row[OrganizationTable::C_OPTIONS]) || $row[OrganizationTable::C_OPTIONS] == "") 
			return 30;
		
		$opt = new OrganizationOptions() ;
		$opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
		$op = $opt->getOption() ;
		
		return floatval($op[OrganizationOptions::C_SETTING][OrganizationOptions::C_CLAIM_DAY_LAST]) == 0 ? 30 : intval($op[OrganizationOptions::C_SETTING][OrganizationOptions::C_CLAIM_DAY_LAST]);
	}

        protected function getOverrideType(){
            $arr = array() ;
            $arr[] = array ('code'=>'0','desc'=>'Value' );
            $arr[] = array ('code'=>'1','desc'=>'Percentage' ) ;
            $arr[] = array ('code'=>'2','desc'=>'Date' ) ;
            return Util::createOptionValue($arr) ;
        }
        
        protected function getExpItemType(){
            $arr = array() ;
            $arr[] = array ('code'=>'0','desc'=>'Item' );
            $arr[] = array ('code'=>'1','desc'=>'Group' );
            return Util::createOptionValue($arr) ;
        }

        protected function getTravelPlanByEmpId($empId,$default="") {
		$travelCls = new TravelPlanClass($this->db);
		$vls = $travelCls->getEmpTravelPlan($empId, array('code'=>'','desc'=>''));
	
		return Util::createOptionValue($vls, $default) ;
	}
	
/*	protected function getApprovalGroupByUserId($userId,$default="") {
		$approvalGroupCls = new RequestApprovalGroupClass($this->db);
		$vls = $approvalGroupCls->getApprovalGroupList($userId, array());
	
		return Util::createOptionValue($vls, $default) ;
	}*/

	protected function getInvoiceApprovalGroupByUserId($userId,$default="") {
		$approvalGroupCls = new InvoiceApprovalGroupClass($this->db);
		$vls = $approvalGroupCls->getApprovalGroupList($userId, array());
	
		return Util::createOptionValue($vls, $default) ;
	}
	
	protected function getDeptGroup($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select Dept. ---";
		if($isChooseOne == false)
			$textChooseHead = "All";
		return $this->generateOptions(DepartmentTable::C_TABLE, DepartmentTable::C_ID, DepartmentTable::C_DESC,
										"$textChooseHead", $default, $isDesciption);
	}
	
	
	protected function getClaimGroup($default="", $isDesciption = true, $isChooseOne = true){
		$textChooseHead = "--- Select Claim Group ---";
		if($isChooseOne == false)
			$textChooseHead = "--- All Claim Group ---";
		return $this->generateOptions(ClaimGroupTable::C_TABLE, ClaimGroupTable::C_ID, ClaimGroupTable::C_DESC, 
										"$textChooseHead", $default, $isDesciption);
	}
	
	protected function getTravelPlan($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select Travel Plan---";
		if($isChooseOne == false)
			$textChooseHead = "All";
		return $this->generateOptions(TravelPlanTable::C_TABLE, TravelPlanTable::C_ID, TravelPlanTable::C_TITLE, 
										"$textChooseHead", $default, $isDesciption);
	}
	
	protected function getExpenseItem($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select Expense ---";
		if($isChooseOne == false)
			$textChooseHead = "All";
		return $this->generateOptions(ExpenseItemTable::C_TABLE, ExpenseItemTable::C_ID, ExpenseItemTable::C_DESC, 
										"$textChooseHead", $default, $isDesciption);
	}
	
	protected function getCurrency($default="", $isDesciption = true, $isChooseOne = true, $isExchangeRate = false) {
		if($default != ""){
			$currencyClass = new CurrencyClass($this->db);
			$row_cur = $currencyClass->getRecordByRef($default);
			if(!is_null($row_cur)){
				$default = $row_cur[CurrencyTable::C_ID];
			}
		}
		
		if ($isExchangeRate) return $this->generateOptions(CurrencyTable::C_TABLE, CurrencyTable::C_ID, CurrencyTable::C_RATE, 0, $default, $isDesciption, array(array('field'=>CurrencyTable::C_DESC,'type'=>'')),true);
		return $this->generateOptions(CurrencyTable::C_TABLE, CurrencyTable::C_ID, CurrencyTable::C_REF, '', $default, $isDesciption,  array(array('field'=>CurrencyTable::C_DESC,'type'=>'')));
	}
	
	protected function getBank($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select a  Bank ---";
		if($isChooseOne == false)
			$textChooseHead = "All";
		return $this->generateOptions(BankTable::C_TABLE, BankTable::C_ID, BankTable::C_DESC, 
									"$textChooseHead", $default, $isDesciption);
	}
	
	protected function getDepartment($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select Department ---";
		if($isChooseOne == false)
			$textChooseHead = "All Department";
		return $this->generateOptions(DepartmentTable::C_TABLE, DepartmentTable::C_ID, DepartmentTable::C_DESC, 
									"$textChooseHead", $default, $isDesciption);
	}
	
	protected function getCompany($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select a Company ---";
		if($isChooseOne == false)
			$textChooseHead = "All";
		return $this->generateOptions(CompanyTable::C_TABLE, CompanyTable::C_COY_ID, CompanyTable::C_DESC, 
									"$textChooseHead", $default, $isDesciption);
	}
	
	protected function getCountry($default="", $isDesciption = true, $isChooseOne = true) {
		$textChooseHead = "--- Select a Country ---";
		if($isChooseOne == false)
			$textChooseHead = "All";
		return $this->generateOptions(CountryTable::C_TABLE, CountryTable::C_ID, CountryTable::C_DESC, 
									"$textChooseHead", $default, $isDesciption);
	}

	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 getUserEmail() {
		return $this->generateOptions(UserTable::C_TABLE, UserTable::C_ID, UserTable::C_EMAIL, "");
	}
	
	/**
	 * 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
	 */
	private function generateOptions($tableName, $keyField, $descField, $textHeading, $default="", $isDesciption = true, $orderby=null, $isnumber=false) {
		$filter 	= array();
		$filter[] 	= array('field'=>$this->fldorg,'value'=>$this->orgid) ;
		if($tableName == UserTable::C_TABLE)
			$filter[] 	= array('field'=>UserTable::C_EXPIRY_DATE,'value'=>MAX_DATE) ;
		$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 getBaseCurrency($coy_id){
        
		$companyCls	= new CompanyClass($this->db) ;
		$row_com	= $companyCls->getRecord($coy_id) ;
		$opt 		= new CompanyOptions() ;
		$opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
		$op 		= $opt->getOption() ;
		$base_currency 	= intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_BASE_CURRENCY]);
        
        if ($base_currency == ""){
            $base_currency = "SGD";
        }
        
        return $base_currency;
    }
	
	protected function getBaseCurrencyOrg() {
		$cls = new OrganizationClass($this->db) ;
		$row = $cls->getRecord($_SESSION[SE_ORGID]) ;
		if (is_null($row))
			return "SGD";
		
		if (is_null($row[OrganizationTable::C_OPTIONS]) || $row[OrganizationTable::C_OPTIONS] == "") 
			return "SGD";
		
		$opt = new OrganizationOptions() ;
		$opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
		$op = $opt->getOption() ;
		
		return $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_BASE_CURRENCY] == "" ? "SGD" : $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_BASE_CURRENCY];
	}
    
    protected function getDefaultLang(){
        $defaultLang = 1;
        /*
        $langClass = new LanguageTypeClass($this->db);
        $empLangClass = new EmployeeLanguageClass($this->db);
        $rowsLang = $langClass->getTable();
        $rowEmpLang = $empLangClass->getRecordByID($_SESSION[SE_EMPID]);
        if (is_null($rowEmpLang) || count ($rowEmpLang) == 0){
            if (is_null($rowsLang) || count($rowsLang) == 0){
                $empLangClass = $empLangClass->inserRecordByID($_SESSION[SE_EMPID], 1);
                $defaultLang = 1;
            } else {
                $empLangClass = $empLangClass->inserRecordByID($_SESSION[SE_EMPID], $rowsLang[0][LanguageTypeTable::C_ID]);
                $defaultLang = $rowsLang[0][LanguageTypeTable::C_ID];
            }
        }
        else {
            $defaultLang = $rowEmpLang[EmployeeLanguageTable::C_LANG];
        }*/
        return $defaultLang;
    }
    
    protected function convertToLangArray($langRows){
        $langArray 	= array();
    
        if (!is_null($langRows) && count($langRows) > 0) {
            foreach ($langRows as $langRow){
                $langArray[$langRow[LocalLangTermDefinedTable::C_TERM_ID]] = $langRow[LocalLangTermDefinedTable::C_TRANSLATION];
            }
        }
        return $langArray;
    }
    
    
	
	protected function notificationEmailApproval($reqId, $approver_emails, $approver_names, $appType = 0, $appId = 0){
		$userCls        = new UserClass($this->db);
		
		$reqCls         = new ActivityHeaderClass($this->db);
        $companyCls = new CompanyClass($this->db);
        $clsWf       = new WorkFlowClass($this->db);
		$reqHeaderRow   = $reqCls->getRecord($reqId);
		$userId         = $reqHeaderRow[RequestHeaderTable::C_CREATE_BY];
		$userRow        = $userCls->getRecord($userId);
        $workflowId = $reqHeaderRow[RequestHeaderTable::C_WORKFLOW_ID];
        $rowWf      = $clsWf->getRecord($workflowId);
        $company_id = $reqHeaderRow[RequestHeaderTable::C_COMPANY_ID];
        $row_com	= $companyCls->getRecord($company_id) ;
        $opt 		= new CompanyOptions() ;
        $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
        $op 		= $opt->getOption() ;
		
		$preparer_email = $userRow[UserTable::C_EMAIL];
		
		$lines = "Dear " . $approver_names . ", <br><br>";
		$lines .= "There is new request to be approved. <br><br>";
		$lines .= "<table>";
		$lines .= "<tr><td style='text-align:right'>Request # :</td><td>" . $reqHeaderRow[RequestHeaderTable::C_CODE] . "</td></tr>";
		
		$dte = date_create($reqHeaderRow[RequestHeaderTable::C_DATE]);
		
		$lines .= "<tr><td style='text-align:right'>Date :</td><td>" . date_format($dte, 'd/m/Y') . "</td></tr>";
		$lines .= "<tr><td style='text-align:right'>User :</td><td>" . $userRow[UserTable::C_FULL_NAME] . " (" . $userRow[UserTable::C_NAME] . ")" . "</td></tr>";
		$lines .= "</table><br><br>";
		
		$lines .= "Please visit the following URL to approve the request.<br><br>";
		$lines .= $this->getWebPageURL();
            
        /*
        $email_body = file_get_contents(PATH_LIB . "emailApproval.txt");
		$email_body = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_body);
		$email_body = str_replace("{APPROVER_NAMES}", $approver_names, $email_body);
		$email_body = str_replace("{COMPANY_NAME}", $row_com[CompanyTable::C_DESC] . " - " . $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_REF_NO], $email_body);
		$email_body = str_replace("{REQUEST_CODE}", $reqHeaderRow[RequestHeaderTable::C_CODE], $email_body);
		$dte = date_create($reqHeaderRow[RequestHeaderTable::C_DATE]);
		$email_body = str_replace("{REQUEST_DATE}", date_format($dte, 'd/m/Y'), $email_body);
		$email_body = str_replace("{PREPARER}", $userRow[UserTable::C_FULL_NAME] . " (" . $userRow[UserTable::C_NAME] . ")", $email_body);
		*/
		EmailLog::write("Sending email to approver " . $approver_names . " (" . implode(";", $approver_emails) . ") to approve request (" . $reqHeaderRow[RequestHeaderTable::C_CODE] . ")");
        
        $email_header = "{WORKFLOW}-{COMPANY}-{TITLE}";
		$email_header = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_header);
		$email_header = str_replace("{USER_NAME}", $userRow[UserTable::C_FULL_NAME], $email_header);
		$email_header = str_replace("{WORKFLOW}", $rowWf[WorkFlowTable::C_DESC], $email_header);
		$email_header = str_replace("{TITLE}", $reqHeaderRow[RequestHeaderTable::C_TITLE], $email_header);
		$email_header = str_replace("{COMPANY_NAME}", $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_REF_NO], $email_header);
		$email_header = str_replace("{COMPANY}", $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_REF_NO], $email_header);
		$email_header = str_replace("{REQUEST_CODE}", $reqHeaderRow[RequestHeaderTable::C_CODE], $email_header);
		$email_header = str_replace("{ENTER}", "<br />", $email_header);        
		return $this->sendEmail($email_header, 
								$lines,
								explode(";",$preparer_email), 
								$approver_emails,
                                null, 
                                null,
                                $company_id, 
                                $appType,
                                $appId);
	}
    
    
    
    protected function recursiveRemoveDirectory($directory)
    {
        foreach(glob("{$directory}/*") as $file)
        {
            if(is_dir($file)) { 
                recursiveRemoveDirectory($file);
            } else {
                unlink($file);
            }
        }
        //rmdir($directory);
    }
    
/*    protected function deleteTemporaryDocument($userId, $idx = -1){
        if($idx != -1){
            try {
                $cls = new RequestSupplierDetailClass($this->db);

                $tempRows = $cls->getTempDocuments($userId, $idx);
                if (!is_null($tempRows) && count($tempRows) > 0){
                    $tempDirectory = PATH_CLAIM . "temp-" . $userId. "/" . $tempRows[0][RequestSupplierDetailTable::C_SUPPLIER_ATTACH];

                    if(file_exists($tempDirectory)){
                        unlink($tempDirectory);
                    }
                }

                unset($cls);
            } catch(Exception $e){
                Log::write("[deleteTemporaryDocument]" . $e->getMessage());
            }
        } else {
            $tempDirectory = PATH_CLAIM . "temp-" . $userId. "/";
            $this->recursiveRemoveDirectory($tempDirectory);
        }
    }
    */
    protected function deleteAdditionalDocument($reqId){
        
        $tempDirectory = PATH_CLAIM . "additional/" . $reqId. "/";
        
        $this->recursiveRemoveDirectory($tempDirectory);
    }
    
    protected function getCompanyOption(){
        $cls    = new CompanyClass($this->db);
        $rows   = $cls->getTable();
        
		$vls 		= array() ;
		$vls[] 		= array ('code'=>'','desc'=>'-- Select --') ;

		if(!is_null($rows) && count($rows) > 0) {
			foreach ($rows as $row) {
				$opt        = new CompanyOptions() ;
				$opt->loadXml($row[CompanyTable::C_OPTIONS]) ;
				$op         = $opt->getOption() ;
				
				$vls[] 		= array ('code'=>$row[CompanyTable::C_COY_ID],'desc'=>$op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] . " - " . $row[CompanyTable::C_DESC] . " - " . $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_REF_NO]) ;
			}
		}
		
		return Util::createOptionValue($vls, "") ;
    }
    
  //   protected function getEmployeeOption(){
  //       $cls    = new EmployeeClass($this->dbsun);
  //       $rows   = $cls->getAllRecord();
        
		// $vls 			= array() ;
		
		// if(is_null($rows) || count($rows) == 0)
		// 	return null;
		
		// foreach ($rows as $row) {
		// 	$vls[] 		= array ('code'=>$row[EmployeeTable::C_ID],'desc'=>$row[EmployeeTable::C_NAME] . " - " . $row[EmployeeTable::C_ID]) ;
		// }
		// return Util::createOptionValue($vls, "") ;
  //   }

    protected function getPermissionPortal(){
		$clsright=new UserRight() ;
        $clsgroup=new UserGroupClass($this->db);
        $clsright->initRights() ;
        
        if ($_SESSION[SE_USERGROUP] != "") {
            $row = $clsgroup->getRecord($_SESSION[SE_USERGROUP]) ;
            if (!is_null($row)) {
                if (!is_null($row[UserGroupTable::C_RIGHTS]))
                    $clsright->toRights($row[UserGroupTable::C_RIGHTS]); ;
            }
        }
        
        return $clsright->getPortalRight() ;
    }
    
    protected function checkPermissionOtherDepartment($userCreate){
        $clsDeptInter = new DepartmentInterPermissionClass($this->db);
        $clsUser = new UserClass($this->db);

        $deptIdRequest = $clsUser->getRecord($userCreate)[UserTable::C_DEPT];

        $deptId = $clsUser->getRecord($_SESSION[SE_USERID])[UserTable::C_DEPT];
        $listOfDept = $clsDeptInter->getInterPermission($deptId);
        $listOfDept[] = array(
            DepartmentInterPermissionTable::C_INTER => $deptId
        ); 

        $found = false;
        foreach($listOfDept as $deptRow){
            if($deptIdRequest == $deptRow[DepartmentInterPermissionTable::C_INTER]){
                $found = true;
                break;
            }
        }        
        return $found;
    }

    protected function deleteAttachment($id){
            $tempDirectory = PATH_JOBASSIGN . $id. "/";
            $this->recursiveRemoveDirectory($tempDirectory);
	}
	protected function getSchMonth(){
        $arr = array() ;
        for($m=1; $m<=12; ++$m){
            $monthName = date('F', mktime(0, 0, 0, $m, 1));
            $arr[] = array ('code'=>$m,'desc'=>$monthName );
        }
        return Util::createOptionValue($arr) ; 
    }

    protected function getSchYear(){
        $arr = array() ;
        $firstYear = (int)date('Y');
        for($i=$firstYear;$i<=$firstYear +2 ;$i++)
        {
            $arr[] = array ('code'=>$i,'desc'=>$i );
        }
        return Util::createOptionValue($arr) ; 
	}
	
	protected function getDateFilterOption(){
        $arr = array() ;
        $arr[] = array ('code'=>1,'desc'=>"Today" );
        $arr[] = array ('code'=>2,'desc'=>"Yesterday" );
        $arr[] = array ('code'=>3,'desc'=>"Last Week" );
        $arr[] = array ('code'=>4,'desc'=>"Last 2 Month" );
        return Util::createOptionValue($arr) ; 
	}

	protected function getJobVenueOption(){
        $arr = array() ;
        $arr[] = array ('code'=>0,'desc'=>"" );
        $arr[] = array ('code'=>1,'desc'=>"On-Site" );
        $arr[] = array ('code'=>2,'desc'=>"Off-Site" );
        return Util::createOptionValue($arr) ; 
	}	
	
    protected function getCustomerOption(){
        $cls = new CustomerClass($this->db);        
        $rows = $cls->getTable();
        
        $vls   = array() ;
        $vls[] = array ('code'=>"",'desc'=>"-- Select --") ;
        
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[CustomerTable::C_ID],'desc'=>$row[CustomerTable::C_CODE] ." - ". $row[CustomerTable::C_NAME]) ;
            }

            array_multisort(array_map(function($element) {
	    		return strtolower( $element['desc'] );
	  		}, $vls), SORT_ASC, $vls);           
		}		
        return Util::createOptionValue($vls) ;
	}
	
	protected function getPlanScheduleOpt(){
        $arr = array() ;
        $arr[] = array ('code'=>ScheduleType::Daily,'desc'=>"Daily" );
        $arr[] = array ('code'=>ScheduleType::Weekly,'desc'=>"Weekly" );
        $arr[] = array ('code'=>ScheduleType::Monthly,'desc'=>"Monthly" );
        $arr[] = array ('code'=>ScheduleType::Quarterly,'desc'=>"Quarterly" );
        return Util::createOptionValue($arr) ;        
	}

	protected function getCurrencyOption(){
        $cls = new CurrencyClass($this->db);
        
        $rows = $cls->getTable();
        
        $vls   = array() ;
        $vls[] = array ('code'=>"",'desc'=>"-- Select --") ;
        
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[CurrencyTable::C_ID],'desc'=>$row[CurrencyTable::C_REF]) ;
            }

            array_multisort(array_map(function($element) {
	    		return strtolower( $element['desc'] );
	  		}, $vls), SORT_ASC, $vls);           
		}		
        return Util::createOptionValue($vls) ;
	}
	protected function getPaymentTermsOption(){
        $cls = new PaymentTermsClass($this->db);
        
        $rows = $cls->getTable("", PaymentTermsTable::C_DESC);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"",'desc'=>"-- Select --") ;
        $default   	= "" ;
        
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
				if($row[PaymentTermsTable::C_DEFAULT] == 1) {
					$default = $row[PaymentTermsTable::C_ID];
				}
                $vls[] = array ('code'=>$row[PaymentTermsTable::C_ID],'desc'=>$row[PaymentTermsTable::C_DESC]) ;
            }        
		}		
        return Util::createOptionValue($vls, $default) ;
	}
	protected function getInvoiceTitleOption(){
        $cls = new InvoiceTitleClass($this->db);
        
        $rows = $cls->getTable("", InvoiceTitleTable::C_DESC);
        
        $vls   		= array() ;
        $vls[] 		= array('code'=>"",'desc'=>"-- Select --") ;
        $default   	= "" ;
        
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
				if($row[InvoiceTitleTable::C_DEFAULT] == 1) {
					$default = $row[InvoiceTitleTable::C_ID];
				}
                $vls[] = array('code'=>$row[InvoiceTitleTable::C_ID],'desc'=>$row[InvoiceTitleTable::C_DESC]) ;
            }        
		}		
        return Util::createOptionValue($vls, $default) ;
	}
	
	protected function createMenuFunc($href,$desc,$type) {
        return "javascript:showPage('" . Util::convertLink($href) . "','". $desc . "'". ",'" . "$type" . "')" ;
    }

	protected function getSalesQuotationPendingApproval() {
		$cls = new SalesQuotationClass($this->db);
		$rows = $cls->getPendingApprovalList($_SESSION[SE_USERID]);
		if(!is_null($rows) && count($rows)>0){
			return count($rows);
		}
		return 0;
	}

	protected function getSalesQuotationApproval() {
		$cls = new SalesQuotationClass($this->db);
		$rows = $cls->getApprovalList($_SESSION[SE_USERID]);
		if(!is_null($rows) && count($rows)>0){
			return count($rows);
		}
		return 0;
	}
    
    protected function getOptionSalesQuotationStatus(){
        $opt = array() ;
        $opt[] = array('code'=>"",'desc'=>'-- Select --');
        $opt[] = array('code'=>-1,'desc'=>'All');
        $opt[] = array('code'=>SalesQuotationStatus::Open,'desc'=>'Open');
        $opt[] = array('code'=>SalesQuotationStatus::Submitted,'desc'=>'Submitted');
        $opt[] = array('code'=>SalesQuotationStatus::Approved,'desc'=>'Approved');
        $opt[] = array('code'=>SalesQuotationStatus::Rejected,'desc'=>'Rejected');
        $opt[] = array('code'=>SalesQuotationStatus::Issued,'desc'=>'Issued');
        $opt[] = array('code'=>SalesQuotationStatus::Revised,'desc'=>'Revised');
        $opt[] = array('code'=>SalesQuotationStatus::Accepted,'desc'=>'Accepted');
        $opt[] = array('code'=>SalesQuotationStatus::Closed,'desc'=>'Closed');
        return Util::createOptionValue($opt) ;
    }
} 