<?php
use function GuzzleHttp\json_decode;

class ApiSignatureModelClass extends ModelClassEx {

	/*-------------------------------------------------------------------------
	* @ メンバ変数
	-------------------------------------------------------------------------*/
	private $rs					= null;			// 出金リスト
	private $account			= null;			// 口座情報
	private $aId				= NO_STRING;	// APIID
	private $userAccount		= NO_STRING;	// 口座番号
	private $firstName			= NO_STRING;	// 名
	private $lastName			= NO_STRING;	// 姓
	private $userName			= NO_STRING;	// ユーザ名
	private $password			= NO_STRING;	// パスワード
	private $ipAddress			= NO_STRING;	// IPアドレス
	private $domainName			= NO_STRING;	// ドメイン名
	private $whitelistSet	    = NO_STRING;	// ホワイトリスト設定
	
	private $lang				= NO_STRING;

	// ------------------ 検索系 ------------------//
	// ------------------ 検索系 ------------------//

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

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

		try {

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

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

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

	/*-------------------------------------------------------------------------
	* @function_name: パラメータの設定
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function setParameter() {
		$this -> aId			= $this -> getDataPost(PARAM_A_ID);			          // APIID
		$this -> userAccount	= $this -> getDataPost(PARAM_USER_ACCOUNT);	          // 口座番号
		$this -> userName		= $this -> getDataPost(PARAM_USER_NAME);	          // ユーザ名
		$this -> password		= $this -> getDataPost(PARAM_PASSWORD);		          // パスワード
		$this -> ipAddress		= $this -> getDataPost(PARAM_IP_ADDRESS);	          // IPアドレス
		$this -> domainName		= $this -> getDataPost(PARAM_DOMAIN_NAME);	          // IPアドレス
		$this -> whitelistSet   = $this -> getDataPost(PARAM_WHITELIST_SETTING);	  // ホワイトリスト設定
		
		$this -> lang			= $this -> getLangage();
	}

	/*-------------------------------------------------------------------------
	* @function_name: パラメータの再設定
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function restore() {
		$this -> lastName	= $this -> getColumnData($this -> account, COLUMN_LAST_NAME);
		$this -> firstName	= $this -> getColumnData($this -> account, COLUMN_FIRST_NAME);
		$this -> userAccount = $this -> getColumnData($this -> account, COLUMN_USER_ACCOUNT);

		// 修正データ取得の場合
		if($this -> getType() == TYPE_EDIT && $this -> isLoopData($this -> rs)) {
		    $this -> userName	  = $this -> getColumnData($this -> rs, COLUMN_USER_NAME);
		    $this -> password	  = $this -> getColumnData($this -> rs, COLUMN_PASSWORD);
		    $this -> ipAddress	  = $this -> getColumnData($this -> rs, COLUMN_IP_ADDRESS);
		    $this -> domainName   = $this -> getColumnData($this -> rs, COLUMN_DOMAINS);
			
		    if($this -> checkJSONString($this -> getColumnData($this -> rs, COLUMN_WHITELIST_SETTING))){
			    $this -> whitelistSet = [];
			    $wlsets = (array) json_decode($this -> getColumnData($this -> rs, COLUMN_WHITELIST_SETTING));
			    
			    foreach($wlsets as $key => $var){
			        if($var)
			            $this -> whitelistSet[] = $key;
			    }
			}
		}
	}

	/*-------------------------------------------------------------------------
	* @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('APUR', array(''))){
			$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_PAGE_ACCESS', array());
			header('Location: /'.$redirect.'menu');
			exit();
		}

		if($this -> getType() == CONTROL_ACTION || $this -> getType() == TYPE_EDIT || $this -> getType() == TYPE_SAVE) {
			//check access
			if(!$this -> checkAdminUserAccess('APUR', array('','1'))){
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
				header('Location: /'.$redirect.'menu');
				exit();
			}
			
		}
		
		/**
		 * 
		 * -- anton --
		 * 12/17/2019
		 * 
		 */
		if($this -> getType() == TYPE_DELETE){
		    //check access
		    if(!$this -> checkAdminUserAccess('APUR', array('','2'))){
		        $this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
		        header('Location: /'.$redirect.'menu');
		        exit();
		    }
		   
		    // checks if an api credential exists 
		    $apiSignature = $this -> getAPISignatureCommon($this -> aId);
		    if(count($apiSignature) !== 0){
		            
		        // checks if a user account exist
		        if(count($this -> getAccountCommon($this -> userAccount)) === 0){
		            $this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
		            header('Location: /'.$redirect.'menu');
		            exit();
		        }
		        
		        // checks if a user account # is a property of a selected a_id
		        if(strcmp($this -> userAccount, $apiSignature[0][COLUMN_USER_ACCOUNT]) !== 0){ 
		            $this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
		            header('Location: /'.$redirect.'menu');
		            exit();
		        }
		        
		    }else{
		        $this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
		        header('Location: /'.$redirect.'menu');
		        exit();
		    }
		}
		
		if($this -> getType() == TYPE_INPUT) {				// 口座入力時の場合

			// 口座番号の入力チェック
			if(!$this -> checkNull($this -> userAccount)) {
				$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_USER_ACCOUNT));
				$rtn = false;
			}

			// 口座番号の存在チェック
			if(!$this -> checkExistAccount($this -> userAccount)) {
				$this -> popUpSessionMessage(ERROR, 'E_ERROR_NOT_EXIST', array(VAL_STR_USER_ACCOUNT));
				$rtn = false;
			}

			if($this -> alreadyRegistered($this -> userAccount)){
			   $this -> popUpSessionMessage(ERROR, 'E_EXIST_DATA', array(VAL_STR_USER_ACCOUNT));
			   $rtn = false;
			}

			if(!$rtn) {
				$this -> setType(CONTROL_ACTION);
				return $rtn;
			}

		} else if($this -> getType()		== TYPE_CONFIRM
					|| $this -> getType()	== TYPE_SAVE) {	// 入力確認時

			// 必須項目チェック
			// ユーザ名の入力チェック
			if(!$this -> checkNull($this -> userName)) {
				$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_USER_NAME));
				$rtn = false;
			}

			// パスワードの入力チェック
			if(!$this -> checkNull($this -> password)) {
				$this -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', array(VAL_STR_PASSWORD));
				$rtn = false;
			}

			if(!$rtn) {

				if($this -> getType() == TYPE_CONFIRM) {		// 入力画面へ戻す
					$this -> setType(TYPE_INPUT);
					return $rtn;

				} else if($this -> getType()	== TYPE_SAVE) {	// 修正画面へ戻す
					$this -> setType(TYPE_BACK);
					return $rtn;
				}
			}
		}

		return true;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 検索条件の取得
	* @parameter	: なし
	* @return		: 検索条件
	-------------------------------------------------------------------------*/
	public function getWhere() {

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

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

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

		// 変数宣言部
		$rtn			= NO_STRING;
		$tType			= NO_STRING;

		if($this -> isLoopData($this -> rs)) {

			// データの数だけループを回す
			$start		= ($this -> getTargetPage() - VAL_INT_1) * VAR_DEFAULT_PAGE_COUNT;
			$end		= $this -> getTargetPage() * VAR_DEFAULT_PAGE_COUNT;
			$listCount	= count($this -> rs);
			for($cnt = $start; $cnt < $end && $cnt < $listCount; $cnt++) {

				$row = $this -> getRowData($this -> rs, $cnt);

				$rtn	.= '<tr>'
							. '<td>' . $this -> getColumnData($row, COLUMN_A_ID) . '</td>'
							. '<td class="l"><a href="javascript:userDetail(\'' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '\', \'_blank\');">' . $this -> getColumnData($row, COLUMN_FIRST_NAME) . DELIMIT_SPACE . $this -> getColumnData($row, COLUMN_LAST_NAME) . '</a></td>'
							. '<td>' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '</td>'
							. '<td>' . $this -> getColumnData($row, COLUMN_USER_NAME) . '</td>'
							. '<td>' . $this -> getColumnData($row, COLUMN_PASSWORD) . '</td>'
							. '<td>' . $this -> getColumnData($row, COLUMN_IP_ADDRESS) . '</td>'
							. '<td class="blocka"><a href="javascript:actionEdit(\'' . $this -> getColumnData($row, COLUMN_A_ID) . '\');"><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;
	}
	
	private function getWhitelistSettingPayload(){
	    $whitelistSetting = [
	        "allow_ip_in_payment" => false,
	        "allow_domain_in_payment" => false,
	        "allow_curl_in_payment" => false,
	        "allow_ip_in_remittance" => false,
	        "allow_domain_in_remittance" => false
	    ];
	    
	    foreach(array_keys($whitelistSetting) as $key){
	        if(in_array($key, $this -> whitelistSet))
	            $whitelistSetting[$key] = true;
	    }
	    
	    return json_encode($whitelistSetting);
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: 登録データの取得
	* @parameter	: なし
	* @return		: 登録パラメータの取得
	-------------------------------------------------------------------------*/
	public function getRegistParams() {
		// 変数宣言部
		$rtn = array();
	
		// パラメータの設定
		$rtn = [
		    $this -> getSequenceNo(API_SIGNATURE),
		    $this -> userAccount,
		    $this -> userName,
		    $this -> password,
		    $this -> ipAddress,
		    $this -> domainName,
		    $this -> getWhitelistSettingPayload()
		];
		
		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 更新データの取得
	* @parameter	: なし
	* @return		: 更新パラメータの取得
	-------------------------------------------------------------------------*/
	public function getUpdateParams() {
		// 変数宣言部
		$rtn = array();
		
		// パラメータの設定
		$rtn = [
		    $this -> userAccount,
		    $this -> userName,
		    $this -> password,
		    $this -> ipAddress,
		    $this -> domainName,
		    $this -> getWhitelistSettingPayload()
		];
		
		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 出金リストの設定
	* @parameter	: 出金リスト
	* @return		: なし
	-------------------------------------------------------------------------*/
	public function setResult($rs) {
		$this -> rs = $rs;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 口座情報の設定
	* @parameter	: 口座情報
	* @return		: なし
	-------------------------------------------------------------------------*/
	public function setAccount($rs) {
		$this -> account = $this -> getRowData($rs);
	}

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

	
	public function getAId(){
	    return $this -> aId;
	}
	
	public function echoAId(){
	    echo $this -> aId;
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: 口座番号の取得
	* @parameter	: なし
	* @return		: 口座番号
	-------------------------------------------------------------------------*/
	public function getUserAccount() {
		return $this -> userAccount;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 口座番号の取得
	* @parameter	: なし
	* @return		: 口座番号
	-------------------------------------------------------------------------*/
	public function echoUserAccount() {
		echo $this -> userAccount;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 名の取得
	* @parameter	: なし
	* @return		: 名
	-------------------------------------------------------------------------*/
	public function echoLastName() {
		echo $this -> lastName;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 姓の取得
	* @parameter	: なし
	* @return		: 姓
	-------------------------------------------------------------------------*/
	public function echoFirstName() {
		echo $this -> firstName;
	}

	/*-------------------------------------------------------------------------
	* @function_name: ユーザ名の取得
	* @parameter	: なし
	* @return		: ユーザ名
	-------------------------------------------------------------------------*/
	public function echoUserName() {
		echo $this -> userName;
	}

	/*-------------------------------------------------------------------------
	* @function_name: パスワードの取得
	* @parameter	: なし
	* @return		: パスワード
	-------------------------------------------------------------------------*/
	public function echoPassword() {
		if($this -> password == NO_STRING) {
			echo $this -> createPassword();
		} else {
			echo $this -> password;
		}
	}

	/*-------------------------------------------------------------------------
	* @function_name: IPアドレスの取得
	* @parameter	: なし
	* @return		: IPアドレス
	-------------------------------------------------------------------------*/
	public function echoIpAddress() {
		echo $this -> ipAddress;
	}
	
	/*-------------------------------------------------------------------------
	 * @function_name: ドメイン名の取得
	 * @parameter	: なし
	 * @return		: ドメイン名
	 -------------------------------------------------------------------------*/
	public function echoDomainName() {
	    echo $this -> domainName;
	}
	
	/*-------------------------------------------------------------------------
	 * @function_name: ホワイトリスト管理の設定の取得
	 * @parameter	: なし
	 * @return		: ホワイトリスト管理の設定
	 -------------------------------------------------------------------------*/
	public function echoWhitelistSettingsCheckboxes($disabled = false) {
	    $settings = [
            "Payment API" => [
                VAL_STR_IP_ADDRESS_VALIDATION => "allow_ip_in_payment",
                VAL_STR_DOMAIN_NAME_VALIDATION => "allow_domain_in_payment",
                VAL_STR_ALLOW_SERVER_TO_SERVER => "allow_curl_in_payment"
            ],
	        "Remittance API" => [
	            VAL_STR_IP_ADDRESS_VALIDATION => "allow_ip_in_remittance",
	            VAL_STR_DOMAIN_NAME_VALIDATION => "allow_domain_in_remittance"
	        ]
	    ];
	    
	    foreach($settings as $setKey => $setVars){
	        echo "<b>{$setKey}</b>";
	        echo "<label class=\"method_name\">";
	        
	        foreach($setVars as $vkey => $var){
	            $checked = in_array($var, $this -> whitelistSet) ? "checked" : NO_STRING;
	            $disabled = $disabled ? "disabled" : NO_STRING;
	            
	            echo "<input type=\"checkbox\" class=\"wl-set-cbox\" value=\"{$var}\" {$disabled}
                        name=\"whitelist_setting[]\" {$checked}/>&nbsp;";
	            echo "<span>{$vkey}</span><br/>";
	        }
	        
	        echo "</label>";
	        echo "<br/>";
	    }
	}

	/*-------------------------------------------------------------------------
	* @function_name: insertActivity
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
   function getActivity(){
       $rtn = array();
       
		$userAccount 	= $this -> userAccount;
		$rs 			= $this -> getRowData($this -> getAccountCommon($userAccount));
		
		$details 		= array();
		$type 			= $this -> getType();
		$newUserName 	= $this -> userName;
		$newIpAddress   = $this -> ipAddress;
		$newPassword 	= $this -> password;
		$newPayload     = $this -> getWhitelistSettingPayload();
			
		$lastName 		= $this -> getColumnData($rs, COLUMN_LAST_NAME);
		$firstName 		= $this -> getColumnData($rs, COLUMN_FIRST_NAME);
		$row 		 	= $this -> getRowData($this -> accessSelect('SELECT_API_SIGNATURE_BY_A_ID', array($this -> aId)));
		
		if(count($row) > 0){
		    $id 			= $this -> getColumnData($row, COLUMN_A_ID);
		    $oldUserName 	= $this -> getColumnData($row, COLUMN_USER_NAME);
		    $oldIpAddress 	= $this -> getColumnData($row, COLUMN_IP_ADDRESS);
		    $oldPassword 	= $this -> getColumnData($row, COLUMN_PASSWORD);
		    $oldPayload     = $this -> getColumnData($row, COLUMN_WHITELIST_SETTING);
		    
		    if($type == TYPE_SAVE){
		        if($oldUserName != $newUserName){
		            $details[] = " API username from [{$oldUserName}] to [{$newUserName}]";
		        }
		        
		        if($oldIpAddress != $newIpAddress){
		            $details[] = " IP address from [{$oldIpAddress}] to [{$newIpAddress}]";
		        }
		        
		        if($oldPassword != $newPassword){
		            $details[] = " password from [{$oldPassword}] to [{$newPassword}]";
		        }
		        
		        if($oldPayload != $newPayload){
		            $oldsets = (array) json_decode($oldPayload);
		            $newsets = (array) json_decode($newPayload);
		            
		            foreach(array_keys($oldsets) as $key){
		                if(isset($oldsets[$key]) && isset($newsets[$key])){
    		                if($oldsets[$key] != $newsets[$key]){
    		                    $oldb = $oldsets[$key] ? "true" : "false";
    		                    $newb = $newsets[$key] ? "true" : "false";
    		                    
    		                    $details[] = " Updated {$key} from [{$oldb}] to [{$newb}]";
    		                }
		                }
		            }
		        }
		        
		        if($details != NULL){
		            $message = "Edited {$userAccount} {$lastName} {$firstName}'s <br/> ". implode(', <br/>', $details);
		        }else{
		            $message = "Saved without any changes";
		        }
		    }elseif ($type == TYPE_DELETE){
		        $message = "Deleted an API Signature [AID: {$id}][Account No: {$userAccount}][Username: {$oldUserName}][IP Address: {$oldIpAddress}]";
		    }elseif ($type == TYPE_COMPLETE) {
		        $message = "Created an API Signature for [{$userAccount}]";
		    }
		    		    
		    $rtn = [
		         $this -> getAdminUserData(PARAM_UID),
		         $_SERVER[PARAM_REMOTE_ADDR],
		         $_SERVER[PARAM_HTTP_USER_AGENT],
		         17,
		         date("Y-m-d H:i:s"),
		         $message
		    ];
		}
		
		return $rtn;
	}
}
?>