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


class User 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::UserView:
					$this->getView($params) ;
						break ;
				case REQ_ADD:
					$this->saveRecord($params) ;
					break ;
				case REQ_DELETE:
					$this->deleteRecord($params) ;
					break ;
				case REQ_CHANGE:
					$this->resetPassword($params) ;
					break ;
				case REQ_LIST:
					$this->getUserList($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 UserClass($this->db) ;
		$datas 		 = array() ;
		$modifyby 	 = $_SESSION[SE_USERID] ;
		$modifydate  = date_create('now')->format('Y-m-d H:i:s') ;
		$name 		 = $this->getParam($params,'name',"") ;

		// $row_users   = $cls->getTable();
		$new_users	 = json_decode($params['new_user'], true);
		$exist_users = json_decode($params['existing_user'], true);

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

					if ($cls->isNameFound($name)) {
						$this->sendJsonResponse(Status::Error,"User name already exist. Please choose other name.",$name,$this->type) ;
						return ;
					}
					
					$datas = array();
					$datas[] = $this->db->fieldValue(UserTable::C_NAME,$name) ;
					$datas[] = $this->db->fieldValue(UserTable::C_FULL_NAME,$full_name) ;
					$datas[] = $this->db->fieldValue(UserTable::C_USER_GROUP,$user_group) ;
					$datas[] = $this->db->fieldValue(UserTable::C_CHANGE_PWD, 1) ;
					$datas[] = $this->db->fieldValue(UserTable::C_MODIFY_BY,$modifyby) ;
					$datas[] = $this->db->fieldValue(UserTable::C_MODIFY_DATE,$modifydate) ;
					$datas[] = $this->db->fieldValue(UserTable::C_CREATE_BY,$modifyby) ;
					$datas[] = $this->db->fieldValue(UserTable::C_CREATE_DATE,$modifydate) ;

					$id = $cls->addRecord($datas);
					// array_push($array_current_id, $id);
				}
			}
			
			if(!is_null($exist_users) && count($exist_users) > 0){
				foreach($exist_users as $exist_user){
					$id	  		= $exist_user['user_id'];
					$full_name 	= $exist_user['full_name'];
					$user_group = $exist_user['user_group'];
					
					$datas = array();
					$datas[] = $this->db->fieldValue(UserTable::C_FULL_NAME,$full_name) ;
					$datas[] = $this->db->fieldValue(UserTable::C_USER_GROUP, $user_group);
					$datas[] = $this->db->fieldValue(UserTable::C_MODIFY_BY,$modifyby) ;
					$datas[] = $this->db->fieldValue(UserTable::C_MODIFY_DATE,$modifydate) ;
					
					$cls->updateRecord($id, $datas);
					// array_push($array_current_id, $id);
				}
			}

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

        $rows = $usrcls->getTable();

        $vls   = array() ;

        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[UserGroupTable::C_ID],'desc'=>$row[UserGroupTable::C_NAME]);
            }
        }

        $datas = Util::createOptionValue($vls) ;
		return $datas;
    }
	private function getUserList($params) {
		$cls = new userClass($this->db);

		$sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                case "col_code":
                    $orderby = UserTable::C_NAME . " " . $sort[1];
                    break;
                case "col_name":
                    $orderby = UserTable::C_FULL_NAME . " " . $sort[1];
                    break;
                default:
                    $orderby = UserTable::C_NAME . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = UserTable::C_NAME . " asc";
        }
		$rows = $cls->getTable("",$orderby);
		unset($cls);
		
		$idx 		= 1;
		$html 		= "";
		$cls_group	= new UserGroupClass($this->db);
		$rows_group = $cls_group->getTable();
		
		if( !is_null($rows) && count($rows)>0 ){
			foreach ($rows as $row) {
				$html.= '<tr id="tr_user'.$idx.'" class="existing_user">
							<td><input type="checkbox" id="user_check'.$idx.'" class="user_check" value="'.$idx.'" name="user_chk[]" disabled></td>
                            <td><input type="text" id="user_code'.$idx.'" class="form-control user_name" value="'.$row[UserTable::C_NAME].'"  disabled></td>
							<td><input type="text" id="user_desc'.$idx.'" class="form-control user_full_name" value="'.$row[UserTable::C_FULL_NAME].'"  disabled></td>
							<td><select id="cobusergroup" class="form-control user_option" disabled>';
				foreach ($rows_group as $row_group) {
					if($row_group[UserGroupTable::C_ID] == $row[UserTable::C_USER_GROUP]) {
						$html.='<option value="'. $row_group[UserGroupTable::C_ID] . '" selected>' . $row_group[UserGroupTable::C_NAME] . '</option>';
					} 
					else {
						$html.='<option value="'. $row_group[UserGroupTable::C_ID] . '">' . $row_group[UserGroupTable::C_NAME] . '</option>';
					}
				}
				$html.= '</select></td>
							<td style="display:none" class="user_id" id="user_id'.$idx.'">'.$row[UserTable::C_ID].'</td>
        					<td style="display:none" class="user_idx" id="user_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/UserView.php") ;

        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        $dataReturn = [];
		$dataReturn['htmlContent'] = $var_screen;
        $dataReturn['headTitle']   = "User" ;
		$this->sendJsonResponse(Status::Ok,"User Info",$dataReturn,$this->type);
	}
	private function getUserName() {
		return $_SESSION[SE_USERNAME] ;
	}
	private function getFullName() {
		return $_SESSION[SE_FULLNAME] ;
	}

	private function resetPassword($params=null) {
		$cls = new UserClass($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) {
					$cls->resetPassword($decode);
				}
			}
			$this->db->commitTran();
			$this->sendJsonResponse(Status::Ok,"Successfully reset password of user from system.","",$this->type);
			return;
		} catch (Exception $e) {
			$this->db->rollbackTran() ;
			Log::write('[User] ' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in reseting password of user from the system.","",$this->type);
			return;
		}
		unset ($cls);
	}
}
?>