<?php
class AdminUserModelClass extends ModelClassEx {

	/*-------------------------------------------------------------------------
	* @ メンバ変数
	-------------------------------------------------------------------------*/
	private $rs            					= null;            	// ログデータ
	private $failList           			= null;            	// import fail list (array)
	private $failID            				= NO_STRING;        // import fail id (string)
	private $departmentList  				= NO_STRING;        // department list (array)
	private $importDataJSON            		= NO_STRING;        // import data (string JSON)
	private $uId     						= NO_STRING;       	//admin firstname (string)
	private $userAccount     				= NO_STRING;       	//admin firstname (string)
	private $firstName     					= NO_STRING;       	//admin firstname (string)
	private $lastName      					= NO_STRING;       	//admin lastname (string)
	private $departmentId  					= NO_STRING;       	//admin department id (string)
	private $departmentName					= NO_STRING;       	//admin department name (string)
	private $email		   					= NO_STRING;       	//admin email (string)
	private $functionAccess   				= null;		        //function access (array)
	private $loginFlg 						= NO_STRING;

	//search parameters
	private $sUserAccount					= NO_STRING;		//search userAccount (string)
	private $sName							= NO_STRING;		//search name (string)
	private $sDepartment					= NO_STRING;		//search department (string)
	private $sUserName						= NO_STRING;		//search username (string)
	private $sLastLoginFrom					= NO_STRING;		//search last login from date (string)
	private $sLastLoginTo					= NO_STRING;		//search last login to date (string)

	/**
	 *
	 * anton
	 *
	 */
	private $lang							= NO_STRING;
	private $defPageCount                   = VAR_DEFAULT_PAGE_COUNT;
	private $total;
	
	/*-------------------------------------------------------------------------
	* @function_name: コントロールパネルシステムindexモデルクラスコンストラクタ
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function __construct() {
		// スーパークラスコンストラクタ呼び出し
		parent::__construct();
	}

	/*-------------------------------------------------------------------------
	* @function_name: 初期設定関数
	* @parameter	: なし
	* @return		: 成功:success、失敗:error
	-------------------------------------------------------------------------*/
	public function init() {

		try {
			$rtn = true;

			// パラメータの設定
			$this -> setParameter();

			// チェック
			$this -> validate();

		} catch (Exception $e) {
			throw new Exception(NO_STRING);
		}
	}

	/*-------------------------------------------------------------------------
	* @function_name: パラメータの設定
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function setParameter() {
		//user data input parameters
		$this -> uId						=	$this -> getDataPost(PARAM_UID, true);
		$this -> userAccount				=	$this -> getDataPost(PARAM_USER_ACCOUNT, true);
		$this -> firstName					=	$this -> getDataPost(PARAM_FIRST_NAME, true);
		$this -> lastName					=	$this -> getDataPost(PARAM_LAST_NAME, true);
		$this -> departmentId				=	$this -> getDataPost(PARAM_DEPARTMENT_ID, true);
		$this -> departmentName				=	$this -> getDataPost(PARAM_DEPARTMENT_NAME, true);
		$this -> userName					=	$this -> getDataPost(PARAM_EMAIL, true);
		$this -> functionAccess				=	$this -> getDataPost(PARAM_FUNCTION_ACCESS, true);
		$this -> password					=	$this -> getDataPost(PARAM_PASSWORD, true);
		$this -> loginFlg					=	$this -> getDataPost(PARAM_LOGIN_FLG, true);

		//search parameters
		$this -> sUserAccount				= $this -> getDataPost(PARAM_S_USER_ACCOUNT, true);
		$this -> sName						= $this -> getDataPost(PARAM_S_NAME, true);
		$this -> sDepartment				= $this -> getDataPost(PARAM_DEPARTMENT_ID, true);
		$this -> sLastLoginFrom				= $this -> getDataPost(PARAM_S_LAST_LOGIN_FROM, true);
		$this -> sLastLoginTo				= $this -> getDataPost(PARAM_S_LAST_LOGIN_TO, true);

		//other parameters
		$this -> failID						= $this -> getDataPost(PARAM_FAIL, true, true, true);
		$this -> importDataJSON				= $this -> getDataPost(PARAM_IMPORT_DATA);
		
		$this -> lang						= $this -> getLangage();
	}

	/*-------------------------------------------------------------------------
	* @function_name: サーバ側データチェック
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function validate() {
		$rtn = true;

		// ログインチェック
		if(!$this -> checkAdminUserLogin()) {
			throw new Exception(NO_STRING);
		}

		/**
		 *
		 * -- anton --
		 * 04/22/2019
		 *
		 */
		$redirect = ($this -> lang != "en" ? "" : "{$this -> lang}/");
		
		//check access
		if(!$this -> checkAdminUserAccess('ALST', array(''))){
			$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_PAGE_ACCESS', array());
			header('Location: /'.$redirect.'menu');
			exit();
		}

		if($this -> getType() == TYPE_ADMIN_USER_IMPORT_INPUT) {
			//check access
			if(!$this -> checkAdminUserAccess('ALST', array('','3'))){
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
				header('Location: /'.$redirect.'menu');
				exit();
			}
		}

		if($this -> getType() == TYPE_ADMIN_USER_INPUT) {
			//check access
			if(!$this -> checkAdminUserAccess('ALST', array('','1'))){
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
				header('Location: /'.$redirect.'menu');
				exit();
			}
		}

		if($this -> getType() == TYPE_ADMIN_USER_DETAILS) {
			//check access
			if(!$this -> checkAdminUserAccess('ADTL', array(''))){
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_PAGE_ACCESS', array());
				header('Location: /'.$redirect.'menu');
				exit();
			}
		}

		if($this -> getType() == TYPE_ADMIN_USER_EDIT_INPUT) {
			//check access
			if(!$this -> checkAdminUserAccess('ADTL', array('','1'))){
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
				header('Location: /'.$redirect.'menu');
				exit();
			}
		}

		if($this -> getType() == TYPE_ADMIN_USER_DELETE) {
			//check access
			if(!$this -> checkAdminUserAccess('ADTL', array('', '2'))){
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
				header('Location: /'.$redirect.'menu');
				exit();
			}
		}

		//if type is admin user create
		if($this -> getType() == TYPE_ADMIN_USER_CREATE) {
			$rtn = $this -> validateAdminFields();

			//if $rtn is false then return back to input page.
			if(!$rtn) {
				$this -> setType(TYPE_ADMIN_USER_INPUT);
				return $rtn;
			}
		}

		//if type is admin user edit
		if($this -> getType() == TYPE_ADMIN_USER_EDIT_SAVE) {
			$rtn = $this -> validateAdminFields();
			//check if field is null or if the format is correct
			if(!$this -> checkNull($this -> password)){
				$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_PASSWORD));
				$rtn = false;
			} elseif(!$this -> checkStringAscii($this -> password)) {
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_REGULAR_EMAIL', array(VAL_STR_PASSWORD));
				$rtn = false;
			}

			//if $rtn is false then return back to input page.
			if(!$rtn) {
				$this -> setType(TYPE_ADMIN_USER_DETAILS);
				return $rtn;
			}
		}

		//if type is admin import
		if($this -> getType() == TYPE_ADMIN_USER_IMPORT_CONFIRM) {
			//check if there is a file uploaded
			if(!$this -> checkNull($_FILES[PARAM_ADMIN_CSV][PARAM_NAME])) {
				$this -> popUpSessionMessage(ERROR, 'E_DO_NOT_UPLOAD', array());
				$this -> setType(TYPE_ADMIN_USER_IMPORT_INPUT);
				$rtn = false;
				return $rtn;
			} elseif(!is_uploaded_file($_FILES[PARAM_ADMIN_CSV][PARAM_TMP_NAME])) {
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_UPLOAD_ADMIN_FAILED', array());
				$this -> setType(TYPE_ADMIN_USER_IMPORT_INPUT);
				$rtn = false;
				return $rtn;
			} elseif(strtolower(pathinfo($_FILES[PARAM_ADMIN_CSV][PARAM_NAME], PATHINFO_EXTENSION)) != 'csv') {
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_UPLOAD_FILE_TYPE', array());
				$this -> setType(TYPE_ADMIN_USER_IMPORT_INPUT);
				$rtn = false;
				return $rtn;
			} elseif(count($this -> parseCSV(true)) <= 0){ //check if there is data inside the csv file
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_UPLOAD_DATA_REQUIRED', array());
				$this -> setType(TYPE_ADMIN_USER_IMPORT_INPUT);
				$rtn = false;
				return $rtn;
			}
		}

		//if type is admin import back or admin edit back
		if($this -> getType() == TYPE_ADMIN_USER_IMPORT_BACK) {
			$this -> setType(TYPE_ADMIN_USER_LIST);
		}

		//if type is admin import back or admin edit back
		if($this -> getType() == TYPE_ADMIN_USER_EDIT_BACK) {
			$this -> setType(TYPE_ADMIN_USER_DETAILS);
		}

		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: validateAdminFields
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	public function validateAdminFields() {
		$rtn = true;

		//check if field is null or if the format is correct
		if(!$this -> checkNull($this -> firstName)){
			$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_FIRST_NAME));
			$rtn = false;
		} elseif(!$this -> checkStringAlphabetAndSpace($this -> firstName)) {
			$this -> popUpSessionMessage(ERROR, 'E_ERROR_REGULAR_EMAIL', array(VAL_STR_FIRST_NAME));
			$rtn = false;
		}

		//check if field is null or if the format is correct
		if(!$this -> checkNull($this -> lastName)){
			$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_LAST_NAME));
			$rtn = false;
		} elseif(!$this -> checkStringAlphabetAndSpace($this -> lastName)) {
			$this -> popUpSessionMessage(ERROR, 'E_ERROR_REGULAR_EMAIL', array(VAL_STR_LAST_NAME));
			$rtn = false;
		}

		//check if field is null or if the format is correct
		if(!$this -> checkNull($this -> departmentId)){
			$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_DEPARTMENT));
			$rtn = false;
		} elseif(!$this -> checkStringNumber($this -> departmentId)) {
			$this -> popUpSessionMessage(ERROR, 'E_ERROR_REGULAR_EMAIL', array(VAL_STR_DEPARTMENT));
			$rtn = false;
		}

		//check if field is null or if the format is correct
		if(!$this -> checkNull($this -> userName)){
			$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_USER_NAME));
			$rtn = false;
		} elseif(($this -> getType() == TYPE_ADMIN_USER_CREATE || $this -> getType() != TYPE_ADMIN_USER_EDIT_SAVE) && !$this -> checkMailAddress($this -> userName)) {
			$this -> popUpSessionMessage(ERROR, 'E_NO_SUCH_ANYTHING_DATA', array(VAL_STR_USER_NAME, $this -> userName));
			$rtn = false;
		}

		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 検索条件の取得
	* @parameter	: 結果セット
	* @return		: 検索条件配列
	-------------------------------------------------------------------------*/
	function getWhere() {

		// 変数宣言部
		$where		= NO_STRING;
		$rtn		= array();

		//search via useraccount
		if($this -> sUserAccount != NO_STRING) {
			$where .= ' AND data.user_account = (\')' . $this -> sUserAccount . '(\')';
		}

		//search via name
		if($this -> sName != NO_STRING) {
			$where .= ' AND (data.first_name LIKE (\')%' . $this -> sName . '%(\') OR data.last_name LIKE (\')%' . $this -> sName . '%(\'))';
		}

		//search via department name
		if($this -> sDepartment != NO_STRING) {
			$where .= ' AND department.ad_id LIKE (\')%' . $this -> sDepartment . '%(\')';
		}
		
		if($this -> userName != NO_STRING) {
		    $where .= ' AND data.user_name LIKE (\')%' . $this -> userName . '%(\')';
		}

		//search via last login date (FROM)
		if($this -> loginFlg != NO_STRING){
			if($this -> sLastLoginFrom != '2014/01/01'
					&& $this -> sLastLoginFrom != NO_STRING) {
				$where .= ' AND data.last_login_time >= (\')' . str_replace(DELIMIT_SLASH, DELIMIT_HYPHEN, $this -> sLastLoginFrom) . '(\')';
			}

			//search via last login date (TO)
			if($this -> sLastLoginTo != NO_STRING) {
				$where .= ' AND data.last_login_time < DATE_ADD((\')' . str_replace(DELIMIT_SLASH, DELIMIT_HYPHEN, $this -> sLastLoginTo) . '(\'), INTERVAL 1 DAY)';
			}
		}

		// ページ数
		$start	= ($this -> getTargetPage() - VAL_INT_1) * $this -> defPageCount;

		$page = ' LIMIT ' . $start . DELIMIT_COMMA . $this -> defPageCount;

		//chck if search is not search all
		if($this -> getType() == TYPE_ADMIN_USER_SEARCH_ALL) {
			$where = NO_STRING;
		}

		$rtn[] = $where;
		$rtn[] = $page;

		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 一覧データの設定
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function setResult($rs) {
		$this -> rs = $rs;
	}
	
	public function setTotal($total){
	    $this -> total = $total;
	}

	/*-------------------------------------------------------------------------
	* @function_name: ページャの表示
	* @parameter	: なし
	* @return		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	function dispPager() {
		echo  $this -> getPagerCommon($this -> getTargetPage()
				, $this -> getTotalPageCommon($this -> defPageCount, $this -> total)
				, $this -> total
				, NO_STRING);
	}

	/*-------------------------------------------------------------------------
	* @function_name: generatePassword
	* @parameter	:
	* @return		: string - alphanumeric password
	-------------------------------------------------------------------------*/
	public function generatePassword() {
		$alphaLower				= array();
		$alphaUpper				= array();
		$numeric				= array();
		$characterPool			= array();
		$passwordArray			= array();
		$passwordKeysArray		= array();
		$password				= NO_STRING;

		//generate ascii for lowercase alphabet
		for($char = 97; $char <= 122; $char++) {
			$alphaLower[] = chr($char);
		}

		//generate ascii for uppercase alphabet
		for($char = 65; $char <= 90; $char++) {
			$alphaUpper[] = chr($char);
		}

		//generate ascii for numbers 0-9
		for($char = 48; $char <= 57; $char++) {
			$numeric[] = chr($char);
		}

		//merge the array of characters into one array
		$characterPool = array_merge($alphaLower, $alphaUpper, $numeric);

		//array keys of initial generated password
		$passwordKeysArray = array_rand($characterPool, 8);

		shuffle($passwordKeysArray);

		foreach($passwordKeysArray as $val) {
			$passwordArray[] = $characterPool[$val];
		}

		//final output
		$password = implode($passwordArray);

		return $password;
	}

	/*-------------------------------------------------------------------------
	* @function_name: parseCSV
	* @parameter	: $checkEmpty - boolean - default = false; if true, will only check 2nd row
	* @return		: $adminUsersArray - array containing all user records
	-------------------------------------------------------------------------*/
	public function parseCSV($checkEmpty = false) {
		$adminUsersArray	= array();

		//validate uploaded file
		if(isset($_FILES[PARAM_ADMIN_CSV])){
			//check if upload is via http post
			if(is_uploaded_file($_FILES[PARAM_ADMIN_CSV][PARAM_TMP_NAME])) {
				//open file for reading
				$file = fopen($_FILES[PARAM_ADMIN_CSV][PARAM_TMP_NAME], "r");

				//check if read is successful
				if($file !== false) {
					//create row counter to skip first row reading
					$row = 1;

					//put csv data into array
					while(($data = fgetcsv($file, 2000, ',')) !== false) {
						//check if it is not the first row
						if($row > 1) {
							$adminUsersArray[] = $data;
							//check if $checkEmpty is true
							if($checkEmpty) {
								return $adminUsersArray;
							}
						}
						$row++;
					}
				}

				//close file
				fclose($file);
			}
		}

		return $adminUsersArray;
	}

	/*-------------------------------------------------------------------------
	* @function_name: writeFailToCSV
	* @parameter	: $failArray - array containing failed import data
	* @return		:
	-------------------------------------------------------------------------*/
	public function writeFailToCSV($failArray) {
		//assign variables
		$path 			= SYSTEM_DOCUMENT_ACCOUNT . 'Failed_Admin_Import' . DIRECTORY_SEPARATOR;
		$fileName 		= ($this -> failID != NO_STRING) ?  $this -> failID .  '_fail.csv' : date('YmdHis') . '_fail.csv';
		$exportString	= "Department,Lastname,Firstname,Username"."\n";

		if(!file_exists($path)) {
			mkdir($path, 0777);
		}

		//open file for writing
		$file = fopen($path . $fileName, 'w+');

		//concatenate array data into one string
		foreach($failArray as $failData) {
			$department = $this -> accessSelect('DETAIL_DEPT', array($failData[0]));
			$failData[0] = $this -> getColumnData($department[0], COLUMN_NAME);
			$exportString .= implode(DELIMIT_COMMA, $failData) . "\n";
		}

		//write to csv
		fwrite($file, $exportString);

		fclose($file);
	}

	/*-------------------------------------------------------------------------
	* @function_name: データ一覧の表示
	* @parameter	: なし
	* @return		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	public function echoList() {

		// 変数宣言部
		$rtn	= NO_STRING;
		$row	= null;

		if($this -> isLoopData($this -> rs)) {			
			foreach($this -> rs as $row){
			    $rtn .= '<tr>'
			        . '<td>' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '</td>'
			        . '<td>' . $this -> getColumnData($row, COLUMN_DEPARTMENT_NAME) . '</td>'
			        . '<td>' . $this -> getColumnData($row, COLUMN_LAST_NAME) . '&nbsp;' . $this -> getColumnData($row, COLUMN_FIRST_NAME) . '</td>'
			        . '<td>' . $this -> getColumnData($row, COLUMN_MAIL) . '</td>'
			        . '<td>' . $this -> getColumnData($row, COLUMN_LAST_LOGIN_TIME) . '</td>'
			        . '<td class="blocka"><a href="javascript:actionDetail(\'' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '\');"><span class="fa fa-info-circle fa-lg"></span></a></td>'
			        . '</tr>';
			}
		} else {
			$rtn = '<tr><td colspan="6">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}

		echo $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: echoAdminDetails
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	public function echoAdminDetails() {
		// 変数宣言部
		$rtn	= NO_STRING;
		$row	= null;

		if($this -> isLoopData($this -> rs)) {
			foreach($this -> rs as $row) {
				$rtn .= '<tr>
							<th>'.VAL_STR_ADMIN_UANUMBER.'</th>
							<td>' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '</td>
						</tr>
						<tr>
							<th>'.VAL_STR_DEPARTMENT.'</th>
							<td>' . $this -> getColumnData($row, COLUMN_DEPARTMENT_NAME) . '</td>
						</tr>
						<tr>
							<th>'.VAL_STR_ADMIN_NAME.'</th>
							<td>' . $this -> getColumnData($row, COLUMN_LAST_NAME) . '&nbsp;' . $this -> getColumnData($row, COLUMN_FIRST_NAME) . '</td>
						</tr>
						<tr>
							<th>'.VAL_STR_ADMIN_UNAME.'</th>
							<td>' . $this -> getColumnData($row, COLUMN_MAIL) . '</td>
						</tr>
						<tr>
							<th>'.VAL_STR_PASSWORD.'</th>
							<td>' . $this -> getColumnData($row, COLUMN_PASSWORD) . '</td>
						</tr>';
			}
		} else {
			$rtn = '<tr><td colspan="6">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}

		echo $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: echoAdminEdit
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	public function echoAdminEdit() {
		// 変数宣言部
		$rtn	= NO_STRING;
		$row	= null;

		if($this -> isLoopData($this -> rs)) {
			foreach($this -> rs as $row) {
				$rtn .= '<tr>
							<th>User Account</th>
							<td>' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '<input type="hidden" value="' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '" name="user_account" /><input type="hidden" value="' . $this -> getColumnData($row, COLUMN_UID) . '" name="u_id" /></td>
						</tr>
						<tr>
							<th>Department</th>
							<td>' . $this -> getDepartmentDropdown($this -> getColumnData($row, COLUMN_DEPARTMENT_NAME), true) . '</td>
						</tr>
						<tr>
							<th>Name</th>
							<td><input type="text" value="' . $this -> getColumnData($row, COLUMN_LAST_NAME) . '" name="last_name" placeholder="Last Name" /> &nbsp; <input type="text" value="' . $this -> getColumnData($row, COLUMN_FIRST_NAME) . '" name="first_name" placeholder="First Name" /></td>
						</tr>
						<tr>
							<th>Username</th>
							<td><input type="text" value="' . $this -> getColumnData($row, COLUMN_MAIL) . '"  name="email" /></td>
						</tr>
						<tr>
							<th>Password</th>
							<td><input type="text" value="' . $this -> getColumnData($row, COLUMN_PASSWORD) . '"  name="password" /></td>
						</tr>';
			}
		} else {
			$rtn = '<tr><td colspan="6">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}

		echo $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: echoAdminFunctionAccess
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	public function echoAdminFunctionAccess() {
		// 変数宣言部
		
		
		
		$rtn	= NO_STRING;
		$row	= null;
		$rtn .= '<table class="table col bdr default odd w60p fontXS m_auto mb20" id="functionDetails">';
		if($this -> isLoopData($this -> rs)) {
			foreach($this -> rs as $row) {
				$functionAccessList 	= unserialize($this -> getColumnData($row, COLUMN_FUNC_ACCESS));

				//check function list count
				if($functionAccessList != NO_STRING) {
					if($this -> getType() == TYPE_ADMIN_USER_EDIT_INPUT) {
						//get department functionlist
					    $res = $this -> accessSelect('DETAIL_DEPT', array($this -> getColumnData($row, COLUMN_DEPARTMENT_ID)));
						$functionList = unserialize($this -> getColumnData($res[0], 'function_list'));
					} elseif($this -> getType() == TYPE_ADMIN_USER_DETAILS) {
						$functionList		= array_keys($functionAccessList);
					}
					
					if(count($functionList) > 0) {
						$functionListString = implode(DELIMIT_COMMA, $functionList);
						//get function list with category
						$functionDetails = $this -> accessSelect('LIST_DEPT_FUNCTION', array($functionListString));


						/********************table creation**************************/
						$categoryArray = array();
						foreach($functionDetails as $row) {
							$categoryId     = $row['category_id'];
							$accessArray    = unserialize($row['function_access']);
							$accessString   = NO_STRING;
							$functionId		= $row['function_id'];
							$accessFlag		= (isset($functionAccessList[$functionId]) && is_array($functionAccessList[$functionId])) ? true : false;
							$disabled		= ($this -> getType() == TYPE_ADMIN_USER_DETAILS) ? 'disabled' : NO_STRING;

							//build access checkbox
							if(in_array(1, $accessArray)) {
								$checked = NO_STRING;
								if($accessFlag && in_array(1, $functionAccessList[$functionId])){
									$checked = 'checked="checked"';
								}
								$edit = VAL_STR_ADMIN_EDIT;
								$accessString .= '<input type="checkbox" name="function_access['.$functionId.'][]" value="1" '.$checked.' '.$disabled.' class="functionAccess" >'.$edit;
							}

							if(in_array(2, $accessArray)) {
								$checked = NO_STRING;
								if($accessFlag && in_array(2, $functionAccessList[$functionId])){
									$checked = 'checked="checked"';
								}
								$delete = VAL_STR_REMOVE;
								$accessString .= '<input type="checkbox" name="function_access['.$functionId.'][]" value="2" '.$checked.' '.$disabled.' class="functionAccess" >'.$delete;
							}

							if(in_array(3, $accessArray)) {
								$checked = NO_STRING;
								if($accessFlag && in_array(3, $functionAccessList[$functionId])){
									$checked = 'checked="checked"';
								}

								$upload = VAL_STR_ADMIN_UPLOAD;
								$accessString .= '<input type="checkbox" name="function_access['.$functionId.'][]" value="3" '.$checked.' '.$disabled.' class="functionAccess" >'.$upload;
							}

							if(!in_array($categoryId, $categoryArray)) {
								$categoryArray[] = $categoryId;
								$rtn .= '<tr>
											<th colspan="2">' . $row['category_name'] . '</th>
										</tr>';
							}

							$checked = ($accessFlag) ? 'checked' : '';
							$rtn .= '<tr>
										<td><input type="checkbox" name="function_access['.$functionId.'][]" value="" '.$checked.' '.$disabled.' class="functionName" >' . $row['function_name'] . '</td>
										<td>' . $accessString . '</td>
									</tr>';
						}
					}
				} else {
					if($this -> getType() == TYPE_ADMIN_USER_EDIT_INPUT) {
						$rtn .= $this -> getDepartmentFunctionList($this -> getColumnData($row, COLUMN_DEPARTMENT_ID), $this -> lang);
					}
				}
			}
		}
		$rtn .= '</table>';
		echo $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: echoImportList
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	public function echoImportList() {
		// 変数宣言部
		$rtn		= NO_STRING;
		$row		= null;
		$importData = array();

		//get import data
		$importData = json_decode($this -> getImportData(), true);

		$rtn .= '<tr>
					<th>'.VAL_STR_DEPARTMENT.'</th>
					<th>'.VAL_STR_FIRST_NAME.'</th>
					<th>'.VAL_STR_LAST_NAME.'</th>
					<th>'.VAL_STR_ADMIN_UNAME.'</th>
				</tr>';

		if(count($importData) > 0) {
			foreach($importData as $row) {
				$department		= $this -> accessSelect('DETAIL_DEPT', array($row[0])); //get department name
				$rtn .= '<tr>
							<td>' . $this -> getColumnData($department[0], COLUMN_NAME) . '</td>
							<td>' . $row[1] . '</td>
							<td>' . $row[2] . '</td>
							<td>' . $row[3] . '</td>
						</tr>';
			}
		} else {
			$rtn = '<tr><td colspan="6">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}

		echo $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: echoFailList
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	public function echoFailList() {
		// 変数宣言部
		$rtn	= NO_STRING;
		$row	= null;

		//set table headers
		$rtn .= '<tr>
		<th>'.VAL_STR_DEPARTMENT.'</th>
		<th>'.VAL_STR_FIRST_NAME.'</th>
		<th>'.VAL_STR_LAST_NAME.'</th>
		<th>'.VAL_STR_ADMIN_UACCOUNT.'</th>
				</tr>';

		if($this -> isLoopData($this -> failList)) {
			foreach($this -> failList as $row) {
				$department		= $this -> accessSelect('DETAIL_DEPT', array($row[0])); //get department name
				$rtn .= '<tr>
							<td>' . $this -> getColumnData($department[0], COLUMN_NAME) . '</td>
							<td>' . $row[1] . '</td>
							<td>' . $row[2] . '</td>
							<td>' . $row[3] . '</td>
						</tr>';
			}
		} else {
			$rtn = '<tr><td colspan="6">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}

		echo $rtn;
	}

	public function getField($fieldName){
	    return $this -> {$fieldName};
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: setParameterCSV
	* @parameter	: $adminUserData - array containing admin user data
	* @return		:
	-------------------------------------------------------------------------*/
	public function setParameterCSV($adminUserData) {
		$this -> departmentId	= $adminUserData[0];	//department
		$this -> firstName		= $adminUserData[1];	//firstname
		$this -> lastName		= $adminUserData[2];	//lastname
		$this -> userName		= $adminUserData[3];	//userName
	}

	/*-------------------------------------------------------------------------
	* @function_name: setFailID
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	public function setFailID() {
		$this -> failID = date('YmdHis');
	}

	/*-------------------------------------------------------------------------
	* @function_name: setDepartmentList
	* @parameter	: $departmentArray - array containing all departments and its data
	* @return		:
	-------------------------------------------------------------------------*/
	public function setDepartmentList($departmentArray) {
		$this -> departmentList = $departmentArray;
	}

	/*-------------------------------------------------------------------------
	* @function_name: setFailList
	* @parameter	: $failArray - array containing the failed import data
	* @return		:
	-------------------------------------------------------------------------*/
	public function setFailList($failArray) {
		$this -> failList = $failArray;
	}

	/*-------------------------------------------------------------------------
	* @function_name: setAdminUserDataJSON
	* @parameter	: $dataArray - array containing the import data
	* @return		:
	-------------------------------------------------------------------------*/
	public function setAdminUserDataJSON($dataArray) {
		$count = count($dataArray);

		for($i = 0; $i < $count; $i++) {
			$department = $this -> accessSelect('DETAIL_DEPT_BY_NAME', array($dataArray[$i][0]));
			$dataArray[$i][0] = $this -> getColumnData($department[0], COLUMN_AD_ID);
		}



		$this -> importDataJSON = json_encode($dataArray);
	}

	/*-------------------------------------------------------------------------
	* @function_name: getDepartmentDropdown
	* @parameter	: $departName - default null
	* @return		:
	-------------------------------------------------------------------------*/
	public function getDepartmentDropdown($findWhat = null, $forDepartmentName = false) {
		$rtn  			= NO_STRING;
		$departmentList = $this -> getDepartmentList();

		$rtn .= '<select class="select" name="department_id" id="department_id" >
				<option value="">--- All ---</option>';

		foreach ($departmentList as $department) {
		    $comparedColumn = $forDepartmentName ? COLUMN_NAME : COLUMN_AD_ID;
		    
		    //check if department name is not null and is equal to the department name of the current option
		    if($this -> getColumnData($department, $comparedColumn) == $findWhat) {
				$rtn .= '<option value=' .  $this -> getColumnData($department, COLUMN_AD_ID) . ' selected=\'selected\' >' . $this -> getColumnData($department, COLUMN_NAME) . '</option>';
			} else {
				$rtn .= '<option value=' .  $this -> getColumnData($department, COLUMN_AD_ID) . '>' . $this -> getColumnData($department, COLUMN_NAME) . '</option>';
			}
		}

		$rtn .= '</select>';
		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getUserAccount
	* @parameter	:
	* @return		: string - user account
	-------------------------------------------------------------------------*/
	public function getUserAccount() {
		return $this -> userAccount;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getImportData
	* @parameter	:
	* @return		: array - import data
	-------------------------------------------------------------------------*/
	public function getImportData() {
		return $this -> importDataJSON;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getFailID
	* @parameter	:
	* @return		: string - failID
	-------------------------------------------------------------------------*/
	public function getFailID() {
		return $this -> failID;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getDepartmentList
	* @parameter	:
	* @return		: array - department list
	-------------------------------------------------------------------------*/
	public function getDepartmentList() {
		return $this -> departmentList;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getDepartmentName
	* @parameter	:
	* @return		: string - department list
	-------------------------------------------------------------------------*/
	public function getDepartmentName() {
		return $this -> departmentName;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getUserEditData
	* @parameter	:
	* @return		: array - user edited data
	-------------------------------------------------------------------------*/
	public function getUserEditData() {
		$params = array();

		$params['u_id'] 			= $this -> uId;							//uid
		$params['user_account'] 	= $this -> userAccount;					//user account
		$params['user_name'] 		= $this -> userName;					//user account
		$params['first_name'] 		= $this -> firstName;					//user firstname
		$params['last_name'] 		= $this -> lastName;					//user lastname
		$params['department'] 		= $this -> departmentId;				//department
		$params['password'] 		= $this -> password;					//password
		$params['function_access'] 	= serialize($this -> functionAccess);	//admin access array

		return $params;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getUserAdminData
	* @parameter	:
	* @return		: array - user data
	-------------------------------------------------------------------------*/
	public function getUserAdminData() {
		$params = array();

		//generate user account and uid
		$this -> uId		 = $this -> createUId();
		$this -> userAccount = $this -> createAccount();

		$params[] = $this -> uId;					//uId
		$params[] = $this -> userName;				//email (username)
		$params[] = $this -> userAccount;			//user account
		$params[] = $this -> lastName;				//user lastname
		$params[] = $this -> firstName;				//user firstname
		$params[] = '1';							//admin flag
		$params[] = '2';							//status
		$params[] = '0000000000';					//gps kind of payment

		return $params;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getUserAccessData
	* @parameter	:
	* @return		: array - user access data
	-------------------------------------------------------------------------*/
	public function getUserAccessData() {
		$params = array();

		$params[] = $this -> uId;							//uId
		$params[] = $this -> userAccount;					//user account
		$params[] = $this -> departmentId;					//department
		$params[] = serialize($this -> functionAccess);		//function access array

		return $params;
	}

	/*-------------------------------------------------------------------------
	* @function_name: getDepartmentFunctionList
	* @parameter	: $departmentId - id of the department to search
	* @return		: string -
	-------------------------------------------------------------------------*/
	/**
	 * 
	 * 2019/04/03
	 * ($lang) func_param -- anton
	 * 
	 */
	function getDepartmentFunctionList($departmentId, $lang = "ja") {
		
	    $rtn                    = NO_STRING;
	    $functionListString     = NO_STRING;
	    $functionList           = array();
	    $functionAccess         = array();
	    $departmentFunctionList = array();

	    //get department functionlist
	    $res = $this -> accessSelect('DETAIL_DEPT', array($departmentId));

	    //check if there is a record
	    if(count($res) > 0 && count($res[0]) > 0) {
	        $functionList = unserialize($this -> getColumnData($res[0], 'function_list'));
	    }

	    //check function list count
	    if(count($functionList) > 0) {
	        $functionListString = implode(DELIMIT_COMMA, $functionList);
	        //get function list with category
	        $functionDetails = $this -> accessSelect('LIST_DEPT_FUNCTION', array($functionListString));


	        /********************table creation**************************/
	        $categoryArray = array();
	        foreach($functionDetails as $row) {
	            $categoryId     = $row['category_id'];
	            $accessArray    = unserialize($row['function_access']);
	            $accessString   = NO_STRING;
	            $functionId		= $row['function_id'];

	            //build access checkbox
	            if(in_array(1, $accessArray)) {
	            	$edit = VAL_STR_ADMIN_EDIT;
	                $accessString .= '<input type="checkbox" name="function_access['.$functionId.'][]" value="1" class="functionAccess" >'.$edit;
	            }

	            if(in_array(2, $accessArray)) {
	            	$delete = VAL_STR_REMOVE;
	                $accessString .= '<input type="checkbox" name="function_access['.$functionId.'][]" value="2" class="functionAccess" >'.$delete;
	            }

	            if(in_array(3, $accessArray)) {
	            	$upload = VAL_STR_ADMIN_UPLOAD;
	                $accessString .= '<input type="checkbox" name="function_access['.$functionId.'][]" value="3" class="functionAccess" >'.$upload;
	            }

	            if(!in_array($categoryId, $categoryArray)) {
	                $categoryArray[] = $categoryId;
	                $rtn .= '<tr>
	                    <th colspan="2">' . $row['category_name'] . '</th>
	                </tr>';
	            }

	            $rtn .= '<tr>
	                <td><input type="checkbox" name="function_access['.$functionId.'][]" value="" class="functionName" >' . $row['function_name'] . '</td>
	                <td>' . $accessString . '</td>
	            </tr>';
	        }
	    }

	    return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: HTML表示用のデータ取得関数
	* @parameter	: なし
	* @return		: HTML表示用データ配列
	-------------------------------------------------------------------------*/
	public function dispHTML() {
		return array();
	}

	/*-------------------------------------------------------------------------
	* @function_name: dispLoginFlg
	* @parameter	: NONE
	* @return		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	function dispLoginFlg() {
		echo '<label>'
				. $this -> makeCheckOne(PARAM_LOGIN_FLG
											, PARAM_LOGIN_FLG
											, VAL_INT_1
											, NO_STRING, $this -> loginFlg)
				. '</label>';
	}

	/*-------------------------------------------------------------------------
	* @function_name: getActivity
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function getActivity() {
		$type = $this -> getType();

		
		if($type == TYPE_ADMIN_USER_EDIT_SAVE){
			$rs 				= $this -> accessSelect('SELECT_ADMIN_USER', array($this -> userAccount));

			$oldList			= unserialize($this -> getColumnData($rs[NO_COUNT], COLUMN_FUNC_ACCESS));
			$newList 			= $this -> functionAccess;
			$oldUserName 		= $this -> getColumnData($rs[NO_COUNT], COLUMN_USER_NAME);
			$oldFirstName 		= $this -> getColumnData($rs[NO_COUNT], COLUMN_FIRST_NAME);
			$oldLastName 		= $this -> getColumnData($rs[NO_COUNT], COLUMN_LAST_NAME);
			$oldDept 			= $this -> getColumnData($rs[NO_COUNT], COLUMN_DEPARTMENT_NAME);
			$oldPassword 		= $this -> getColumnData($rs[NO_COUNT], COLUMN_PASSWORD);
			$newUsername		= $this -> userName;					//user account
			$newFirstName 		= $this -> firstName;					//user firstname
			$newLastName 		= $this -> lastName;					//user lastname
			$newDept	 		= $this -> departmentId;				//department
			$newPassword 		= $this -> password;
			$detail 			= array();

			if($oldList != $newList){
				$detail[]   			= 'function list';
				$oldFunctionList		= ($oldList != NO_STRING) ? array_keys($oldList) : array();

				$newFunctionList 		= ($newList != NO_STRING) ? array_keys($newList) : array();

				$accessList 			= array('', 'Edit', 'Delete', 'Upload');

				$sameValue				= array_intersect($oldFunctionList, $newFunctionList);
				$removed				= array_diff($oldFunctionList, $sameValue);
				$added					= array_diff($newFunctionList, $sameValue);
				$theIds 				= array();
				foreach ($sameValue as $value) {
					$theIds[] = "fl.fl_id = ".$value;
				}
				$theValues 				= implode(' OR ', $theIds);
				$result 				= $this -> accessSelect('SELECT_ADMIN_FUNCTION_VIA_ID', array($theValues));
				$cnt = 0;

				if($oldList != NO_COUNT){
					foreach ($oldList as $key => $value) {
						if(in_array($key, $newFunctionList)){
							if($value != $newList[$key]){
								$removedAccess	= array_diff($value, $newList[$key]);
								$addedAccess	= array_diff($newList[$key], $value);
								$funcName 		= $this -> getColumnData($result[$cnt], COLUMN_NAME);
								$access 		= array();
								$access2 		= array();
								if((count($removedAccess)) != NO_COUNT){
									foreach ($removedAccess as  $value) {
										$access[] .= ' Disabled '.$accessList[$value].' function';
									}
								}

								if((count($addedAccess)) != NO_COUNT){
									foreach ($addedAccess as  $value) {
										$access2[] .= 'Enabled '.$accessList[$value].' function';
									}
								}
								$detail[] = $funcName.' ['.implode(', ', array_merge($access2, $access)). ']';
							}
							$cnt++;
						}

					}
				}

				if((count($added)) != NO_COUNT){

					foreach ($added as $value) {
						$fl_id[] = "fl.fl_id = ".$value;
					}


					$ids = implode(' OR ', $fl_id);
					$rs = $this -> accessSelect('SELECT_ADMIN_FUNCTION_VIA_ID', array($ids));

					$getFunctionNameAdded = array();
					$getAccess 			  = array();

					foreach ($rs as $row) {
						$getFunctionNameAdded[] = $this -> getColumnData($row, COLUMN_NAME);
						$getAccess[] = $this -> getColumnData($row, COLUMN_FUNC_ACCESS);
					}

					$addedFunctions 	= implode(", ", $getFunctionNameAdded);
					$detail[] 			.= ' added ['. $addedFunctions.']';
					
					$cnt 				= NO_COUNT;
					$deet = array();

					foreach ($newList as $keys => $values) {
						if(in_array($keys, $added)){
							$enabledMsg = array();
							foreach ($values as $accesses) {
								if($accesses != ''){
									$enabledMsg[] = 'Enabled '.$accessList[$accesses].' Function';
								}
							}
							$detail[] = $getFunctionNameAdded[$cnt].' ['. implode(', ', $enabledMsg).']';
						$cnt++;
						}
					}
				}

				if((count($removed)) != NO_COUNT){

					foreach ($removed as $value) {
						$fl_id2[] = "fl.fl_id = ".$value;
					}
					$ids2 = implode(' OR ', $fl_id2);
					$rs2 = $this -> accessSelect('SELECT_ADMIN_FUNCTION_VIA_ID', array($ids2));
					$getFunctionNameRemoved = array();
					foreach ($rs2 as $row){
						$getFunctionNameRemoved[] = $this -> getColumnData($row, COLUMN_NAME);
					}

					$removedFunctions 		= implode(", ", $getFunctionNameRemoved);
					$detail[] 				.= ' removed ['. $removedFunctions.']';

				}

				


			}

			if($oldUserName != $newUsername){
				$detail[] = 'username from ['.$oldUserName.'] to ['.$newUsername.']';
			}

			if($oldFirstName != $newFirstName){
				$detail[] = 'first name from ['.$oldFirstName.'] to ['.$newFirstName.']';
			}

			if($oldLastName != $newLastName){
				$detail[] = 'last name from ['.$oldLastName.'] to ['.$newLastName.']';
			}

			if($oldDept != $this -> getDeptName($newDept)){
				$detail[] = 'department from ['.$oldDept.'] to ['.$this -> getDeptName($newDept).']';
			}

			if($oldPassword != $newPassword){
				$detail[] = 'pasword from ['.$oldPassword.'] to ['.$newPassword.']';
			}

			

			if($detail != NULL){
   				$message = '[Admin List] <br> Edited Admin '. $newUsername .'\'s '. implode(', <br/>', $detail);
   			}else{
   				$message = 'Saved without any changes';
   			}

		}elseif($type == TYPE_ADMIN_USER_DELETE){
			$message = 'Deleted admin account '.$this -> userAccount;
		}elseif($type == TYPE_ADMIN_USER_CREATE){
			$message = 'Created new admin user '.$this -> firstName.' '.$this -> lastName;
		}

		$rtn = array();

		$rtn[] = $this -> getAdminUserData(PARAM_UID);
		$rtn[] = $_SERVER[PARAM_REMOTE_ADDR];
		$rtn[] = $_SERVER[PARAM_HTTP_USER_AGENT];
		$rtn[] = 23;
		$rtn[] = date("Y-m-d H:i:s");
		$rtn[] = $message;

		return $rtn;


	}

	function getDeptName($id){
		$rs 	= $this -> accessSelect('DETAIL_DEPT', array($id));
		$name 	= $this -> getColumnData($rs[0], COLUMN_NAME);

		return $name;	
	}
}

?>