<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "destination/DestinationClass.php") ;
require_once (PATH_LIB . "LicenseFile.php") ;

class Destination extends GLBase {
	private $type = "" ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
		$this->orgid = $_SESSION[SE_ORGID] ;
		$this->fldorg = $_SESSION[SE_ORGID] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		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::DestinationView:
					$this->getView($params) ;
						break ;
				case REQ_ADD:
					$this->saveRecord($params) ;
					break ;
				case REQ_DELETE:
					$this->deleteRecord($params) ;
					break ;
				case REQ_LIST:
					$this->getDestinationList($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 saveRecord($params) {
		$cls 		 = new DestinationClass($this->db) ;
		$datas 		 = array() ;
		$modifyby 	 = $_SESSION[SE_USERID] ;
		$modifydate  = date_create('now')->format('Y-m-d H:i:s') ;

		// $row_destinations   = $cls->getTable();
		$new_destinations	 = json_decode($params['new_destination'], true);
		$exist_destinations  = json_decode($params['existing_destination'], true);

		// $array_existing_id = array();
		// $array_current_id  = array();
		try {
			$this->db->beginTran();
			if(!is_null($new_destinations) && count($new_destinations) > 0){
				foreach($new_destinations as $new_destination){
					$name 	= $new_destination['name'];
					$link 	= $new_destination['link'];

					if ($cls->isNameFound($name)) {
						$this->sendJsonResponse(Status::Error,"Destination name already exist. Please choose other name.",$name,$this->type) ;
						return ;
					}
					
					$datas = array();
					$datas[] = $this->db->fieldValue(DestinationTable::C_NAME,$name) ;
					$datas[] = $this->db->fieldValue(DestinationTable::C_LINK,$link) ;
					$datas[] = $this->db->fieldValue(DestinationTable::C_MODIFY_BY,$modifyby) ;
					$datas[] = $this->db->fieldValue(DestinationTable::C_MODIFY_DATE,$modifydate) ;
					$datas[] = $this->db->fieldValue(DestinationTable::C_CREATE_BY,$modifyby) ;
					$datas[] = $this->db->fieldValue(DestinationTable::C_CREATE_DATE,$modifydate) ;

					$id = $cls->addRecord($datas);
					// array_push($array_current_id, $id);
				}
			}
			
			if(!is_null($exist_destinations) && count($exist_destinations) > 0){
				foreach($exist_destinations as $exist_destination){
					
					$id	  	 = $exist_destination['destination_id'];
					$link 	 = $exist_destination['link'];
					
					$datas 	 = array();
					$datas[] = $this->db->fieldValue(DestinationTable::C_LINK,$link) ;
					$datas[] = $this->db->fieldValue(DestinationTable::C_MODIFY_BY,$modifyby) ;
					$datas[] = $this->db->fieldValue(DestinationTable::C_MODIFY_DATE,$modifydate) ;
					
					$cls->updateRecord($id, $datas);
					// array_push($array_current_id, $id);
				}
			}

			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Destination successfully added to the system.",$id,$this->type);
		} catch (Exception $e) {
			Log::write('[Destination]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}
	
	private function deleteRecord($params) {
		$cls = new DestinationClass($this->db);

		$ids =  $this->getParam($params, 'id', "");
		if( $ids == "" ){
			$this->sendJsonResponse(Status::Error,"Invalid ID.","",$this->type);
			return;
		}

		try {
			$this->db->beginTran();

			$decodes = json_decode($ids,true);
			$separate = "";
			$str = "";
			if(!is_null($decodes) && count($decodes)>0){
				foreach ($decodes as $decode) {
					$str .= $separate.$decode;
					$separate = ",";

					$cls->deleteDestinationRecord($str);
				}
			}
			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Successfully delete destination from system.","",$this->type);
			return;
		} catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[Destination] ' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting destination from the system.","",$this->type);
			return;
		}
		unset ($cls);
	}

	private function getDestinationList($params) {
		$cls = new DestinationClass($this->db);

		$sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                case "col_name":
                    $orderby = DestinationTable::C_NAME . " " . $sort[1];
                    break;
                case "col_link":
                    $orderby = DestinationTable::C_LINK . " " . $sort[1];
                    break;
                default:
                    $orderby = DestinationTable::C_NAME . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = DestinationTable::C_NAME . " asc";
        }

		$rows = $cls->getTable("",$orderby);

		$lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $list = [
                    "id" => $row[DestinationTable::C_ID],
                    "name" => htmlentities($row[DestinationTable::C_NAME]),
                    "link" => htmlentities($row[DestinationTable::C_LINK]),
                ];

                array_push($lists, $list);
            }
        }
        $lists = json_encode($lists);

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

		// $idx = 1;
		// $html = "";
		// if( !is_null($rows) && count($rows)>0 ){
		// 	foreach ($rows as $row) {
		// 		$html.= '<tr id="tr_destination'.$idx.'" class="existing_destination">
		// 					<td><input type="checkbox" id="destination_check'.$idx.'" class="destination_check" value="'.$idx.'" name="destination_chk[]" disabled></td>
        //                     <td><input type="text" id="destination_code'.$idx.'" class="form-control destination_name" value="'.$row[DestinationTable::C_NAME].'"  disabled></td>
		// 					<td><input type="text" id="destination_desc'.$idx.'" class="form-control destination_link" value="'.$row[DestinationTable::C_LINK].'"  disabled></td>
		// 					<td style="display:none" class="destination_id" id="destination_id'.$idx.'">'.$row[DestinationTable::C_ID].'</td>
        // 					<td style="display:none" class="destination_idx" id="destination_idx'.$idx.'">'.$idx.'</td>
		// 				</tr>';
		// 		$idx++;
		// 	}
		// }
		// $datas= array(
		// 	"html" =>$html,
		// 	"idx" => $idx+1
		// );
		// $this->sendJsonResponse(Status::Ok,"",$datas,$this->type);
	}

	private function getView($params) {
		ob_start() ;
		include (PATH_VIEWS . "destination/DestinationView.php") ;

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