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

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

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

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

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

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

	private function getSoftwareList($params) {
		$cls = new SoftwareClass($this->db);

		$sorts  = $params['sorts'];

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

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

		$idx = 1;
		$html = "";
		if( !is_null($rows) && count($rows)>0 ){
			foreach ($rows as $row) {
				$type1 = "";
				$type2 = "";
				$type3 = "";
				if($row[SoftwareTable::C_TYPE] == 1){
					$type1 = 'selected';
				}else if($row[SoftwareTable::C_TYPE] == 2){
					$type2 = 'selected';
				}else if($row[SoftwareTable::C_TYPE] == 3){
					$type3 = 'selected';
				}

				$html.= '<tr id="tr_software'.$idx.'" class="existing_software">
							<td><input type="checkbox" id="software_check'.$idx.'" class="software_check" value="'.$idx.'" name="software_chk[]" disabled></td>
							<td><input type="text" id="software_desc'.$idx.'" class="form-control software_desc" value="'.$row[SoftwareTable::C_DESC].'"  disabled></td>
							<td style="padding: 0px !important;">
								<select id="software_type'.$idx.'" class="form-control software_type" disabled>
									<option value="1" '.$type1.'>Accounting</option>
									<option value="2" '.$type2.'>Sales</option>
									<option value="3" '.$type3.'>Others</option>
								</select>
							</td>
							<td style="display:none" class="software_id" id="software_id'.$idx.'">'.$row[SoftwareTable::C_ID].'</td>
        					<td style="display:none" class="software_idx" id="software_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/SoftwareView.php") ;

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