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

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

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

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

			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Business Sector 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 BusinessSectorClass($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 business sector from system.","",$this->type);
			return;
		} catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[Business Sector] ' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting business sector from the system.","",$this->type);
			return;
		}
		unset ($cls);
	}

	private function getBusinessSectorList($params) {
		$cls = new BusinessSectorClass($this->db);

		$sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                default:
                    $orderby = BusinessSectorTable::C_DESC . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = BusinessSectorTable::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_business_sector'.$idx.'" class="existing_business_sector">
							<td><input type="checkbox" id="business_sector_check'.$idx.'" class="business_sector_check" value="'.$idx.'" name="business_sector_chk[]" disabled></td>
							<td><input type="text" id="business_sector_desc'.$idx.'" class="form-control business_sector_desc" value="'.$row[BusinessSectorTable::C_DESC].'"  disabled></td>
							<td style="display:none" class="business_sector_id" id="business_sector_id'.$idx.'">'.$row[BusinessSectorTable::C_ID].'</td>
        					<td style="display:none" class="business_sector_idx" id="business_sector_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/BusinessSectorView.php") ;

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