<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/goods/GoodsDeliveryClass.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/goods/ItemClass.php") ;
// require_once (PATH_LIB    . 'ImageResize.php');

class PortalGoodsDelivery extends ActivityBase {

	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
		//$this->fldid 	= GoodsDeliveryTable::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::PortalGoodsDelivery:
                    $this->processGoodsDeliveryInfo() ;
                    break ;
				case Command::PortalGoodsDeliveryFilter:
					$this->processGoodDeliveryFilter($params);
                    break;
                case Command::PortalGoodsDeliveryAddView:
                    $this->processViewGoodDeliveryAdd();
                    break;
                case Command::PortalGoodsDeliveryUpdateView:
                    $this->processGoodDeliveryUpdateView($params);
                    break;
				case REQ_ADD:
					$this->addRecord($params) ;
					break ;
				case REQ_UPDATE:
					$this->updateRecord($params) ;
                    break ;
                case REQ_DELETE:
                    $this->processGoodDeliveryDelete($params) ;
                    break ;
                case "POPULATE_GRN":
                    $this->getGrnOption($params) ;
                    break ;
                case "POPULATE_GRN_DETAIL":
                    $this->getGrnHeader($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 processGoodsDeliveryInfo() {
        ob_start() ;
 
        include (PATH_VIEWS . "portal/goodsdeliver/GoodsDeliveryInfoView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Goods Delivery" ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);
	}
	
	private function processGoodDeliveryFilter($params) {
        $cls        = new GoodsDeliveryClass($this->db);
        $custCls    = new CustomerClass($this->db) ;

        $rows = $cls->getGoodDeliveryList($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[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::Received) {
                    $status = "<span>Received</span>";
                } else if($row[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::QuotationSent){
                    $status = "<span>Quotation Sent</span>";
                } else if($row[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedQuotation){
                    $status = "<span>Confiscated Quotation</span>";
                } else if($row[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::ConfiscatedDelivery){
                    $status = "<span>Confiscated Delivery</span>";
                } else if($row[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::InRepair){
                    $status = "<span>In Repair</span>";
                } else if($row[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::WaitingRepair){
                    $status = "<span>Waiting Repair</span>";
                } else if($row[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::WaitingDelivery){
                    $status = "<span>Waiting for Delivery</span>";
                } else if($row[GoodsDeliveryTable::C_STATUS]==GoodsReceivingStatus::Finished){
                    $status = "<span>Finished</span>";
                }

                $btnStr  = "<button  title=\"View\" onclick=\"javascript: showEditGoodsDelivery(" . $row[GoodsDeliveryTable::C_ID] .", this);\" id=\"btnEdit\" data-toggle=\"modal\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>"; 
                $btnStr  .= "<button title=\"Delete\" onclick=\"javascript: deleteGoodsDeliver(" . $row[GoodsDeliveryTable::C_ID] .", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger glyphicon glyphicon-trash btn-sm\"></button>";
                
                $htmlStr .= "<tr id=\"goods-deliver-rows-" . $row[GoodsDeliveryTable::C_ID] . "\">" .
                                    "<td style='display:none'>" . $row[GoodsDeliveryTable::C_ID] . "</td>" . 
                                    "<td>". date_create($row[GoodsDeliveryTable::C_DATE])->format('d-m-Y') ."</td>" .
                                    "<td>". $name ."</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 processViewGoodDeliveryAdd() {
        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/goodsdeliver/GoodsDeliveryAddView.php") ;
        $addHeaderContent= array() ;
        $addHeaderContent["all"] =  Util::minifyHtml(ob_get_clean()) ;
        $addHeaderContent["userLoc"] =  $defaultLocation;
        
        $this->sendJsonResponse(Status::Ok,"Goods Delivery Add Content",$addHeaderContent,$this->type);
    }
    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 getGrnOption($params){

        $cls = new GoodsReceivingClass($this->db);
        $location_id = $this->getParamInt($params,'loc_id',0);
        $grn_id      = $this->getParamInt($params,'grn_id',0);
        $data = [];
        try {

            $filter = $this->db->fieldParam(GoodsReceivingTable::C_USER_LOC_ID) ;
            $value = array() ;
            $value[] = $this->db->valueParam(GoodsReceivingTable::C_USER_LOC_ID,$location_id) ;
            $rows = $cls->getTable($filter,GoodsReceivingTable::C_USER_LOC_ID,$value) ;
        
            
            $vls   = array() ;
            $vls[] = array ('code'=>"0",'desc'=>"--- Select ---") ;
            
            if(!is_null($rows) || count($rows) > 0) {
                foreach ($rows as $row) {
                    $vls[] = array ('code'=>$row[GoodsReceivingTable::C_ID],'desc'=>$row[GoodsReceivingTable::C_CODE]) ;
                }           
            }
            $data['all']    = Util::createOptionValue($vls) ;
            $data['grn_id'] = $grn_id;
            $this->sendJsonResponse(Status::Ok,"Goods Delivery Add Content",$data,$this->type);

        }catch (Exception $e) {

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

            $this->sendJsonResponse(Status::Ok,"Goods Delivery Add Content",$data,$this->type);

		}
    }

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

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

        $rowsHeader = $cls->getRecord($id);
        $dataHeader = [];

        if (!is_null($rowsHeader) && count($rowsHeader)>0) {

            $dataHeader['customer']     = $rowsHeader[GoodsReceivingTable::C_CUST_ID] ;
            $dataHeader['status_cust']  = $rowsHeader[GoodsReceivingTable::C_STATUS_CUST] ;
            $dataHeader['prospect'] = $rowsHeader[GoodsReceivingTable::C_PROSPECT_NAME] ;
            $dataHeader['contact']  = $rowsHeader[GoodsReceivingTable::C_CONTACT_NAME] ;
            $dataHeader['phone']    = $rowsHeader[GoodsReceivingTable::C_CONTACT_PHONE] ;
            $dataHeader['email']    = $rowsHeader[GoodsReceivingTable::C_CONTACT_EMAIL] ;
            $dataHeader['code']     = $rowsHeader[GoodsReceivingTable::C_CODE] ;
            $dataHeader['date']     = date_create($rowsHeader[GoodsReceivingTable::C_DATE])->format('d/m/Y') ;
            $dataHeader['time']     = date_create($rowsHeader[GoodsReceivingTable::C_DATE])->format('H:i A') ;
            $dataHeader['detail']   = $this->getGrnDetail($rowsHeader[GoodsReceivingTable::C_ID]);

        }else{
            $dataHeader['customer']     = "None" ;
            $dataHeader['prospect']     = "None" ;
            $dataHeader['status_cust']  = 1 ;
            $dataHeader['contact']      = "None" ;
            $dataHeader['phone']        = "None" ;
            $dataHeader['email']        = "None" ;
            $dataHeader['code']         = "None" ;
            $dataHeader['date']         = "None" ;
            $dataHeader['time']         = "None" ;
            $dataHeader['detail']       = "" ;
        }

        $this->sendJsonResponse(Status::Ok,"Goods Receiving Edit Content",$dataHeader,$this->type);
    }

    private function getGrnDetail($id) {
        $cls = new GoodsReceivingDetailClass($this->db) ;
        $clsItem = new ItemClass($this->db);
        $rows = $cls->getGoodsReceivingDetail($id) ;
        
        $lines = "" ;
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                
                if (strlen($lines) > 0){
                    $lines .= "|" ;
                }
                $item_code = $clsItem->getRecord($row[GoodsReceivingDetailTable::C_ITEM_ID])[ItemTable::C_CODE];
                $lines .= $row[GoodsReceivingDetailTable::C_ID] . "~" . 
                          $item_code . "~" . 
                          $row[GoodsReceivingDetailTable::C_ITEM_DESC] . "~" . 
                          $row[GoodsReceivingDetailTable::C_SERIAL_NUMBER] . "~" . 
                          $row[GoodsReceivingDetailTable::C_QTY] ."~".
                          $row[GoodsReceivingDetailTable::C_ITEM_BRAND]."~".
                          $row[GoodsReceivingDetailTable::C_COMMENT] ;
            }                           
        }
        unset($cls) ;
        return $lines ;
    }
    private function addRecord($params) {
        $cls        = new GoodsDeliveryClass($this->db);

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

        $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];

        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_GRN_ID,$grn_id) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_REMARK,"") ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_CODE,"") ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_USER_ID,$modifyby) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_USER_LOC_ID,$this->getParamInt($params,'loc_id',0)) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_STATUS,GoodsReceivingStatus::WaitingDelivery) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_WS_ID,$ws) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_MODIFY_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_CREATE_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_MODIFY_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_CREATE_DATE,$modifydate) ;
        try{
            $id = $cls->addRecord($datas) ;
            if ($id > 0) {
                $this->sendJsonResponse(Status::Ok,"Goods Delivery successfully added to the system.",$datas,$this->type);
            }else{
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new Goods Delivery to the system.",$id, $this->type) ;
            }
        } catch (Exception $e) {
            Log::write('[Goods Delivery]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
        }

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

            $cls      = new GoodsDeliveryClass($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] ;

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

                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_GRN_ID,$grn_id) ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_REMARK,"") ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_CODE,"") ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_USER_ID,$modifyby) ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_USER_LOC_ID,$this->getParamInt($params,'loc_id',0)) ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_STATUS,GoodsReceivingStatus::WaitingDelivery) ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(GoodsDeliveryTable::C_MODIFY_DATE,$modifydate) ;
                
                $cls->updateRecord($id,$datas) ;
              
                $this->sendJsonResponse(Status::Ok,"Goods Delivery detail successfully updated to the system.",$datas,$this->type) ;
            } catch (Exception $e) {
                Log::write('[Goods Delivery]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Goods Delivery detail to the system.","",$this->type) ;
            }

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

        }else {
            $this->sendJsonResponse(Status::Error,"You must supply the Goods Delivery id you wish to update. Please try again.","",$this->type);
        }
    }
    private function processGoodDeliveryUpdateView($params) {
        ob_start() ;
        $cls        = new GoodsDeliveryClass($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/goodsdeliver/GoodsDeliveryAddView.php") ;
        
        $editHeaderContent = array();
        $editHeaderContent["all"]       =  Util::minifyHtml(ob_get_clean()) ;
        
        
        $editHeaderContent['id']             = $row[GoodsDeliveryTable::C_ID];
        $editHeaderContent['grn_id']         = $row[GoodsDeliveryTable::C_GRN_ID];
        $editHeaderContent["userLoc"]        = ($row[GoodsDeliveryTable::C_USER_LOC_ID] != 0 ? $row[GoodsDeliveryTable::C_USER_LOC_ID] : $defaultLocation ) ;
        $this->sendJsonResponse(Status::Ok,"Goods Delivery Edit Content",$editHeaderContent,$this->type);
        unset($cls);
        unset($clsOrg);
        unset($row);
    }

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

            $cls = new GoodsDeliveryClass($this->db) ;

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

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