<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_CONTROLLERS . "base/GLBase.php") ;
require_once (PATH_MODELS . "customer/CustomerScheduleClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CompanyProfileClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftHeaderImageClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftDetailClass.php") ;
require_once (PATH_MODELS . "corporate_gift/CorporateGiftDeliveryClass.php");
require_once (PATH_MODELS . "corporate_gift/CorporateGiftHistoryClass.php");
require_once (PATH_CODE . 'ConfigDb.php') ;

class SubmitSchedule extends GLBase {
	private $type 		 	 = "" ;
	private $custschedid 	 = "" ;
	private $position 	 	 = "" ;
	private $name 		 	 = "" ;
	private $phone 		 	 = "" ;
	private $remarks 	 	 = "" ;
	private $delivery 	 	 = "" ;
	private $diarytype 	 	 = "" ;
	private $giftname 	 	 = "" ;
	private $coy_id 	 	 = "" ;
	private $giftid 	 	 = "" ;
	private $delivery_cutoff = "" ;
	private $htmlItem 	 	 = "" ;
	private $htmlDelivery	 = "" ;
	private $records 	 	 = array() ;
	function __construct() {
		$config = new ConfigDb(PATH_CODE . 'db.xml') ;
		$config->loadConfig() ;

		$_SESSION[SE_DB] = new MsSqlDb($config->getHost(),$config->getDbName(),$config->getUserName(),$config->getPassword()) ;
	
		unset($config) ;
		
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->db) ;
		unset($this->records) ;
	}
	public function processRequest($params) {
		try {
			$this->db->open() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			if (!$this->checkSessionTimeout($this->type)) {
				$this->db->close();
				return false;
			}
			switch ($this->type) {
				case REQ_LIST:
					// $data = $this->populateCalendar();
					$this->sendJsonResponse(Status::Ok,"Success.",'',$this->type) ;
					break;
				case REQ_ADD:
					$this->addRecord($params) ;
					break ;
				case REQ_QUERY:
					$this->checkNumber($params);
					break;
				case REQ_VIEW:
					$this->getView($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 populateCalendar() {
		$currentyear = date('Y');
		$currentmonth = date('n');
		$currentdate = date('j');
		// $nextdate = new DateTime(date('Y-m-d', strtotime(date('Y-m-d'). ' +7 days')));
		// $enddate = new DateTime(date('Y-m-d', strtotime(date('Y-m-d'). ' +14 days')));
		$nextdate = new DateTime('2025-12-08');
		$enddate = new DateTime('2025-12-31');
		$oneday = new DateInterval("P1D");
		$noofdays = Util::getLastDay($currentyear, $currentmonth);
		
		$columns = array();
		
		foreach(new DatePeriod($nextdate, $oneday, $enddate->add($oneday)) as $day) {
			$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
			if($day_num < 6 && count($columns) < 14) { /* weekday */
				if($day->format('d-m-Y') != '26-09-2025') {
					$columns[] = $day;
				}
			}
		}


		$list = "<table class='table table-bordered table-responsive' style='width:100%;' cellspacing='0' id='interview_schedule_table'>";
		$list .= "<tbody id='schedule_table_body' style='width:100%!important;'>";

		for ($j = 0; $j < count($columns); $j++) {
			$day = Util::getDay($columns[$j]->format('Y'), $columns[$j]->format('m'), $columns[$j]->format('d'));
			$list .= "<tr style='width:100%!important;'><th style='width:100%;text-align: left;background-color:#44759d;color:white;white-space: nowrap;'>".$columns[$j]->format('d M')." (".$day.")</th>";

			if ($columns[$j]->format('d') < $currentdate) {
				$nextmonth = new DateTime(date('Y-m-d', strtotime('first day of +1 month')));
				$date = $nextmonth->format('Y') . "-" . $nextmonth->format('m') . "-" . $columns[$j]->format('d');
			} else {
				$date = $currentyear . "-" . $currentmonth . "-" . $columns[$j]->format('d');
			}

			$list .= "<td style='width:100%;text-align: left;vertical-align: top;white-space: nowrap;' id='td_schedule_time_" . $columns[$j]->format('Y-m-d') . "_11:00 - 12:30' onclick='selectTimeShedule(this, \"" . $date . "_11:00 - 12:30\");'>11:00 - 12:30<div>&nbsp;</div></td>";

			$list .= "<td style='width:100%;text-align: left;vertical-align: top;white-space: nowrap;' id='td_schedule_time_" . $columns[$j]->format('Y-m-d') . "_14:00 - 17:00' onclick='selectTimeShedule(this, \"" . $date . "_14:00 - 17:00\");'>14:00 - 17:00<div>&nbsp;</div></td>";

			$list .= "</tr>";
		}

		$list .= "</tbody></table>";

		return $list;
	}

	private function addRecord($params) {
		$cls 			= new CustomerScheduleClass($this->db) ;
		$clsDetail 		= new CorporateGiftDetailClass($this->db) ;
		$clsHistory 	= new CorporateGiftHistoryClass($this->db) ;
		$clsDelivery	= new CorporateGiftDeliveryClass($this->db) ;
		$datas 			= array() ;
		$modifyby 		= 0 ;
		$modifydate 	= date_create('now')->format('Y-m-d H:i:s') ;

		$id 		  = $this->getParam($params, 'id', "");
		$remarks 	  = $this->getParam($params, 'remarks', "");
		$name 		  = $this->getParam($params, 'name', "");
		$giftname 	  = $this->getParam($params, 'giftname', "");
		$gifttype 	  = $this->getParam($params, 'gifttype', "");
		$delivery_id  = $this->getParam($params, 'deliveryid', "");
		$deliverytime = $this->getParam($params, 'deliverytime', "");
		$coy_id 	  = $this->getParam($params, 'coy_id', "");
		$gift_id 	  = $this->getParam($params, 'gift_id', "");

		// $row			= $clsDetail->getScheduleByID($id);
		$row			= $cls->getScheduleByID($id);
		$rowDelivery 	= $clsDelivery->getRecord($delivery_id);
		$delivery_date 	= $rowDelivery[CorporateGiftDeliveryTable::C_DATE];
		if($deliverytime == 1){
			$delivery_time = $rowDelivery[CorporateGiftDeliveryTable::C_TIME1];
		}else{
			$delivery_time = $rowDelivery[CorporateGiftDeliveryTable::C_TIME2];
		}

		try {
			$this->db->beginTran() ;
			$datas   = [];
			$datas[] = $this->db->fieldValue(CustomerScheduleTable::C_REMARKS,$remarks);
			$datas[] = $this->db->fieldValue(CustomerScheduleTable::C_DELIVERY_DATE,$delivery_date);
			$datas[] = $this->db->fieldValue(CustomerScheduleTable::C_DELIVERY_TIME,$delivery_time);
			$datas[] = $this->db->fieldValue(CustomerScheduleTable::C_CHOSEN_GIFT_ITEM,$gifttype);
			$datas[] = $this->db->fieldValue(CustomerScheduleTable::C_MODIFY_BY,$modifyby) ;
			$datas[] = $this->db->fieldValue(CustomerScheduleTable::C_MODIFY_DATE,$modifydate) ;
			$cls->updateRecord($id, $datas) ;

			$datas_history 	  = [];
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_ID,$gift_id);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_CUSTOMER_ID,$row[CustomerContactTable::C_ID]);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_CONTACT_ID,$row[CustomerScheduleTable::C_NAME_ID]);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_REMARKS,$remarks);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_DELIVERY_DATE,$rowDelivery[CorporateGiftDeliveryTable::C_DATE]);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_DELIVERY_TIME,$delivery_time);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_RESPONSE_TIME,$modifydate);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_GIFT_MASTER_ID,$gift_id);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_CHOSEN_ITEM_ID,$gifttype);
			$datas_history [] = $this->db->fieldValue(CorporateGiftHistoryTable::C_GIFT_AMOUNT,$row[CustomerScheduleTable::C_GIFT_AMOUNT]);
			$clsHistory->addRecord($datas_history);

			if ($id > 0) {
				$this->db->commitTran() ;
				// $this->sendSubmissionEmail($id, $remarks, $delivery_date, $delivery_time, $coy_id, $gift_id);
				$this->sendJsonResponse(Status::Ok,"Dear ". $name .", your selected " . $giftname . " delivery date and time is successfully submitted on " . date_create($delivery_date)->format('d/m/Y') ." at around ". $delivery_time .". Thank you for your attention.",$id,$this->type);
				Log::write(print_r("Dear ". $name .", Your selected " . $giftname . " delivery date and time is successfully submitted on " . date_create($delivery_date)->format('d/m/Y') ." at around ". $delivery_time .". Thank you for your attention.",true));
			} else {
				$this->db->rollbackTran() ;
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding " . $giftname . " delivery date and time to the system.",$id, $this->type) ;
			}
		}  catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[NewCandidate]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}

	private function sendSubmissionEmail($id, $remarks, $deliverydate, $deliverytime, $from_coy, $gift_id) {
		if (isset($id)) {
			$clsSched 	= new CustomerScheduleClass($this->db);
			$clsComp 	= new CompanyProfileClass($this->db);
			$clsImg  	= new CorporateGiftHeaderImageClass($this->db) ;
			$row 		= $clsSched->getCustomerScheduleGiftByID($id);
			$row_comp	= $clsComp->getRecord($from_coy);

			//=================
			//$row_emp = $clsEmp->getRecord($row[CustomerScheduleTable::C_NAME_ID]);
			$full_name 	= $row[CustomerScheduleTable::C_NAME];
			$to_email 	= $row[CustomerScheduleTable::C_EMAIL];

			$gift_item	= $row[CorporateGiftTable::C_NAME];
			$gift_type	= $row[CorporateGiftDetailTable::C_ITEM_NAME];
			//=================
			$coy_name	= $row_comp[CompanyProfileTable::C_NAME];
			$coy_url	= $row_comp[CompanyProfileTable::C_URL];
			$fromEmails	= $row_comp[CompanyProfileTable::C_MAIL_SENDER];

			$header_path = $this->getBaseURL() . "/" . $clsImg->getCorporateGiftHeaderImageByGiftIDAndCompID($gift_id, $from_coy);
			$item_path 	 = $this->getBaseURL() . "/" . $row[CorporateGiftDetailTable::C_ITEM_IMAGE];
			$sign_path	 = $this->getBaseURL() . "/" . $row_comp[CompanyProfileTable::C_SIGNATURE_PATH];
			
			$ccEmail 	= null;
			if(trim($row[CustomerScheduleTable::C_CC_EMAIL]) != "" && $row[CustomerScheduleTable::C_CC_EMAIL] != null){
				$ccEmail	= explode(";", $row[CustomerScheduleTable::C_CC_EMAIL]);
			}
			//=========================================
			//EMAIL MESSAGE
			$now = new DateTime();
			$year = $now->format("Y");
			$delivery_date = date_create($deliverydate)->format('d/m/Y');
			
			$header_img = '<img align="center" alt="Email Header" border="0" class="center fixedwidth " src="'. $header_path .'" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; width: 100%; border: 0; display: block;" title="Email Header"/>';
			$item_img   = '<img align="center" alt="Item Image" border="0" class="center fixedwidth " src="'. $item_path .'" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: 300px; max-height: 300px; width: 200px; max-width: 200px; border: 0; display: block;" title="Item Image"/>';
			$sign_img 	= '<img align="center" alt="Email Signature" border="0" class="center fixedwidth " src="'. $sign_path .'" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; height: auto; width: 100%; border: 0; display: block;" title="Email Signature"/>';

			$email_body = file_get_contents(str_replace("\schedule", "", PATH_LIB) . "emailDiarySubmission.txt");
			$email_body = str_replace("{TO_NAME}", $full_name, $email_body);
			$email_body = str_replace("{ITEM_NAME}", $gift_item, $email_body);
			$email_body = str_replace("{DELIVERY_DATE}", $delivery_date, $email_body);
			$email_body = str_replace("{DELIVERY_TIME}", $deliverytime, $email_body);
			$email_body = str_replace("{REMARKS}", '<tr>
							<td valign="top" style="color:#000000;font-family:Helvetica;font-size:16px;font-weight:normal;text-align:right;" width="30%" class="textContent">
								<b>Comment :</b>
                            </td>
							<td valign="top" class="textContent">
								'.$remarks.'
							</td>
						</tr>', $email_body);
			$email_body = str_replace("{ITEM_TYPE}", $gift_type, $email_body);
			$email_body = str_replace("{EMAIL_SUPPORT}", 'darren@sbgsea.com', $email_body);
			$email_body = str_replace("{IMAGE}", $header_img, $email_body);
			$email_body = str_replace("{ITEM_IMAGE}", $item_img, $email_body);
			$email_body = str_replace("{COPY_RIGHT}", $coy_name, $email_body);
			$email_body = str_replace("{COY_URL}", $coy_url, $email_body);
			$email_body = str_replace("{YEAR}", $year, $email_body);
			$email_body = str_replace("{COMPANY_NAME}", $sign_img, $email_body);

			if(trim($to_email) == ""){
				return true;
			}

			EmailLog::write("Sending acknowledgement email to " . $full_name . " (" . $to_email . ") cc " . $ccEmail);
			
			return $this->sendEmail($gift_item . " Delivery Schedule Acknowledgement",
									$email_body,
									$fromEmails,
									$ccEmail,
									explode(";",$to_email),
									null,
									$from_coy);
		} else {
			return false;
		}
	}
	private function checkNumber($params){
		try {
			if (isset($params['phone'])) {
				$datas = array();
				$clsCandidate = new CustomerScheduleClass($this->db) ;
				$phone = $this->getParam($params,'phone',"") ;

				$phone_n = $phone;
				if(substr($phone_n,0,1) == '6'){
					$phone_n = substr($phone_n, 1);
				}
				$filter = "" ;
				$filter .= CustomerScheduleTable::C_PHONE . " = '" . $phone_n ." '";

				$params = array() ;
				$orderby = CustomerScheduleTable::C_ID ;

				$rows = $clsCandidate->getTable($filter,$orderby,$params) ;
				
				if(!is_null($rows) && count($rows) > 0) {
					$this->sendJsonResponse(Status::Invalid,"This phone number already exist.",$rows,$this->type);
				}else{		
					$this->sendJsonResponse(Status::Ok,"","",$this->type);
				}
				unset($rows) ;
				unset($clsCandidate) ;						
			}
		} catch (Exception $e) {
			log::write($e->getMessage());
			$this->sendJsonResponse(Status::Error,"Something went wrong.","",$this->type) ;
		}
	}

	private function getView($params) {
		ob_start() ;
		if(isset($params['ref'])) {
			$this->custschedid 		= "";
			$this->position 		= "";
			$this->name 			= "";
			$this->phone 			= "";
			$this->remarks 			= "";
			$this->delivery 		= "";
			$this->diarytype 		= "";
			$this->delivery_cutoff 	= "";

			$this->giftid 			= "";
			$this->giftname 		= "";
			$this->htmlItem			= "";
			$this->htmlDelivery 	= "";
			$this->coy_id 			= "";
			
			$cls 			= new CustomerScheduleClass($this->db);
			$clsCus			= new CustomerClass($this->db);
			$clsGift		= new CorporateGiftClass($this->db);
			$clsDetail		= new CorporateGiftDetailClass($this->db);
			$clsDelivery	= new CorporateGiftDeliveryClass($this->db);
			$clsCompany		= new CompanyProfileClass($this->db);

			$rows 			= $cls->getRecordByRefId($params['ref'], $params['gift']);
			
			if(!is_null($rows) && count($rows) > 0){
				$rowsGift 		= $clsGift->getRecord($params['gift']);
				$rowsDetail  	= $clsDetail->getCorporateGiftDetailByGiftID($params['gift']);
				$rowsDelivery 	= $clsDelivery->getCorporateGiftDeliveryByGiftID($params['gift']);
				$row_com 		= $clsCus->getRecord($rows[CustomerContactTable::C_ID]);
				$coy_name 		= $row_com[CustomerTable::C_NAME];
				$dte 			= date_create($rows[CustomerScheduleTable::C_DELIVERY_DATE]) ;
				$year 			= date_format($dte, 'Y') ;
				$month 			= str_replace("0", "", date_format($dte, 'm')) ;
				$day 			= date_format($dte, 'd') ;
				
				$deliverydate = $year . "-" . $month . "-" . $day ;
				$deliverydate = date_format($dte, 'Y-m-d') ;

				$this->giftid 		= $rows[CustomerScheduleTable::C_GIFT_MASTER_ID];
				$this->coy_id 		= $rows['SCH_COY_ID'];
				$this->custschedid 	= $rows[CustomerScheduleTable::C_ID];
				$this->position 	= $coy_name;
				$this->name 		= $rows[CustomerScheduleTable::C_NAME];
				$this->phone 		= $rows[CustomerScheduleTable::C_PHONE];
				$this->remarks 		= $rows[CustomerScheduleTable::C_REMARKS];
				$this->diarytype 	= $rows[CustomerScheduleTable::C_CHOSEN_GIFT_ITEM] ?? '';
				$this->delivery 	= "td_schedule_time_" . $deliverydate . "_" . $rows[CustomerScheduleTable::C_DELIVERY_TIME];
				$rowCompany			= $clsCompany->getRecord($rows['SCH_COY_ID']);
			}
			if(!is_null($rowsGift) && count($rowsGift) > 0){
				$this->giftname 		= $rowsGift[CorporateGiftTable::C_NAME];
				$this->delivery_cutoff 	= $rowsGift[CorporateGiftTable::C_CUTOFF_DATE];
			}
			if(!is_null($rowsDetail) && count($rowsDetail) > 0){
				$countItem = count($rowsDetail);
				$currentCount = 0;
				foreach($rowsDetail as $key => $rowDetail){
					$currentCount++;;
					if($currentCount == 2){
						$this->htmlItem .= "<td class='product-td'>
										<div class='product-wrap'>
											<img src='".$rowDetail[CorporateGiftDetailTable::C_ITEM_IMAGE]."' alt='".$rowDetail[CorporateGiftDetailTable::C_ITEM_NAME]."'>
											<lable>".$rowDetail[CorporateGiftDetailTable::C_ITEM_NAME]."</label>
											<div class='donate-now'>
												<input type='radio' id='type".$rowDetail[CorporateGiftDetailTable::C_DETAIL_ID]."' value='".$rowDetail[CorporateGiftDetailTable::C_DETAIL_ID]."' name='gift-type'>
												<label for='type".$rowDetail[CorporateGiftDetailTable::C_DETAIL_ID]."'>Choose This <span id='tick' style='color:#fff;margin-left:5px;'>&#10003;</span></label>
											</div>
										</div>
									</td>
								</tr>";
						$currentCount = 0;
					}else{
						$colspan = "";
						if($key == ($countItem - 1) ){
							$colspan = "colspan='2'";
						}
						$this->htmlItem .= "<tr>
									<td class='product-td' ".$colspan.">
										<div class='product-wrap'>
											<img src='".$rowDetail[CorporateGiftDetailTable::C_ITEM_IMAGE]."' alt='".$rowDetail[CorporateGiftDetailTable::C_ITEM_NAME]."'>
											<label>".$rowDetail[CorporateGiftDetailTable::C_ITEM_NAME]."</label>
											<div class='donate-now'>
												<input type='radio' id='type".$rowDetail[CorporateGiftDetailTable::C_DETAIL_ID]."' value='".$rowDetail[CorporateGiftDetailTable::C_DETAIL_ID]."' name='gift-type'>
												<label for='type".$rowDetail[CorporateGiftDetailTable::C_DETAIL_ID]."'>Choose This <span id='tick' style='color:#fff;margin-left:5px;'>&#10003;</span></label>
											</div>
										</div>
									</td>";
					}
				}
			}
			if(!is_null($rowsDelivery) && count($rowsDelivery) > 0){

				$this->htmlDelivery .= "<table class='table table-bordered table-responsive' style='width:100%;' cellspacing='0' id='interview_schedule_table'>" .
											"<tbody id='schedule_table_body' style='width:100%!important;'>";

				foreach($rowsDelivery as $rowDelivery){
					$date = date_create($rowDelivery[CorporateGiftDeliveryTable::C_DATE])->format('d/m/Y');
					$this->htmlDelivery .= "<tr style='width:100%!important;'>" .
												"<th style='width:100%;text-align: left;background-color:#44759d;color:white;white-space: nowrap;'>".$date. "</th>".
												"<td style='width:100%;text-align: left;vertical-align: top;white-space: nowrap;' id='td_schedule_time1_" . $rowDelivery[CorporateGiftDeliveryTable::C_DELIVERY_ID] . "' onclick='selectTimeShedule(this, \"" . $rowDelivery[CorporateGiftDeliveryTable::C_TIME1]."\");'>".$rowDelivery[CorporateGiftDeliveryTable::C_TIME1]."<div>&nbsp;</div></td>".
												"<td style='width:100%;text-align: left;vertical-align: top;white-space: nowrap;' id='td_schedule_time2_" . $rowDelivery[CorporateGiftDeliveryTable::C_DELIVERY_ID] . "' onclick='selectTimeShedule(this, \"" . $rowDelivery[CorporateGiftDeliveryTable::C_TIME2]."\");'>".$rowDelivery[CorporateGiftDeliveryTable::C_TIME2]."<div>&nbsp;</div></td>";
				}

				$this->htmlDelivery .= "</tbody></table>";
			}
		}
		$logo = '<img align="center" alt="Logo" border="0" class="center fixedwidth " src="'. $this->getBaseURL() . "/" . $rowCompany[CompanyProfileTable::C_LOGO_PATH] . '" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 175px; display: block;" title="Logo" width="175"/>';

		include (PATH_VIEWS . "corporate_gift/submitscheduleview.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}

}
