<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "admin/CompanyLocationClass.php");
require_once (PATH_MODELS . "activity/goods/GoodsReceivingClass.php");
require_once (PATH_MODELS . "activity/goods/GoodsReceivingDetailClass.php");
require_once (PATH_MODELS . "activity/goods/GoodsReceivingCommunicationClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/goods/ItemClass.php") ;
require_once (PATH_MODELS . "activity/BrandClass.php");
require_once (PATH_MODELS . "activity/ModelClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");
// require_once (PATH_LIB    . 'ImageResize.php');

class PortalGoodsReceiving extends ActivityBase {

    function __construct() {
        $this->db       = $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
        $this->fldid    = GoodsReceivingTable::C_ID ;
        $this->orgid    = $_SESSION[SE_ORGID] ;
    }
    
    function __destruct() {
        unset($this->db) ;
    }
    
    public function processRequest($params) {
        $this->type = REQ_VIEW ;
        try {
            $this->db->open() ;
            $this->dbsun->open() ;
            $this->loadSetting() ;
            if (isset($params) && count($params) > 0) {
                if (isset($params['type']))
                    $this->type = $params['type'] ;
            }
            
            switch ($this->type) {
                case Command::PortalGoodsReceivingAddView:
                    $this->processViewGoodReceivingAdd();
                    break;
                case Command::PortalGoodsReceivingUpdateView:
                    $this->processGoodReceivingUpdateView($params);
                    break;
                case Command::PortalGoodsReceiving:
                    $this->processGoodReceivingInfo() ;
                    break ;
                case Command::PortalGoodsReceivingFilter:
                    $this->processGoodReceivingFilter($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params) ;
                    break ;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalGoodsReceivingDelete:
                    $this->processGoodReceivingDelete($params) ;
                    break ;
                case "C_ADD_GOODS_RECEIVING_INQUIRY_VIEW":
                    $this->InquiryView($params) ;
                    break ;
                case "SHOW_REPORT":
                    $this->printReport($params) ;
                    break ;
                case "GRN_SEND_EMAIL":
                    $this->sendEmailNow($params) ;
                    break ;
                //========================================
                default:
                    $this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
                    break ;
            }
            $this->db->close() ;
            $this->dbsun->close() ;
            return true ;
        } catch (Exception $e) {
            $this->db->close() ;
            $this->dbsun->close() ;
            die ($e->getMessage()) ;
        }
    }
    private function sendEmailNow($params)  {
        $cls            = new GoodsReceivingClass($this->db);
        $clsDetail      = new GoodsReceivingDetailClass($this->db);
        $clsUser        = new UserClass($this->db);
        $clsItem        = new ItemClass($this->db);
        $clsCustomer    = new CustomerClass($this->db);
        $clsCompany     = new CompanyClass($this->db);

        $row = $cls->getRecord($this->getParamInt($params,'grn_id',0));
        
        if(is_null($row)){
            $this->sendJsonResponse(Status::Error,"Cannot find GRN","", $this->type);
            return;
        }
    
        if(trim($row[GoodsReceivingTable::C_CONTACT_EMAIL]) == ""){
            $this->sendJsonResponse(Status::Error,"Please fill customer email before send","", $this->type);
            return;
        }
        
        try{
            $coyId  = $clsUser->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];

            if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::Received) {
                $status = "<span>received</span>";
            } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::QuotationSent){
                $status = "<span>quotation sent</span>";
            } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedQuotation){
                $status = "<span>confiscated quotation</span>";
            } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedDelivery){
                $status = "<span>confiscated delivery</span>";
            } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::InRepair){
                $status = "<span>in repair</span>";
            } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::WaitingRepair){
                $status = "<span>waiting repair</span>";
            } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::WaitingDelivery){
                $status = "<span>waiting delivery</span>";
            } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::Finished){
                $status = "<span>finished</span>";
            }else{
                $status = "<span>unknown</span>";
            }

            $email_body = file_get_contents(PATH_LIB . "emailGoodsReceiving.txt");
            $email_body = str_replace("{NAME}", $row[GoodsReceivingTable::C_CONTACT_NAME], $email_body);
            $email_body = str_replace("{STATUS}", $status, $email_body);
            $email_body = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_body);
            $email_body = str_replace("{CUST}", $clsCustomer->getRecord($row[GoodsReceivingTable::C_CUST_ID])[CustomerTable::C_NAME], $email_body);
            $email_body = str_replace("{NAME}", $row[GoodsReceivingTable::C_CONTACT_NAME], $email_body);
            $email_body = str_replace("{PHONE}", $row[GoodsReceivingTable::C_CONTACT_PHONE], $email_body);
            $email_body = str_replace("{EMAIL}", $row[GoodsReceivingTable::C_CONTACT_EMAIL], $email_body);
            $email_body = str_replace("{COYNAME}", $clsCompany->getRecord($coyId)[CompanyTable::C_DESC], $email_body);

            $date = date_create($row[GoodsReceivingTable::C_DATE])->format('d/m/Y');
            $email_body = str_replace("{DATE}", $date, $email_body);

            $lines = "";
            $rowsDetail = $clsDetail->getGoodsReceivingDetail($row[GoodsReceivingTable::C_ID]);
            if (!is_null($rowsDetail) && count($rowsDetail)>0) {
                foreach ($rowsDetail as $detail) {

                    $item_code = $clsItem->getRecord($detail[GoodsReceivingDetailTable::C_ITEM_ID])[ItemTable::C_CODE];
                   
                    $lines .= '<tr>' ;
                    $lines .= '<td valign="top">'.$item_code .'</td>';
                    $lines .= '<td>'.$detail[GoodsReceivingDetailTable::C_ITEM_DESC] .'<br> <span style="color:blue;">' . $detail[GoodsReceivingDetailTable::C_COMMENT] . '</span></td>';
                    $lines .= '<td valign="top">'.$detail[GoodsReceivingDetailTable::C_ITEM_BRAND] .'</td>';
                    $lines .= '<td valign="top">'.$detail[GoodsReceivingDetailTable::C_SERIAL_NUMBER] .'</td>';
                    $lines .= '<td valign="top">'.$detail[GoodsReceivingDetailTable::C_QTY] .'</td>';
                    $lines .= '</tr>' ;

                }
            }

            $email_body = str_replace("{DETAIL}", $lines, $email_body);
            $email_body = str_replace("{IMAGE}", $this->getLogo(), $email_body);
            // Log::write(print_r($this->getLogo(),true));die();

            $now = new DateTime();
            $year = $now->format("Y");
            $email_body = str_replace("{YEAR}", $year, $email_body);

            $resEmail =  $this->sendEmail("[NO-REPLY] eService Goods Receiving", 
                                            $email_body,
                                            null, 
                                            explode(";",$row[GoodsReceivingTable::C_CONTACT_EMAIL]), 
                                            null,
                                            null,$coyId);
            
            if($resEmail){   
                $this->sendJsonResponse(Status::Ok,"Email has been sent to customer email address.","", $this->type);
            } else {
                $this->sendJsonResponse(Status::Error,"There is an error in sending email", "", $this->type);
            }
        } catch (Exception $e){
            Log::write("[GRN_EMAIL] " . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Unsuccessful database operation","",$this->type) ;
        }
    }
    private function processGoodReceivingInfo() {
        ob_start() ;

        include (PATH_VIEWS . "portal/goodsreceiving/GoodsReceivingInfoView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Goods Receiving" ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);
    }

    private function InquiryView(){
        ob_start() ;
        include (PATH_VIEWS . "portal/goodsreceiving/GoodsReceivingInquiryView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  = Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Goods Receiving Inquiry" ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);
    }

    private function processGoodReceivingFilter($params) {
        $cls        = new GoodsReceivingClass($this->db);
        $custCls    = new CustomerClass($this->db) ;

        $rows = $cls->getGoodReceivingList($params['date'], $params['cust'], $params['grnId']);

        $htmlStr = "";
        
        if(!is_null($rows) || count($rows) > 0){
            
            foreach ($rows as $row) {

                $name = "";
                if(is_null($row[GoodsReceivingTable::C_PROSPECT_NAME]) || $row[GoodsReceivingTable::C_PROSPECT_NAME]=="") {
                    $name = $custCls->getRecord($row[GoodsReceivingTable::C_CUST_ID])[CustomerTable::C_NAME];
                } else {
                    $name = $row[GoodsReceivingTable::C_PROSPECT_NAME];
                }

                $status = "";
                if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::Received) {
                    $status = "<span>Received</span>";
                } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::QuotationSent){
                    $status = "<span>Quotation Sent</span>";
                } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedQuotation){
                    $status = "<span>Confiscated Quotation</span>";
                } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedDelivery){
                    $status = "<span>Confiscated Delivery</span>";
                } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::InRepair){
                    $status = "<span>In Repair</span>";
                } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::WaitingRepair){
                    $status = "<span>Waiting Repair</span>";
                } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::WaitingDelivery){
                    $status = "<span>Waiting Delivery</span>";
                } else if($row[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::Finished){
                    $status = "<span>Finished</span>";
                }

                $btnStr  = "<button  title=\"View\" onclick=\"javascript: showEditGoodsReceiving(" . $row[GoodsReceivingTable::C_ID] .", this);\" id=\"btnEdit\" data-toggle=\"modal\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>"; 
                $btnStr  .= "<button title=\"Delete\" onclick=\"javascript: popupDeleteGoodsReceiving(" . $row[GoodsReceivingTable::C_ID] .", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger glyphicon glyphicon-trash btn-sm\"></button>";
                
                $htmlStr .= "<tr id=\"goods-receiving-rows-" . $row[GoodsReceivingTable::C_ID] . "\">" .
                                    "<td style='display:none'>" . $row[GoodsReceivingTable::C_ID] . "</td>" . 
                                    "<td>". date_create($row[GoodsReceivingTable::C_DATE])->format('d-m-Y') ."</td>" .
                                    "<td>". $name ."</td>" .
                                    "<td>". $row[GoodsReceivingTable::C_CONTACT_NAME] . "<br>" . $row[GoodsReceivingTable::C_CONTACT_PHONE] . "</td>" .
                                    "<td>". $row[GoodsReceivingTable::C_CODE] ."</td>" .
                                    "<td>" . $status . "</td>" .
                                    "<td><div>" . $btnStr . "</div></td>".
                                "</tr>";
            }
        
        }
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }

    private function processViewGoodReceivingAdd() {
        ob_start() ;
        $cls = new UserClass($this->db);
        $clsOrg = new OrganizationClass($this->db) ;

        $rowOrg = $clsOrg->getRecord($_SESSION[SE_ORGID]) ;
        $use_bu=0;
        if (!is_null($rowOrg)) {
            if (!is_null($rowOrg[OrganizationTable::C_OPTIONS]) && $rowOrg[OrganizationTable::C_OPTIONS] != "") {

                $opt = new OrganizationOptions() ;
                $opt->loadXml($rowOrg[OrganizationTable::C_OPTIONS]) ;
                $op = $opt->getOption() ;

                $use_bu=$op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_BU] ;

            }
        }
        
        $loginId = $cls->getRecord($_SESSION[SE_USERID])[UserTable::C_ID];
        $coyId   = $cls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];
        $name    = $cls->getRecord($_SESSION[SE_USERID])[UserTable::C_FULL_NAME];
        $phone   = $cls->getRecord($_SESSION[SE_USERID])[UserTable::C_PHONE];
        $email   = $cls->getRecord($_SESSION[SE_USERID])[UserTable::C_EMAIL];

        $defaultLocation  = $cls->getRecord($_SESSION[SE_USERID])[UserTable::C_COM_LOC];

        include (PATH_VIEWS . "portal/goodsreceiving/GoodsReceivingAddView.php") ;
        $addHeaderContent= array() ;
        $addHeaderContent["all"] =  Util::minifyHtml(ob_get_clean()) ;
        $addHeaderContent["headerData"]["userLoc"] =  $defaultLocation;
        
        $this->sendJsonResponse(Status::Ok,"Goods Receiving Add Content",$addHeaderContent,$this->type);
    }

    private function addRecord($params) {
        $cls           = new GoodsReceivingClass($this->db) ;
        $dtlCls        = new GoodsReceivingDetailClass($this->db) ;
        $comCls        = new GoodsReceivingCommunicationClass($this->db) ;

        $datas      = array() ;
        $orgid      = $_SESSION[SE_ORGID] ;
        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        $ws         = $_SESSION[SE_REMOTE_IP];

        $date = str_replace('/', '-',  $params['date']);
        $time = $date." ".$params['time'];
        $combined = DateTime::createFromFormat('d-m-Y h:i A',$time)->format('Y-m-d H:i:s');

        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_DATE,$combined) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_USER_ID,$this->getParam($params,'user_id',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_USER_LOC_ID,$this->getParam($params,'user_loc',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CUST_ID,$this->getParam($params,'cust_coy',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_STATUS_CUST,$this->getParam($params,'status_cust',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_PROSPECT_NAME,$this->getParam($params,'prospect_name',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CONTACT_NAME,$this->getParam($params,'contact_name',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CONTACT_PHONE,$this->getParam($params,'contact_phone',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CONTACT_EMAIL,$this->getParam($params,'contact_email',"")) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_STATUS,GoodsReceivingStatus::Received) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_WS_ID,$ws) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_MODIFY_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CREATE_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_MODIFY_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CREATE_DATE,$modifydate) ;

        //running number
        $companyCls = new CompanyClass($this->db) ;
        $row_com    = $companyCls->getRecord($params['user_coy']) ;
        $opt        = new CompanyOptions() ;
        $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
        $op         = $opt->getOption() ;
        $max_code   = intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_RN]);
        $result_code = $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_PREFIX] . str_pad($max_code, intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_LENGTH]), "0", STR_PAD_LEFT); 
        $datas[]    = $this->db->fieldValue(GoodsReceivingTable::C_CODE, $result_code) ;

        $detail = $this->getParam($params,'detail',"") ;
        $communication = $this->getParam($params,'communication',"") ;
        
        try {

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

                $this->addGoodsReceivingDetail($id,$detail) ;
                $this->addGoodsReceivingCommunication($id,$communication) ;

                //running number
                $max_code += 1;
                $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_RN] = $max_code;
                $opt->setOption($op) ;

                $data_coy= array() ;
                $data_coy[]    = $this->db->fieldValue(CompanyTable::C_OPTIONS,$opt->getXml());
                $companyCls->updateRecord($params['user_coy'],$data_coy) ;
                //====
                
                $row = $cls->getRecord($id);
                
                $this->sendJsonResponse(Status::Ok,"Goods Receiving successfully added to the system.",$datas,$this->type);
            } else {
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new Goods Receiving to the system.",$id, $this->type) ;
            }
        } catch (Exception $e) {
            Log::write('[Goods Receiving]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
        }
        unset($cls) ;
        unset($dtlCls) ;
        unset($comCls) ;
    }

    private function addGoodsReceivingDetail($id, $detail) {
        $cls = new GoodsReceivingDetailClass($this->db) ;

        if ($detail != "") {
            $lines = explode("|",$detail) ;
            for ($i= 0;$i < count($lines) ;$i++) {
                $line = explode("~",$lines[$i]) ;
                if (count($line) == 6) {
                    $datas = array() ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingDetailTable::C_HEADER_ID,$id);
                    $datas[] = $this->db->fieldValue(GoodsReceivingDetailTable::C_ITEM_ID,$line[0]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingDetailTable::C_ITEM_DESC,$line[1]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingDetailTable::C_SERIAL_NUMBER,$line[2]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingDetailTable::C_QTY,$line[3]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingDetailTable::C_COMMENT,$line[4]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingDetailTable::C_ITEM_BRAND,$line[5]) ;

                    $cls->addRecord($datas) ;
                }
            }
        }
        unset($cls) ;
    }

    private function addGoodsReceivingCommunication($id, $communication) {
        $cls = new GoodsReceivingCommunicationClass($this->db) ;

        if ($communication != "") {
            $lines = explode("|",$communication) ;
            for ($i= 0;$i < count($lines) ;$i++) {
                $line = explode("~",$lines[$i]) ;
                if (count($line) == 4) {
                    $datas = array() ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingCommunicationTable::C_HEADER_ID,$id);
                    $datas[] = $this->db->fieldValue(GoodsReceivingCommunicationTable::C_DATE,$line[0]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingCommunicationTable::C_NAME,$line[1]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingCommunicationTable::C_CONTACT,$line[2]) ;
                    $datas[] = $this->db->fieldValue(GoodsReceivingCommunicationTable::C_METHOD,$line[3]) ;

                    $cls->addRecord($datas) ;
                }
            }
        }
        unset($cls) ;
    }

    private function processGoodReceivingUpdateView($params) {
        ob_start() ;
        $cls        = new GoodsReceivingClass($this->db) ;
        $userCls    = new UserClass($this->db);
        $clsOrg     = new OrganizationClass($this->db) ;

        $id    = $params['id'];
        $row   = $cls->getRecord($id);
        
        $rowOrg = $clsOrg->getRecord($_SESSION[SE_ORGID]) ;
        $use_bu=0;
        if (!is_null($rowOrg)) {
            if (!is_null($rowOrg[OrganizationTable::C_OPTIONS]) && $rowOrg[OrganizationTable::C_OPTIONS] != "") {

                $opt = new OrganizationOptions() ;
                $opt->loadXml($rowOrg[OrganizationTable::C_OPTIONS]) ;
                $op = $opt->getOption() ;

                $use_bu=$op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_BU] ;

            }
        }

        $loginId = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_ID];
        $coyId   = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];
        $name    = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_FULL_NAME];
        $phone   = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_PHONE];
        $email   = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_EMAIL];
        $defaultLocation  = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COM_LOC];

        include (PATH_VIEWS . "portal/goodsreceiving/GoodsReceivingAddView.php") ;
        
        $editHeaderContent = array();
        $editHeaderContent["all"]       =  Util::minifyHtml(ob_get_clean()) ;

        $datas = array();
        $datas['id']             = $row[GoodsReceivingTable::C_ID];
        $datas['loginId']        = $row[GoodsReceivingTable::C_USER_ID];
        $datas['loginCoyId']     = $userCls->getRecord($row[GoodsReceivingTable::C_USER_ID])[UserTable::C_COY_ID];
        $datas['loginName']      = $userCls->getRecord($row[GoodsReceivingTable::C_USER_ID])[UserTable::C_FULL_NAME];
        $datas['loginEmail']     = $userCls->getRecord($row[GoodsReceivingTable::C_USER_ID])[UserTable::C_EMAIL];
        $datas['loginPhone']     = $userCls->getRecord($row[GoodsReceivingTable::C_USER_ID])[UserTable::C_PHONE];
        $datas['userLoc']        = ($row[GoodsReceivingTable::C_USER_LOC_ID] == 0 ? $defaultLocation : $row[GoodsReceivingTable::C_USER_LOC_ID] ) ;
        $datas['status_cust']    = $row[GoodsReceivingTable::C_STATUS_CUST];
        $datas['cust']           = $row[GoodsReceivingTable::C_CUST_ID];
        $datas['prospect']       = $row[GoodsReceivingTable::C_PROSPECT_NAME];
        $datas['prospectname']   = $row[GoodsReceivingTable::C_CONTACT_NAME];
        $datas['prospectphone']  = $row[GoodsReceivingTable::C_CONTACT_PHONE];
        $datas['prospectemail']  = $row[GoodsReceivingTable::C_CONTACT_EMAIL];
        $date = new DateTime($row[GoodsReceivingTable::C_DATE]); 
        $datas['date']           = $date->format('d/m/Y');
        $datas['time']           = $date->format('h:i A');
        
        $datas['detail']        = $this->getGoodsReceivingDetail($id);
        $datas['communication'] = $this->getGoodsReceivingCommunication($id);

        $editHeaderContent["headerData"] =  $datas ;
        
        $this->sendJsonResponse(Status::Ok,"Goods Receiving Edit Content",$editHeaderContent,$this->type);
        unset($cls);
        unset($clsOrg);
        unset($row);
    }

    private function getGoodsReceivingDetail($id) {
        $cls = new GoodsReceivingDetailClass($this->db) ;

        $rows = $cls->getGoodsReceivingDetail($id) ;
        $lines = "" ;
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                
                if (strlen($lines) > 0){
                    $lines .= "|" ;
                }

                $lines .= $row[GoodsReceivingDetailTable::C_ID] . "~" . 
                          $row[GoodsReceivingDetailTable::C_ITEM_ID] . "~" . 
                          $row[GoodsReceivingDetailTable::C_ITEM_DESC] . "~" . 
                          $row[GoodsReceivingDetailTable::C_SERIAL_NUMBER] . "~" . 
                          $row[GoodsReceivingDetailTable::C_QTY] . "~" .
                          $row[GoodsReceivingDetailTable::C_COMMENT] . "~" .
                          $row[GoodsReceivingDetailTable::C_ITEM_BRAND] ;
            }                           
        }
        unset($cls) ;
        return $lines ;
    }

    private function getGoodsReceivingCommunication($id) {
        $cls = new GoodsReceivingCommunicationClass($this->db) ;

        $rows = $cls->getGoodsReceivingCommunication($id) ;
        $lines = "" ;
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                
                if (strlen($lines) > 0){
                    $lines .= "|" ;
                }
                $method = "";
                if($row[GoodsReceivingCommunicationTable::C_METHOD]==1) {
                    $method = "Call";
                } else {
                    $method = "Email";
                }
                $lines .= $row[GoodsReceivingCommunicationTable::C_ID] . "~" . 
                          $row[GoodsReceivingCommunicationTable::C_DATE] . "~" . 
                          $row[GoodsReceivingCommunicationTable::C_NAME] . "~" . 
                          $row[GoodsReceivingCommunicationTable::C_CONTACT] . "~" . 
                          $method . "~" . 
                          $row[GoodsReceivingCommunicationTable::C_METHOD] ;
            }                           
        }
        unset($cls) ;
        return $lines ;
    }

    private function updateRecord($params) {
        if (isset($params['id'])) {
            $id = $params['id'] ;

            $cls      = new GoodsReceivingClass($this->db) ;
            $dtlCls   = new GoodsReceivingDetailClass($this->db) ;
            $comCls   = new GoodsReceivingCommunicationClass($this->db) ;

            try {
                $datas = array() ;
                
                $modifyby   = $_SESSION[SE_USERID] ;
                $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                $ws = $_SESSION[SE_REMOTE_IP] ;

                $date = str_replace('/', '-',  $params['date']);
                $time = $date." ".$params['time'];
                $combined = DateTime::createFromFormat('d-m-Y h:i A',$time)->format('Y-m-d H:i:s');

                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_DATE,$combined) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_USER_ID,$this->getParam($params,'user_id',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_USER_LOC_ID,$this->getParam($params,'user_loc',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CUST_ID,$this->getParam($params,'cust_coy',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_STATUS_CUST,$this->getParam($params,'status_cust',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_PROSPECT_NAME,$this->getParam($params,'prospect_name',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CONTACT_NAME,$this->getParam($params,'contact_name',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CONTACT_PHONE,$this->getParam($params,'contact_phone',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CONTACT_EMAIL,$this->getParam($params,'contact_email',"")) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_STATUS,GoodsReceivingStatus::Received) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CREATE_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(GoodsReceivingTable::C_CREATE_DATE,$modifydate) ;
                
                $detail = $this->getParam($params,'detail',"") ;
                $communication = $this->getParam($params,'communication',"") ;
                Log::write($detail);
                $dtlCls->deleteRecord($id);
                $this->addGoodsReceivingDetail($id,$detail) ;
                $comCls->deleteRecord($id);
                $this->addGoodsReceivingCommunication($id,$communication) ;
                
                $cls->updateRecord($id,$datas) ;
              
                $this->sendJsonResponse(Status::Ok,"Goods Receiving detail successfully updated to the system.",$datas,$this->type) ;
            } catch (Exception $e) {
                Log::write('[Goods Receiving]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Goods Receiving detail to the system.","",$this->type) ;
            }

            unset($cls) ;
            unset($dtlCls) ;
            unset($comCls) ;

        }else {
            $this->sendJsonResponse(Status::Error,"You must supply the Goods Receiving id you wish to update. Please try again.","",$this->type);
        }
    }

    private function processGoodReceivingDelete($params) {
        if (isset($params['id'])) {
            $id = $params['id'] ;

            $cls = new GoodsReceivingClass($this->db) ;
            $dtlCls = new GoodsReceivingDetailClass($this->db) ;
            $comCls = new GoodsReceivingCommunicationClass($this->db) ;

            try {
                $cls->deleteRecord($id) ; 
                $dtlCls->deleteRecord($id);
                $comCls->deleteRecord($id);

                $this->sendJsonResponse(Status::Ok,"Goods Receiving successfully deleted from the system.",$id,$this->type);
            } catch (Exception $e) {
                Log::write('[Goods Receiving]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Goods Receiving record from the system.","",$this->type) ;
            }
            unset($cls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the Goods Receiving id if you wish to delete. Please try again.","",$this->type);
        }
    }

    private function getItemOption(){
        $cls = new ItemClass($this->db);
        $rows = $cls->getTable();

        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"New Item") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[ItemTable::C_ID],'desc'=>$row[ItemTable::C_CODE]) ;
            }           
        }
     
        return Util::createOptionValue($vls) ; 
    }

    private function getItemDescOption(){
        $cls = new ItemClass($this->db);
        $rows = $cls->getTable();

        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"New Item") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[ItemTable::C_ID],'desc'=>$row[ItemTable::C_DESC]) ;
            }           
        }
     
        return Util::createOptionValue($vls) ; 
    }

    private function getItemBrandOption(){
        $cls = new ItemClass($this->db);
        $rows = $cls->getTable();

        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"New Brand") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[ItemTable::C_ID],'desc'=>$row[ItemTable::C_BRAND]) ;
            }           
        }
     
        return Util::createOptionValue($vls) ; 
    }

    private function getLocationOption(){

        $cls = new CompanyLocationClass($this->db);
        $userCls = new UserClass($this->db);

        try {

            $coyId   = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];

            $filter = $this->db->fieldParam(CompanyLocationTable::C_COY_ID) ;
            $value = array() ;
            $value[] = $this->db->valueParam(CompanyLocationTable::C_COY_ID,$coyId) ;
            $rows = $cls->getTable($filter,CompanyLocationTable::C_COY_ID,$value) ;
        
            
            $vls   = array() ;
            $vls[] = array ('code'=>"0",'desc'=>"-- Select a Location --") ;
            
            if(!is_null($rows) || count($rows) > 0) {
                foreach ($rows as $row) {
                    $vls[] = array ('code'=>$row[CompanyLocationTable::C_ID],'desc'=>$row[CompanyLocationTable::C_DESC]) ;
                }           
            }
            return Util::createOptionValue($vls) ;

        }catch (Exception $e) {

            $vls   = array() ;
            $vls[] = array ('code'=>"0",'desc'=>"--- Select a Location ---") ;
            return Util::createOptionValue($vls) ;

        }
    }

    private function printReport($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdf.php');

        // create new PDF document
        $pdf = new RequestPdf("L", PDF_UNIT, "A5", true, 'UTF-8', false);
        
        $pdf->setPrintHeader(false);
        
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // set some language-dependent strings (optional)
        if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            require_once(dirname(__FILE__).'/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('Helvetica', '', 10);

        // add a page
        $pdf->AddPage();

        // set cell padding
        $pdf->setCellPaddings(1, 1, 1, 1);

        // set cell margins
        //$pdf->setCellMargins(1, 1, 1, 1);

        // set color for background
        $pdf->SetFillColor(255, 255, 255);

        $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }

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

        $cls                    = new GoodsReceivingClass($this->db);
        $clsDetail              = new GoodsReceivingDetailClass($this->db);
        $clsItem                = new ItemClass($this->db);
        $clsCustomer            = new CustomerClass($this->db);
        $clsCompany             = new CompanyClass($this->db);
        $clsCompanyLocation     = new CompanyLocationClass($this->db);
        $userCls                = new UserClass($this->db);

        $row = $cls->getRecord($id);

        //get the grn information
        $rowGrn                 = $cls->getRecord($grn_id);

        //company profile
        $coyId = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];
        $rowCompany = $clsCompany->getRecord($coyId) ;
        $opt        = new CompanyOptions() ;
        $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
        $op         = $opt->getOption() ;
        
        $logopath = Util::getCompanyLogoFile(PATH_PICTURE, $coyId);
        if ($logopath != ""){
            $logopath = "../web/picture/company-" . $coyId . "/" . $logopath;
        }

        $userLocation           = $clsCompanyLocation->getRecord($rowGrn[GoodsReceivingTable::C_USER_LOC_ID])[CompanyLocationTable::C_ADDRESS];
        $clsCompanyName         = $clsCompany->getRecord($coyId)[CompanyTable::C_DESC];

        //get customer information
        $rowCustomerName         = $clsCustomer->getRecord($rowGrn[GoodsReceivingTable::C_CUST_ID])[CustomerTable::C_NAME];
        $rowCustomerContact      = $rowGrn[GoodsReceivingTable::C_CONTACT_NAME];
        $rowCustomerPhone        = $rowGrn[GoodsReceivingTable::C_CONTACT_PHONE];
        $rowCustomerEmail        = $rowGrn[GoodsReceivingTable::C_CONTACT_EMAIL];
        $grnCode                 = $rowGrn[GoodsReceivingTable::C_CODE];
        $grnDate                 = date_create($rowGrn[GoodsReceivingTable::C_DATE])->format('d/m/Y');
        $receivedBy              = $userCls->getRecord($rowGrn[GoodsReceivingTable::C_USER_ID])[UserTable::C_FULL_NAME];

        $status = "";
        if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::Received) {
            $status = "Items Received";  
        } else if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::QuotationSent){
            $status = "Quotation Sent";  
        } else if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedQuotation){
            $status = "Confiscated During Quotation";  
        } else if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedDelivery){
            $status = "Confiscated During Delivery";  
        } else if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::InRepair){
            $status = "Items in Repair";  
        } else if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::WaitingRepair){
            $status = "Items is  Waiting for Repair";  
        } else if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::WaitingDelivery){
            $status = "Items is  Waiting to be Delivered";  
        } else if($rowGrn[GoodsReceivingTable::C_STATUS]==GoodsReceivingStatus::Finished){
            $status = "Finished";  
        }

        $pdf = $this->createHeaderGRPreview($pdf,$id, $logopath, $userLocation, $clsCompanyName, $rowCustomerName, $rowCustomerContact, $rowCustomerPhone,$rowCustomerEmail,$grnCode, $grnDate, $receivedBy, $status);
        
        // move pointer to last page
        $pdf->lastPage();

        // ---------------------------------------------------------
        
        //Close and output PDF document
        // if ($outputType == 'save'){
        //     if ($id != 0){
        //         $rows = $cls->getRecord($id);
        //         $grCode = $rows[GoodsReceivingTable::C_CODE];

        //         $path = PATH_GR . $id;
        //         if(!file_exists($path)){
        //             mkdir($path, 1777);
        //         }
        //         $path .= "/" . $grCode . ".pdf";
        //         $pdf->Output($path, 'F');
        //     } else {
        //         $path = PATH_GR . $id;
        //         if(!file_exists($path)){
        //             mkdir($path, 1777);
        //         }
        //         $path .= "/JobCentreUtilizationReport.pdf";
        //         $pdf->Output($path, 'F');
        //     }
        // } else {
            $pdf->Output('GoodsReceivingReport.pdf', 'I');
        // }

        //============================================================+
        // END OF FILE
        //============================================================+
    }

    public function createHeaderGRPreview($pdf,$id, $logopath, $userLocation, $clsCompanyName, $rowCustomerName, 
                                            $rowCustomerContact, $rowCustomerPhone,$rowCustomerEmail, $grnCode, $grnDate, $receivedBy, $status){

        //company 
        $picHeight = 22;
        if ($logopath != ""){
            $pdf->Image($logopath, PDF_MARGIN_LEFT, 10, 0, $picHeight);
        }

        $width = $pdf->GetX()+15;
        $height = $pdf->GetY()-15;
        $pdf->SetFont('calibri', 'b', 13);
        $pdf->MultiCell(80, 5, $clsCompanyName, 0, 'L', 1, 1, $width+PDF_MARGIN_LEFT , $height, true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(80, 5, $userLocation , 0, 'L', 1, 1, $width+PDF_MARGIN_LEFT , "", true);
        // $pdf->MultiCell(80, 5, "Generated on ".date_create('now')->format('d/m/Y'), 0, 'L', 1, 1, $width+PDF_MARGIN_LEFT , "", true);
        
        //GRN detail
        $pdf->SetFont('Helvetica', 'b', 13);
        $pdf->MultiCell(41, 5, "Goods Receiving", 'B', 'L'           , 1, 1, PDF_MARGIN_LEFT+120, $height, true);
        $pdf->SetFont('Helvetica', '', 10);
        $pdf->MultiCell(25, 5, "GRN Number", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 120, $height + 10, true);
        $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 145, $height + 10, true);
        $pdf->MultiCell(40, 5, $grnCode, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 148, $height + 10, true);
        $pdf->MultiCell(25, 5, "GRN Date", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 120, $height + 15, true);
        $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 145, $height + 15, true);
        $pdf->MultiCell(40, 5, $grnDate, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 148, $height + 15, true);
        $pdf->MultiCell(55, 5, "Received by", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 120, $height + 20, true);
        $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 145, $height + 20, true);
        $pdf->MultiCell(40, 5, $receivedBy, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 148, $height + 20, true);
        $pdf->MultiCell(20, 5, "Status", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 120, $height+25, true);
        $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+145, $height+25, true);
        $pdf->MultiCell(40, 5, $status, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+148, $height+25, true);

        //customer
        $height = $pdf->getY();
        $pdf->MultiCell(20, 5, "Customer", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT, $height, true);
        $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+17, $height, true);
        $pdf->MultiCell(80, 5, $rowCustomerName, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+20, $height, true);
        
        $pdf->MultiCell(15, 5, "Name", 0, 'L', 1, 1, PDF_MARGIN_LEFT , $height+7, true);
        $pdf->MultiCell(10, 5, ":", 0, 'L', 1, 1, PDF_MARGIN_LEFT + 11, $height+7, true);
        $pdf->MultiCell(40, 5, $rowCustomerContact, 0, 'L', 1, 1, PDF_MARGIN_LEFT + 14, $height+7, true);
        $pdf->MultiCell(15, 5, "Tel", 0, 'L', 1, 1, PDF_MARGIN_LEFT + 65, $height+7, true);
        $pdf->MultiCell(10, 5, ":", 0, 'L', 1, 1, PDF_MARGIN_LEFT + 75, $height+7, true);
        $pdf->MultiCell(30, 5, $rowCustomerPhone, 0, 'L', 1, 1, PDF_MARGIN_LEFT + 78, $height+7, true);
         $pdf->MultiCell(15, 5, "Email", 0, 'L', 1, 1, PDF_MARGIN_LEFT + 118, $height+7, true);
        $pdf->MultiCell(10, 5, ":", 0, 'L', 1, 1, PDF_MARGIN_LEFT + 128, $height+7, true);
        $pdf->MultiCell(55, 5, $rowCustomerEmail, 0, 'L', 1, 1, PDF_MARGIN_LEFT + 131, $height+7, true);

        $width = $pdf->getPageWidth();
        $pdf->MultiCell($width-33, 5, "", '', 'L', 1, 1, PDF_MARGIN_LEFT, $height+10, true);

        // $pdf->MultiCell(20, 5, "Customer", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT, $picHeight + 15, true);
        // $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+20, $picHeight + 15, true);
        // $pdf->MultiCell(80, 5, $rowCustomerName, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+23, $picHeight + 15, true);
        // $pdf->MultiCell(20, 5, "Name", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT, $picHeight+20, true);
        // $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+20, $picHeight+20, true);
        // $pdf->MultiCell(40, 5, $rowCustomerContact, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+23, $picHeight+20, true);
        // $pdf->MultiCell(20, 5, "Phone", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT, $picHeight+25, true);
        // $pdf->MultiCell(25, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+20, $picHeight+25, true);
        // $pdf->MultiCell(40, 5, $rowCustomerPhone, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+23, $picHeight+25, true);
        // $pdf->MultiCell(20, 5, "Email", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT, $picHeight+30, true);
        // $pdf->MultiCell(35, 5, ":", 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+20, $picHeight+30, true);
        // $pdf->MultiCell(55, 5, $rowCustomerEmail, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT+23, $picHeight+30, true);

        $width = $pdf->getX();
        
        //item detail
        $clsDetail  = new GoodsReceivingDetailClass($this->db);
        $clsItem    = new ItemClass($this->db);

        $first = false;

        $columnSize2 = array(10,25,80,23,28,13);
        $pdf->SetFont('calibri', '', 10);
        $count = 0;
        $counter = 1;
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;
        $first = true;


        //Header Utilzation
        $pdf = $this->createHeaderUtilization($pdf);
        $pdf->SetFont('calibri', '', 10);
        
        $page = 1;
        
        $rowsDetail = $clsDetail->getGoodsReceivingDetail($id);
        if(!is_null($rowsDetail) && count($rowsDetail) > 0){
            $firstTiming = true;
            
            foreach($rowsDetail as $rowDetail){
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                if($rowDetail[GoodsReceivingDetailTable::C_ITEM_ID]==0 ){
                    $item = '-';
                    
                }else{
                    $item = $clsItem->getRecord($rowDetail[GoodsReceivingDetailTable::C_ITEM_ID])[ItemTable::C_CODE];
                }

                $pdf = $this->processStringLineUtilization($pdf, $columnSize2, $rowHeight, $bottomHeight,
                $counter,$item,$rowDetail[GoodsReceivingDetailTable::C_ITEM_DESC],$rowDetail[GoodsReceivingDetailTable::C_SERIAL_NUMBER],$rowDetail[GoodsReceivingDetailTable::C_ITEM_BRAND],$rowDetail[GoodsReceivingDetailTable::C_QTY],$rowDetail[GoodsReceivingDetailTable::C_COMMENT],$firstTiming);
                $firstTiming = false;
                $counter ++;
            }
        }else{

        }
        
        return $pdf;
    }

    public function createHeaderUtilization($pdf){

        $width = $pdf->getPageWidth();
        $height = $pdf->getY();

        // set font
        $pdf->SetFont('calibri', 'b', 17);
        // $pdf->MultiCell($width-40, 5, "", 0, 'C', 1, 1, PDF_MARGIN_LEFT , $height, true);


        $columnSize2 = array(10,25,80,23,28,13);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';

        $pdf->MultiCell($columnSize2[0], 12, "No", $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Item Code',  $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, ' Item Desc',  $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Brand',  $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Serial Number',  $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, 'QTY',  $border, 'L', 1, 0, '', '', true);
        //space
        $pdf->MultiCell(80, 1, '', '', 'C', 1, 1, '', '', true);
    

        return $pdf;
    }

    public function processStringLineUtilization($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$code,$desc,$sn,$brand,$qty,$comment,$firsttiming){
       if($firsttiming){
        $border = "T";
       }else{
        $border = "";
       }
        
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($desc, $columnSize2[3]);
      
        $cal_estimate =($estimated * $rowHeight) + $pdf->GetY()+11;


        if( $cal_estimate > $bottomHeight){
           
            $newpage=true;
        } 


        if ($newpage){ 
          
            $pdf->AddPage();

            $pdf = $this->createHeaderUtilization($pdf);

            $pdf = $this->processStringLineUtilization($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$code,$desc,$sn,$brand,$qty,$comment,$firsttiming);
        }else{

             $pdf = $this->writeLinePDFUtilization($pdf,$border, $columnSize2, $rowHeight, $counter,$code,$desc,$sn,$brand,$qty,$comment,$firsttiming);

        }
                
        return $pdf;
    }

    public function writeLinePDFUtilization($pdf,$border, $columnSize2, $rowHeight, $counter,$code,$desc,$sn,$brand,$qty,$comment,$firsttiming){
        
        $estimated = $pdf->getStringHeight(80,$desc);
        $pdf->SetFont('calibri', '', 10);
        
        $height = $pdf->getY()+5;
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $counter, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $code, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $desc, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $brand, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $sn, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $qty, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell(1, 5, '', '', 'C', 1, 1, '', $height-5, true);

        if($comment!='') {
            $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", '', 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, "", '', 'L'           , 1, 0, '', '', true);
            $pdf->SetTextColor(0,0,255);
            $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, '   '.$comment, '', 'L'           , 1, 0, '', '', true);
            $pdf->SetTextColor(0,0,0);
            $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", '', 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", '', 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "", '', 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell(1, 5, '', '', 'C', 1, 1, '', $height+5, true);
        }
        return $pdf;
    }

    private function getLogo() {
        $userCls  = new UserClass($this->db);
        $coyid  = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];

        $fn = Util::getLogoFile(PATH_PICTURE, "company-".$coyid) ;
        if ($fn == "") {
            return "" ;
        } else  {
            if (get_magic_quotes_gpc()) {
                $image = stripslashes('<img src="http://eservice-repair.sbgcloud.com/web/picture/company-' . $coyid . '/' . $fn. '" width="120px" height="120px"/>');
            }
            else {
                $image = '<img src="http://eservice-repair.sbgcloud.com/web/picture/company-' . $coyid . '/' . $fn. '" width="120px" height="120px" alt=""/>';
            }
            return $image;
        }

    }

    private function getBrandOption(){
        $vls = $this->getValueList(BrandTable::C_TABLE, BrandTable::C_ID, BrandTable::C_DESC,"-- Select a Brand --") ;
        return Util::createOptionValue($vls) ;
        
    }

    private function getModelType(){
        $vls = $this->getValueList(ModelTable::C_TABLE, ModelTable::C_ID, ModelTable::C_DESC,"-- Select a Model --") ;
        return Util::createOptionValue($vls) ;
        
    }
}
?>