<?php

require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "activity/ActivityEmailApprovalClass.php");
class PortalServiceReportApproval extends ActivityBase {
    function __construct() {
        $this->db       = $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
        $this->fldorg   = ActivityHeaderTable::C_ORG_ID ;
        $this->orgid    = $_SESSION[SE_ORGID] ;
    }
    
    function __destruct() {
        unset($this->db) ;
    }

    public function processRequest($params) {
		$key = "" ;
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
            $this->dbsun->open() ;
            $this->loadSetting() ;

            Log::write($params);
            if (isset($params) && count($params) > 0) {
                if (isset($params['type']))
                    $this->type = $params['type'] ;
                if (isset($params['id']))
					$key = $params['id'];
            }
			switch ($this->type) {
				case command::PortalReportApproval:
					$this->processApprovalSign($params) ;
					break ;
			
				default:
					$this->sendJsonResponse(Status::Error,"invalid request asdasd.","") ;
					break ;
            }
            
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
    }
    
    private function processApprovalSign($params) {
        ob_start() ;
        $cls =  new ActivityHeaderClass($this->db);
        $clsUser = new UserClass($this->db);
        $companyCls = new CompanyClass($this->db);
        $clsEmail    = new ActivityEmailApprovalClass($this->db); 

        $activity_id = $this->getParamInt($params,'id',0);

        $row = $cls->getRecord($activity_id);
        try {
            $this->db->beginTran() ;
            if(!is_null($row) && count($row)>0){
                //1 mean signed
                if($row[ActivityHeaderTable::C_SIGNED] == ServiceStatus::Approved){
                    $userEmail = $clsUser->getRecord($row[ActivityHeaderTable::C_USER_ID])[UserTable::C_EMAIL];

                    $code = $row[ActivityHeaderTable::C_CODE];
                    $remarks =($row[ActivityHeaderTable::C_SIGNED_REMARKS] !== "" ? "(".$row[ActivityHeaderTable::C_SIGNED_REMARKS] .")": "") ;
                    include (PATH_VIEWS . "portal/email/emailSignedView.php") ;
                    echo Util::minifyHtml(ob_get_clean()) ;

                    return;
                }else{
                    $datas= [];
                    $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED,ServiceStatus::Approved) ; 
                    $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED_DATE,date_create('now')->format('Y-m-d H:i:s')) ; 
                    $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED_REMARKS,"Signed from email ") ;  
                    $to_email = "" ;
                    if($cls->updateRecord($activity_id, $datas)){
                      
                        $company_id     = $row[ActivityHeaderTable::C_COY_ID];
                        $row_com        = $companyCls->getRecord($company_id) ;
                        $opt            = new CompanyOptions() ;
                        $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
                        $op         = $opt->getOption() ;

                        $fromEmail = $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_SENDER];
                        $fromEmailStr = $fromEmail;
                        $fromEmails   = explode(";", $fromEmailStr);

                        $code = $row[ActivityHeaderTable::C_CODE];
                        $rowUser = $clsUser->getRecord($row[ActivityHeaderTable::C_USER_ID]);
                       
                        $rowEmail = $clsEmail->getRecord($activity_id);

                        if( (!is_null($rowUser) && count($rowUser)>0) && (!is_null($rowEmail) && count($rowEmail) > 0)){
                            $email_body = file_get_contents(PATH_LIB . "confirmActivityemail.txt");
                            $email_body = str_replace("{SERVICE_CODE}", trim($code), $email_body);
                           // $email_body = str_replace("{USER_NAME}", trim($rowUser[UserTable::C_FULL_NAME]), $email_body);
                            
                            $userEmail = $rowUser[UserTable::C_EMAIL];
                            $repMail = $rowEmail[ActivityEmailApprovalTable::C_EMAIL_TO];
                            $to_email =  $repMail  ;
                            $result = $this->sendEmail("[NO-REPLY] Service Report Acknowledgment", 
                                                    $email_body,
                                                    $fromEmails, 
                                                    explode(";",$repMail), 
                                                    explode(";",$userEmail),
                                                    null,
                                                    $company_id,
                                                    AppType::Activity,
                                                    $activity_id);
                            if($result){
                                Log::write("[Email Approval] - Successfully notify approver ".$repMail ." & user ".$userEmail);
                            }else{
                                Log::write("[Email Approval] - Failed to notify approver ".$repMail." & user ".$userEmail);
                            }
                        }

                    }
                    $datas= [];
                    $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED_REMARKS,"Signed from email ".  $to_email) ;  

                    $cls->updateRecord($activity_id, $datas);

                    $this->db->commitTran() ;

                    $remarks =($row[ActivityHeaderTable::C_SIGNED_REMARKS] !== "" ? "(".$row[ActivityHeaderTable::C_SIGNED_REMARKS] .")": "") ;
                    include (PATH_VIEWS . "portal/email/emailApprovalView.php") ;
                    echo Util::minifyHtml(ob_get_clean()) ;

                    return;
                }
            }else{
                include (PATH_VIEWS . "portal/email/emailDataNotFoundView.php") ;
                echo Util::minifyHtml(ob_get_clean()) ;
                return;
            }

            

        } catch (Exception $e) {
            $this->db->rollbackTran() ;
            Log::write('[Service Aprroval] ' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, we are unable to process your system as there is a error in database operation.","",$this->type) ;
        }
		
	}

}
?>