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

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

		// $row_industries   = $cls->getTable();
		$new_industries	 = json_decode($params['new_industry'], true);
		$exist_industries = json_decode($params['existing_industry'], 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_industry){
					$desc 		= $new_industry['desc'];

					if ($cls->isNameFound($desc)) {
						$this->sendJsonResponse(Status::Error,"Industry description already exist.",$desc,$this->type) ;
						return ;
					}
					
					$datas = array();
					$datas[] = $this->db->fieldValue(IndustryTable::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_industry){
					
					$id	  	= $exist_industry['industry_id'];
					$desc 	= $exist_industry['desc'];
					
					$datas = array();
					$datas[] = $this->db->fieldValue(IndustryTable::C_DESC,$desc) ;
					
					$cls->updateRecord($id, $datas);
					// array_push($array_current_id, $id);
				}
			}

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

	private function getIndustryList($params) {
		$cls = new IndustryClass($this->db);

		$sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                default:
                    $orderby = IndustryTable::C_DESC . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = IndustryTable::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_industry'.$idx.'" class="existing_industry">
							<td><input type="checkbox" id="industry_check'.$idx.'" class="industry_check" value="'.$idx.'" name="industry_chk[]" disabled></td>
							<td><input type="text" id="industry_desc'.$idx.'" class="form-control industry_desc" value="'.$row[IndustryTable::C_DESC].'"  disabled></td>
							<td style="display:none" class="industry_id" id="industry_id'.$idx.'">'.$row[IndustryTable::C_ID].'</td>
        					<td style="display:none" class="industry_idx" id="industry_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/IndustryView.php") ;

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