<?php

use GPBMetadata\Google\Protobuf\Wrappers;

require_once (PATH_CONTROLLERS 	. "Common.php") ;
require_once (PATH_LIB . "LicenseFile.php");
require_once (PATH_MODELS . "customer/CustomerScheduleClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftDeliveryClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftDetailClass.php") ;
require_once (PATH_MODELS . "customer/CustomerScheduleClass.php") ;

class CorporateGiftInquiryReport extends GLBase {
	private $type = "" ;
	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
		$this->orgid 	= $_SESSION[SE_ORGID] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = Command::CorporateGiftInquiryView ;
		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 Command::CorporateGiftInquiryView:
					$this->processCorporateGiftInquiryReportInfo($params) ;
					break ;
				case Command::CorporateGiftInquiryFilter:
					$this->processCorporateGiftInquiryReportFilter($params) ;
					break ;
				case REQ_GET:
					$this->getScheduleDetail($params) ;
					break ;
				case REQ_UPDATE:
					$this->updateSchedule($params) ;
					break ;
				case "GET_DELIVERY_TIME":
					$this->getDeliveryTime($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 processCorporateGiftInquiryReportInfo($params) {
		ob_start() ;
		include (PATH_VIEWS . "report/CorporateGiftInquiryReportView.php") ;

		$action_menu = "";

		$var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        $dataReturn	= [];
		$dataReturn['htmlContent'] = $var_screen;
		$dataReturn['action_menu'] = $action_menu;
        $dataReturn['headTitle']  = "Corporate Gift Inquiry" ;
		$this->sendJsonResponse(Status::Ok,"Load Corporate Gift Inquiry Info",$dataReturn,$this->type);
    }

    private function processCorporateGiftInquiryReportFilter($params) {
		$cls 			= new CustomerScheduleClass($this->db) ;

		$name			= $params['name'] ;
		$phone			= $params['phone'] ;
		$delivery_from	= $params['delivery_from'] ;
		$delivery_to    = $params['delivery_to'] ;
		$gift    		= $params['gift'] ;

		$rows = $cls->getCorporateGiftInquiry($name, $phone, $delivery_from, $delivery_to, $gift);
		$htmlContent = $this->convertCorporateGiftInquiryToHtmlTable($rows);
		$this->sendJsonResponse(Status::Ok,"",$htmlContent,$this->type);
		unset($list);
	}

	private function convertCorporateGiftInquiryToHtmlTable($list) {
		// Define common padding style for table cells
		$cellStyle = "padding-left:8px!important;padding-right:3px!important;padding-top:5px!important;";
		
		$htmlStr = "<thead style='background-color: grey;color:white;'>" .
					"<tr>" .
						"<th style='min-width:100px;'>Delivery Date & Time</th>".
						"<th style='min-width:200px;'>Company</th>".
						"<th style='min-width:200px;'>Company Address</th>".
						"<th style='min-width:100px;'>Name</th>".
						"<th style='min-width:50px;'>Mobile</th>".
						"<th style='min-width:50px;'>Phone</th>".
						"<th style='min-width:100px;'>Gift Type</th>".
						"<th style='min-width:50px;'>Total Gift</th>".
						"<th style='min-width:200px;'>Remarks</th>".
						"<th style='min-width:50px;'></th>".
					"</tr>";
		$htmlStr .=	"</thead> <tbody>";

		$current_date = "";
		$total_gift	  = 0;
		if(!is_null($list) && count($list) > 0){
			foreach($list as $row) {
				if($current_date == ""){
					$current_date = $row[CustomerScheduleTable::C_DELIVERY_DATE];
				}
				if($current_date != $row[CustomerScheduleTable::C_DELIVERY_DATE]){
					$htmlStr .= '<tr>' .
									'<td style="' . $cellStyle . ' font-weight: bold;" colspan=7> Total Gift on ' . date_create($current_date)->format('d/m/Y') . '</td>' .
									'<td style="' . $cellStyle . ' font-weight: bold;" colspan=3>' . $total_gift . '</td>' .
								'</tr>';
					$current_date = $row[CustomerScheduleTable::C_DELIVERY_DATE];
					$total_gift	  = $row[CustomerScheduleTable::C_GIFT_AMOUNT];
					
				}else{
					$total_gift += $row[CustomerScheduleTable::C_GIFT_AMOUNT];
				}

				$htmlStr .= '<tr>' .
								'<td style="' . $cellStyle . '">' 
									. date_create($row[CustomerScheduleTable::C_DELIVERY_DATE])->format("d/m/Y") . '<br>'
									. $row[CustomerScheduleTable::C_DELIVERY_TIME] .
								'</td>' .
								'<td style="' . $cellStyle . '">' . $row[CustomerTable::C_NAME] . '</td>' .
								'<td style="' . $cellStyle . ' white-space:pre">' . $row[CustomerTable::C_ADDRESS] . '</td>' .
								'<td style="' . $cellStyle . '">' . $row[CustomerContactTable::C_PREFER_NAME] . '</td>' .
								'<td style="' . $cellStyle . '">' . $row[CustomerContactTable::C_MOBILE] . '</td>' .
								'<td style="' . $cellStyle . '">' . $row[CustomerContactTable::C_TELEPHONE] . '</td>' .
								'<td style="' . $cellStyle . '">' . $row[CorporateGiftDetailTable::C_ITEM_NAME] . '</td>' .
								'<td style="' . $cellStyle . '">' . $row[CustomerScheduleTable::C_GIFT_AMOUNT] . '</td>' .
								'<td style="' . $cellStyle . '">' . $row[CustomerScheduleTable::C_REMARKS] . '</td>' .
								'<td style="' . $cellStyle . '"><a href="javascript:" onclick="popupUpdateSchedule('.$row[CustomerScheduleTable::C_ID].');">Edit</a></td>' .
							'</tr>';
			}
			$htmlStr .= '<tr>' .
					'<td style="' . $cellStyle . ' font-weight: bold;" colspan=7> Total Gift on ' . date_create($current_date)->format('d/m/Y') . '</td>' .
					'<td style="' . $cellStyle . ' font-weight: bold;" colspan=3>' . $total_gift . '</td>' .
				'</tr>';

			$htmlStr .='</tbody>';
		}

		return $htmlStr;
	}

	private function getScheduleDetail($params){
		$cls 		 = new CustomerScheduleClass($this->db);
		$clsDelivery = new CorporateGiftDeliveryClass($this->db);
		$clsDetail 	 = new CorporateGiftDetailClass($this->db);
		$row         = $cls->getCorporateGiftDetailByID($params['id']);
		
		$rowsDetail = $clsDetail->getCorporateGiftDetailByGiftID($row[CustomerScheduleTable::C_GIFT_MASTER_ID]);
		$vls[] = array('code'=>'', 'desc'=>'-- Select Gift Type --');
		foreach($rowsDetail as $rowDetail){
			$vls[] 		= array ('code'=>$rowDetail[CorporateGiftDetailTable::C_DETAIL_ID],'desc'=>$rowDetail[CorporateGiftDetailTable::C_ITEM_NAME]) ;
		}

		$rowsDelivery = $clsDelivery->getDeliveryTimeByGiftID($row[CustomerScheduleTable::C_GIFT_MASTER_ID]);
		$vlsDelivery[]= array('code'=>'', 'desc'=>'-- Select Delivery Date --');
		foreach($rowsDelivery as $rowDelivery){
			$vlsDelivery[] = array('code'=>$rowDelivery[CorporateGiftDeliveryTable::C_DATE], 'desc'=>date_create($rowDelivery[CorporateGiftDeliveryTable::C_DATE])->format('d/m/Y'));
		}

		$rowsDeliveryTime = $clsDelivery->getDeliveryTimeByGiftID($row[CustomerScheduleTable::C_GIFT_MASTER_ID], $row[CustomerScheduleTable::C_DELIVERY_DATE]);
		$vlsDeliveryTime[]= array('code'=>'', 'desc'=>'-- Select Delivery Time --');
		foreach($rowsDeliveryTime as $rowDeliveryTime){
			$vlsDeliveryTime[] = array('code'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME1], 'desc'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME1]);
			$vlsDeliveryTime[] = array('code'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME2], 'desc'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME2]);
		}
	
		$datas = [];
		$datas['id'] 				= $row[CustomerScheduleTable::C_ID];
		$datas['customer_name'] 	= $row[CustomerTable::C_NAME];
		$datas['customer_address'] 	= $row[CustomerTable::C_ADDRESS];
		$datas['contact_name'] 		= $row[CustomerContactTable::C_PREFER_NAME];
		$datas['contact_phone'] 	= $row[CustomerContactTable::C_MOBILE];
		$datas['contact_email'] 	= $row[CustomerContactTable::C_EMAIL];
		$datas['total_diary'] 		= $row[CustomerScheduleTable::C_GIFT_AMOUNT];
		$datas['gift_id'] 			= $row[CustomerScheduleTable::C_GIFT_MASTER_ID];
		$datas['gift_type'] 		= Util::createOptionValue($vls, $row[CustomerScheduleTable::C_CHOSEN_GIFT_ITEM]);
		$datas['remarks'] 			= $row[CustomerScheduleTable::C_REMARKS];
		$datas['email_date'] 		= date_create($row[CustomerScheduleTable::C_EMAIL_DATE])->format('d/m/Y');
		$datas['email_time'] 		= date_create($row[CustomerScheduleTable::C_EMAIL_TIME])->format('H:i');
		$datas['delivery_date'] 	= Util::createOptionValue($vlsDelivery, $row[CustomerScheduleTable::C_DELIVERY_DATE]);
		$datas['delivery_time'] 	= Util::createOptionValue($vlsDeliveryTime, $row[CustomerScheduleTable::C_DELIVERY_TIME]);

		$this->sendJsonResponse(Status::Ok,"",$datas,$this->type);
	}

	private function updateSchedule($params){
		$cls = new CustomerScheduleClass($this->db);

		$datas	 = [];
		$datas[] = $this->db->fieldValue(CustomerScheduleTable::C_CHOSEN_GIFT_ITEM, $this->getParam($params, 'gift_type', 0));
        $datas[] = $this->db->fieldValue(CustomerScheduleTable::C_GIFT_AMOUNT, $this->getParam($params, 'total_gift', 0));
        $datas[] = $this->db->fieldValue(CustomerScheduleTable::C_REMARKS, $this->getParam($params, 'remarks', ''));
        $datas[] = $this->db->fieldValue(CustomerScheduleTable::C_DELIVERY_DATE, $this->getParam($params, 'delivery_date', '1969-12-31'));
        $datas[] = $this->db->fieldValue(CustomerScheduleTable::C_DELIVERY_TIME, $this->getParam($params, 'delivery_time', '00:00:00'));
		try{
			$cls->updateRecord($params['id'], $datas);
			$this->sendJsonResponse(Status::Ok,"",$datas,$this->type);
			return;
		} catch(Exception $e){
            Log::write("[CorporateGiftInquiry]" . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Application Error","",$this->type) ;
			return;
        }
	}

	private function getDeliveryTime($params){
		$cls = new CorporateGiftDeliveryClass($this->db);
		$rowsDeliveryTime = $cls->getDeliveryTimeByGiftID($params['gift_id'], $params['delivery_date']);
		$vlsDeliveryTime[]= array('code'=>'', 'desc'=>'-- Select Delivery Time --');
		foreach($rowsDeliveryTime as $rowDeliveryTime){
			$vlsDeliveryTime[] = array('code'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME1], 'desc'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME1]);
			$vlsDeliveryTime[] = array('code'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME2], 'desc'=>$rowDeliveryTime[CorporateGiftDeliveryTable::C_TIME2]);
		}

        $option =  Util::createOptionValue($vlsDeliveryTime);
        $this->sendJsonResponse(Status::Ok,"Corporate Gift Entry Info",$option,$this->type);
    }
}
?>