<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_LIB . 'LicenseFile.php') ;
require_once (PATH_MODELS . "admin/OrganizationClass.php") ;
require_once (PATH_MODELS . "admin/OrganizationOptions.php") ;
require_once (PATH_LIB 	  . "class.phpmailer.php");
require_once (PATH_LIB . "NotificationCentre.php");
class Setting extends ControllerBase {
	private $type = "" ;
	private $datas = array() ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = "v" ;
		
		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_UPDATE:
					$this->updateRecord($params) ;
					break ;
				case REQ_GET:
					$this->getRecord() ;
					break ;
				case REQ_DELETE:
					$this->removeLogo($params) ;
					break ;
				case REQ_VIEW:
					$this->getView() ;
					break ;

				case "TEST_EMAIL":
					$this->testEmail($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 testEmail($params)
	{
		$datas = array();
		$datas['mailserver']= $this->getParam($params,'mailServer','') ;
		$datas['mailuser'] 	= $this->getParam($params,'mailUser','') ;
		$datas['mailpwd'] 	= $this->getParam($params,'mailPwd','');
		$datas['ea'] = $this->getParamInt($params,'ea',0);
		$datas['port'] = $this->getParam($params,'mailPort','');
		$datas['ssl'] = $this->getParamInt($params,'ssl',0) ;
		$recipientEmails=[];
		$recipientEmails[] = $this->getParam($params,'to','');
	

		$email_body = "Hello, this is testing email";
		$email_header = "[Claim Email Testing] " ;
		
		EmailLog::write("Sending  test email to ".$recipientEmails[0]);

		$clsNc = new NotificationCentre();
		$result = $clsNc->sendEmail($email_header, $email_body ,$datas['mailuser'], $recipientEmails, null, null, 0, $datas, AppName::Claim, AppType::Claim);
		$mesg = "send by notification centre";
		if (!$result) {
			$result = $this->sendEmailManualSetting($email_header, $email_body ,$datas['mailuser'], null, $recipientEmails, null, 0,$datas);
			$mesg = "send by php mailer";
		}

		$status = ($result ? "success":"failed");

		$this->sendJsonResponse(Status::Ok,$mesg.", ".$status,"",$this->type);
		
	}
	protected function sendEmailManualSetting($subject, $message,$fromEmails, $ccEmails, $recipientEmails, $attachmentList, $companyId,$mailConfig) {
		$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 	  = $mailConfig;
        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) == 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;
		}
	}
	private function updateRecord($params) {
		$cls = new OrganizationClass($this->db) ;
		$opts = new OrganizationOptions() ;		
		try {
			$datas = array() ;
			$modifyby = $_SESSION[SE_USERID] ;
			$modifydate = date_create('now')->format('Y-m-d H:i:s') ;
			$ws = $_SERVER['REMOTE_ADDR']; 
			$op = array() ;
			$op[OrganizationOptions::C_CONTACT] = $this->getContactOpt($params) ;
			$op[OrganizationOptions::C_SETTING] = $this->getSettingOpt($params) ;			
			$opts->setOption($op) ;
			$datas[] = $this->db->fieldValue(OrganizationTable::C_CODE, $this->getParam($params,'code',"")) ;
			$datas[] = $this->db->fieldValue(OrganizationTable::C_OPTIONS,$opts->getXml());
			$datas[] = $this->db->fieldValue(OrganizationTable::C_WS_ID,$ws) ;
			$datas[] = $this->db->fieldValue(OrganizationTable::C_MODIFY_BY,$modifyby) ;
			$datas[] = $this->db->fieldValue(OrganizationTable::C_MODIFY_DATE,$modifydate) ;
			$check = $cls->getTable() ;
			if (!$check) {
				try {
					/*insert if identity is disabled*/
					$datas[] = $this->db->fieldValue(OrganizationTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
					$id = $cls->addRecord($datas) ;
				} catch (Exception $e) {
					/*insert if identity is enabled*/
					unset($datas[count($datas)-1]);
					$id = $cls->addRecord($datas) ;
				}
				
			}else{
				$cls->updateRecord($_SESSION[SE_ORGID],$datas) ;
			}			
			$this->sendJsonResponse(Status::Ok,"System Setting successfully updated to the system.","",$this->type) ;
		} catch (Exception $e) {
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating system setting to the system.","",$this->type) ;
		}
		unset($coy) ;
	}
	private function getContactOpt($params) {
		$op = array() ;
		$op[OrganizationOptions::C_CONT_NAME1] = $this->getParam($params,'name1',"") ;
		$op[OrganizationOptions::C_CONT_NAME2] = $this->getParam($params,'name2',"") ;
		$op[OrganizationOptions::C_CONT_ADDR1] = $this->getParam($params,'addr1',"") ;
		$op[OrganizationOptions::C_CONT_ADDR2] = $this->getParam($params,'addr2',"") ;
		$op[OrganizationOptions::C_CONT_ADDR3] = $this->getParam($params,'addr3',"") ;
		$op[OrganizationOptions::C_CONT_ADDR4] = $this->getParam($params,'addr4',"") ;
		$op[OrganizationOptions::C_CONT_ADDR5] = $this->getParam($params,'addr5',"") ;
		$op[OrganizationOptions::C_CONT_TEL]   = $this->getParam($params,'telno',"") ;
		$op[OrganizationOptions::C_CONT_FAX]   = $this->getParam($params,'faxno',"") ;
		$op[OrganizationOptions::C_CONT_EMAIL] = $this->getParam($params,'email',"");
		$op[OrganizationOptions::C_CONT_WEB]   = $this->getParam($params,'website',"");
		
		return $op ;
	}
	private function getSettingOpt($params) {
		
		$op = array() ;
		$op[OrganizationOptions::C_SET_FAIL_COUNT]                      = $this->getParamInt($params,'failcount',3) ;
		$op[OrganizationOptions::C_SET_REF_NO]                          = $this->getParam($params,'refno',"");
		$op[OrganizationOptions::C_SET_LIC]                             = "" ;
		$op[OrganizationOptions::C_EMAIL_SERVER]                        = $this->getParam($params,'mailServer',"") ;
		$op[OrganizationOptions::C_EMAIL_PORT]                        	= $this->getParam($params,'mailPort',"") ;
		$op[OrganizationOptions::C_EMAIL_USER]                          = $this->getParam($params,'mailUser',"");
		$op[OrganizationOptions::C_EMAIL_PWD]                           = $this->getParam($params,'mailPwd',"");
		$op[OrganizationOptions::C_EMAIL_RESEND]                        = $this->getParam($params,'resend',"");
		$op[OrganizationOptions::C_EMAIL_ENABLE_AUTHENTICATION] 	 	= $this->getParam($params,'ea',"");
		$op[OrganizationOptions::C_EMAIL_SSL] 	 						= $this->getParam($params,'ssl',"");
		$op[OrganizationOptions::C_UPLOAD_SIZE_LIMT]                    = $this->getParam($params,'upload_size_limit',"");
		$op[OrganizationOptions::C_BASE_CURRENCY]                       = $this->getParam($params,'base_currency',"");
		$op[OrganizationOptions::C_CLAIM_DAY_LAST]                      = $this->getParam($params,'claim_day_last',"");
		$op[OrganizationOptions::C_ALLOW_DELETE_MASTER]                 = $this->getParam($params,'allow_delete_master',"");
		$op[OrganizationOptions::C_USE_PAYMENT_REFERENCE]               = $this->getParam($params,'use_payment_reference',"");
		$op[OrganizationOptions::C_USE_TAX_CALCULATION]                 = $this->getParam($params,'use_tax_calculation',"");
		$op[OrganizationOptions::C_USE_TAX_GREY]          			    = $this->getParam($params,'use_tax_grey',"");
		
		$op[OrganizationOptions::C_ALLOW_FUTURE_DATE]          			= $this->getParam($params,'allow_future_date',"");
		$op[OrganizationOptions::C_EMP_CODE_TO_EXPORT]                  = $this->getParam($params,'emp_code_to_export',"");
		$op[OrganizationOptions::C_LIMIT_TYPE]                  		= $this->getParam($params,'limit_type',"1");

		$op[OrganizationOptions::C_MAX_PASSWORD_AGE]                  	= $this->getParamInt($params,'max_password_age',1);
		return $op ;
	}
	private function getRecord() {
		$cls = new OrganizationClass($this->db) ;
		$row = $cls->getRecord($_SESSION[SE_ORGID]) ;
		$this->datas['name1'] = "";
		$this->datas['name2'] = "" ;
		$this->datas['addr1'] = "" ;
		$this->datas['addr2'] = "";
		$this->datas['addr3'] = "" ;
		$this->datas['addr4'] = "";
		$this->datas['addr5'] = "" ;
		$this->datas['failcount'] = "3";
		$this->datas['code']  = "";
		$this->datas['refno'] = "" ;
		$this->datas['telno'] = "" ;
		$this->datas['faxno'] = "" ;
		$this->datas['mailserver'] 	= "" ;
		$this->datas['mailport'] 	= "25" ;
		$this->datas['mailuser'] 	= "" ;
		$this->datas['mailpwd'] 	= "" ;
		$this->datas['resend'] 	= "" ;
		$this->datas['ea'] 	= "" ;
		$this->datas['ssl'] 	= "" ;
		$this->datas['claim_day_last'] 	= "30" ;
		$this->datas['allow_delete_master'] 	= "" ;
		$this->datas['use_tax_calculation'] 	= "0" ;
		$this->datas['use_tax_grey'] 	= "0" ;
		$this->datas['allow_future_date'] 	= "0" ;
		$this->datas['emp_code_to_export'] 	= "0" ;
		$this->datas['use_payment_reference'] 	= "";
		$this->datas['base_currency']           = "";
		$this->datas['upload_size_limit']       = "" ;
		$this->datas['limit_type']       = "1" ;
		$this->datas['max_password_age']       = "1" ;
		if (!is_null($row)) {
			if (!is_null($row[OrganizationTable::C_OPTIONS]) && $row[OrganizationTable::C_OPTIONS] != "") {
				$this->datas['code'] = $row[OrganizationTable::C_CODE] ;
				$opt = new OrganizationOptions() ;
				if(!is_null($row) && count($row) > 0)
					$opt->loadXml($row[OrganizationTable::C_OPTIONS]) ;
				$op = $opt->getOption() ;
				$this->datas['name1']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_NAME1] ;
				$this->datas['name2']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_NAME2] ;
				$this->datas['addr1']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_ADDR1] ;
				$this->datas['addr2']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_ADDR2] ;
				$this->datas['addr3']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_ADDR3] ;
				$this->datas['addr4']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_ADDR4] ;
				$this->datas['addr5']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_ADDR5] ;
				$this->datas['telno']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_TEL] ;
				$this->datas['faxno']                   = $op[OrganizationOptions::C_CONTACT][OrganizationOptions::C_CONT_FAX] ;
				$this->datas['failcount']               = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_SET_FAIL_COUNT] ;
				$this->datas['refno']                   = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_SET_REF_NO] ;
				$this->datas['mailserver']              = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SERVER] ;
				$this->datas['mailport']      		    = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PORT] ;
				$this->datas['mailuser']                = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_USER] ;
				$this->datas['mailpwd']                 = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_PWD] ;
				$this->datas['resend']                  = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_RESEND] ;
				$this->datas['ea']                      = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_ENABLE_AUTHENTICATION] ;
				$this->datas['ssl']                     = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMAIL_SSL] ;
				$this->datas['upload_size_limit']       = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_UPLOAD_SIZE_LIMT] ;
				$this->datas['base_currency']           = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_BASE_CURRENCY] ;
				$this->datas['claim_day_last']          = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_CLAIM_DAY_LAST] ;
				$this->datas['allow_delete_master'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_ALLOW_DELETE_MASTER] ;
				$this->datas['use_payment_reference'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_PAYMENT_REFERENCE] ;
				$this->datas['use_tax_calculation'] 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_TAX_CALCULATION] ;
				$this->datas['use_tax_grey']		 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_TAX_GREY] ;
				$this->datas['allow_future_date']	 	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_ALLOW_FUTURE_DATE] ;
				$this->datas['emp_code_to_export']      = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_EMP_CODE_TO_EXPORT] ;
				$this->datas['limit_type']      		= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_LIMIT_TYPE] ;
				$this->datas['max_password_age']      	= $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_MAX_PASSWORD_AGE] ;
				//Log::write($this->datas['limit_type']);
				unset($opt) ;
			}
		}
		unset($cls) ;
		unset($row) ;
	}
	private function getName1() {
		return $this->datas['name1'] ;
	}
	private function getName2() {
		return $this->datas['name2'] ;
	}
	private function getAddr1() {
		return $this->datas['addr1'] ;
	}
	private function getAddr2() {
		return $this->datas['addr2'] ;
	}
	private function getAddr3() {
		return $this->datas['addr3'] ;
	}
	private function getAddr4() {
		return $this->datas['addr4'] ;
	}
	private function getAddr5() {
		return $this->datas['addr5'] ;
	}
	private function getFailCount() {
		return $this->datas['failcount'] ;
	}
	private function getCode() {
		return $this->datas['code'] ;
	}
	private function getRefNo() {
		return $this->datas['refno'] ;
	}
	private function getTelNo() {
		return $this->datas['telno'] ;
	}
	private function getFaxNo() {
		return $this->datas['faxno'] ;
	}
	private function getEmailServer() {
		return $this->datas['mailserver'] ;
	}
	private function getEmailPort() {
		return isset($this->datas['mailport']) ? $this->datas['mailport']:"" ;
	}
	private function getEmailUser() {
		return $this->datas['mailuser'] ;
	}
	private function getEmailPwd() {
		return $this->datas['mailpwd'] ;
	}
	private function getEnableAuthentication() {
		return ($this->datas['ea'] == '1') ? 'checked' : "";
	}
	private function getEmailSSL() {
		return (isset($this->datas['ssl']) && $this->datas['ssl'] == '1') ? 'checked' : "";
	}
	private function getEmaiResend() {
		return (isset($this->datas['resend']) && $this->datas['resend'] == '1') ? 'checked' : "";
	}
	private function getAllowDeleteMaster() {
		return ($this->datas['allow_delete_master'] == '1') ? 'checked' : "";
	}
	private function getClaimUsePaymentReference() {
		return ($this->datas['use_payment_reference'] == '1') ? 'checked' : "";
	}
	private function getTaxCalculation() {
		return ($this->datas['use_tax_calculation'] == '1') ? 'checked' : "";
	}
	private function getTaxGrey() {
		return ($this->datas['use_tax_grey'] == '1') ? 'checked' : "";
	}
	private function getFutureDate() {
		return ($this->datas['allow_future_date'] == '1') ? 'checked' : "";
	}
	private function getUploadSizeLimit() {
		return floatval($this->datas['upload_size_limit']) == 0 ? 5000 : floatval($this->datas['upload_size_limit']);
	}
	private function getBaseCurrency() {
		return $this->datas['base_currency'] ;
	}
	private function getMaxPasswordAge() {
		return $this->datas['max_password_age'] ;
	}
	private function getClaimDayLast() {
		return intval($this->datas['claim_day_last']) == 0 ? 30 : intval($this->datas['claim_day_last']);
	}
	private function getLimitTypeData() {
		
		return $this->datas['limit_type'] ;
	}
	private function removeLogo($params=null) {
		Util::removeLogoFile(PATH_PICTURE . 'company_' , $_SESSION[SE_ORGID]) ;
		$this->sendJsonResponse(Status::Ok,"Logo successfully removed from the system.","",$this->type) ;
	}
	private function getView() {
		$this->getRecord();
		ob_start() ;
		include (PATH_VIEWS . "admin/SettingView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
    
    private function getEmpCodeToExportSelection(){
		$arr = array() ;
		$arr[] = array ('code'=>'0','desc'=>'Use Employee Code' );
		$arr[] = array ('code'=>'1','desc'=>'Use Employee FIN' ) ;
		return Util::createOptionValue($arr) ;
    }
    
    private function getEmpCodeToExportSelected(){
		return $this->datas['emp_code_to_export'];
    }

    private function getLimitTypeOption() {
		$arr = array() ;
		$arr[] = array ('code'=>'1','desc'=>'Show All' );
		$arr[] = array ('code'=>'0','desc'=>'Per Claim' ) ;
		$arr[] = array ('code'=>'4','desc'=>'Yearly' ) ;
		return Util::createOptionValue($arr) ;
	}
}
?>