<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "admin/DepartmentGroupClass.php") ;
require_once (PATH_LIB . "LicenseFile.php") ;

class DepartmentGroup 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::DepartmentView:
					$this->getView($params) ;
					break ;
				case REQ_ADD:
					$this->saveRecord($params) ;
					break ;
				case REQ_DELETE:
					$this->deleteRecord($params) ;
					break ;
				case REQ_LIST:
					$this->getDepartmentList($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 DepartmentGroupClass($this->db) ;
		$datas 		 = array() ;
		$desc 		 = $this->getParam($params,'desc',"") ;

		// $row_industries   = $cls->getTable();
		$new_industries	 = json_decode($params['new_department'], true);
		$exist_industries = json_decode($params['existing_department'], true);

		// $array_existing_id = array();
		// $array_current_id  = array();
		try {
			$this->db->beginTran();
			if(!is_null($new_industries) && count($new_industries) > 0){
				foreach($new_industries as $new_department){
					$desc 		= $new_department['desc'];

					if ($cls->isNameFound($desc)) {
						$this->sendJsonResponse(Status::Error,"Department description already exist.",$desc,$this->type) ;
						return ;
					}
					
					$datas = array();
					$datas[] = $this->db->fieldValue(DepartmentGroupTable::C_DESC,$desc) ;

					$id = $cls->addRecord($datas);
					// array_push($array_current_id, $id);
				}
			}
			
			if(!is_null($exist_industries) && count($exist_industries) > 0){
				foreach($exist_industries as $exist_department){
					
					$id	  	= $exist_department['department_id'];
					$desc 	= $exist_department['desc'];
					
					$datas = array();
					$datas[] = $this->db->fieldValue(DepartmentGroupTable::C_DESC,$desc) ;
					
					$cls->updateRecord($id, $datas);
					// array_push($array_current_id, $id);
				}
			}

			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Department successfully added to the system.",$id,$this->type);
		} catch (Exception $e) {
			Log::write('[Department Group]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}
	
	private function deleteRecord($params) {
		$cls = new DepartmentGroupClass($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->deleteSettingRecord($str);
				}
			}
			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Successfully delete department from system.","",$this->type);
			return;
		} catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[Department Group] ' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting department from the system.","",$this->type);
			return;
		}
		unset ($cls);
	}

	private function getDepartmentList($params) {
		$cls = new DepartmentGroupClass($this->db);

		$sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                default:
                    $orderby = DepartmentGroupTable::C_DESC . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = DepartmentGroupTable::C_DESC . " asc";
        }

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

		$idx = 1;
		$html = "";
		if( !is_null($rows) && count($rows)>0 ){
			foreach ($rows as $row) {
				$html.= '<tr id="tr_department'.$idx.'" class="existing_department">
							<td><input type="checkbox" id="department_check'.$idx.'" class="department_check" value="'.$idx.'" name="department_chk[]" disabled></td>
							<td><input type="text" id="department_desc'.$idx.'" class="form-control department_desc" value="'.$row[DepartmentGroupTable::C_DESC].'"  disabled></td>
							<td style="display:none" class="department_id" id="department_id'.$idx.'">'.$row[DepartmentGroupTable::C_ID].'</td>
        					<td style="display:none" class="department_idx" id="department_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 . "admin/DepartmentGroupView.php") ;

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