<?php
require_once(SYSTEM_LOGICS . 'account_edit/model.php');

class LogicAccountEdit extends AccountEditModelClass {

	/*-------------------------------------------------------------------------
	* @ メンバ変数
	-------------------------------------------------------------------------*/
	private $htmlStr = NO_STRING;	// 表示用HTML文字列
	
	/*-------------------------------------------------------------------------
	 * @function_name: ロジックのコンストラクタ
	 * @parameter	: なし
	 * @return		: なし
	 -------------------------------------------------------------------------*/
	function __construct() {
		parent::__construct();
	}
	
	/*-------------------------------------------------------------------------
	 * @function_name: ロジック（各クラス共通）
	 * @parameter	: なし
	 * @return		: TRUE:ロジック成功、FALSE:ロジック失敗
	 -------------------------------------------------------------------------*/
	function logic() {
		
		try {
			
			// 初期データ処理
			$this -> init();
			
			if($this -> getType()		== CONTROL_ACTION
					|| $this -> getType()	== TYPE_SEARCH
					|| $this -> getType()	== NO_STRING) {			// データの詳細
						$this -> select();
						$this -> selectLogin();
						if($this -> getType()	== NO_STRING){
							$this -> insertActivity();
						}
						//获取2faenable
						$this -> set2fa(true);
			} else if($this -> getType() == TYPE_INPUT
					|| $this -> getType() == TYPE_INPUT_ACCESS) {		// データの入力
						$this -> select();
						$this -> selectLogin();
						//获取2faenable
						$this -> set2fa(true);
			} else if($this -> getType() == TYPE_COMPLETE) {	// データの更新
				//判断是否有修改个人和法人修改二次认证code的状态
				$this -> insertActivity();
				$this -> exchangeAccount();
				$this -> update();
				$this -> select();
				$this -> selectLogin();
				$this -> update2fa();
				$this -> set2fa(true);
			} else if($this -> getType() == TYPE_SAVE) {		// ユーザメモの更新
				if($this -> checkChiket()) {
					$this -> popUpSessionMessage(INFO, 'I_COMPLATE_SAVE', array());
				}
				$this -> updateNote();
				$this -> select();
				$this -> selectLogin();
				$this -> insertActivity();
				
			} else if($this -> getType() == TYPE_SAVE_RISK) {		// ユーザメモの更新
				if($this -> checkChiket()) {
						$this -> popUpSessionMessage(INFO, 'I_COMPLATE_SAVE', array());
				}
				$this -> updateRisk();
				$this -> select();
				$this -> selectLogin();
				$this -> insertActivity();
			} else if($this -> getType() == TYPE_SAVE_ACCESS) {		// ユーザメモの更新
				$this -> updatePaymentAccess();
				$this -> select();
				$this -> selectLogin();
				$this -> setType('');
			} else if($this -> getType() == TYPE_DELETE) {		// ユーザの削除（論理）
				$this -> delete();

			} else if($this -> getType() == TYPE_ROLL_BACK) {	// KYC書類確認の差戻し

				$this -> rollBack();
				$this -> select();
				$this -> selectLogin();

			} else if($this -> getType() == TYPE_UNLOCK) {		// ユーザのログイン状態解除

				$this -> select();
				$this -> unlock();
				$this -> selectLogin();

			} else if($this -> getType() == TYPE_SEND) {		// 認証メールの再送信
				$this -> reSend();
				$this -> select();
				$this -> selectLogin();

			} else if($this -> getType() == TYPE_CARD) {		// カードの登録
				$this -> registCard();
				$this -> clear();
				$this -> select();
				$this -> selectLogin();
				// Mikko 2019 start
			} else if($this -> getType() == TYPE_LINK_ACCOUNT) {		
				$this -> linkAccount();
				$this -> clear();
				$this -> select();
				$this -> selectLogin();

			} else if($this -> getType() == TYPE_REMOVE_LINK) {		
				$this -> removeLink();
				$this -> select();
				$this -> selectLogin();
				// Mikko 2019 end
			} else if($this -> getType() == TYPE_REMOVE_CARD) {	// カードの削除
				$this -> remove();
				$this -> select();
				$this -> selectLogin();
			} else if($this -> getType() == TYPE_ADMIN_KYC_UPLOAD) {	// KYC登録
				$this -> select();
			} else if($this -> getType() == TYPE_ADMIN_KYC_UPLOAD_COMPLETE) {	// KYC登録完了
				$this -> select();
				if($this -> getAccountType()	== VAR_PERSON){		//KYC登録（個人）

					$this -> loadImageKycPerson();				
					$this -> updateKycValidateStatus();
				}
				if($this -> getAccountType()	== VAR_CORP){		// KYC登録（法人）
					
					$this -> loadImageKycCorp();
					$this -> updateKycValidateStatus();
				}
				$this -> setType(TYPE_COMPLETE);
			} 

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

	/*-------------------------------------------------------------------------
	* @function_name: 詳細の取得
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function selectPaging() {
		$crntPage = $this -> getCrntPage();
		$offset = 50 * ($crntPage - 1);
		$this -> lists(1, $offset);
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: 詳細の取得
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function selectExport() {
		// 通貨情報
		$this -> setCurrencies($this -> accessSelect('LIST_MST_CURRENCY_ACTIVE', array()));
		$this -> lists(0, 0);
	}

	/*-------------------------------------------------------------------------
	* @function_name: 一覧の取得
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function lists($limitType, $offset) {
		// modified mark
		$condition = $this -> getCondition();

		if(!$this -> getCurrencies()) {
			$this -> setCurrencies($this -> accessSelect('LIST_MST_CURRENCY_ACTIVE', array()));
		}

		//check for currency with transactions
		$availableCurrencies = $this -> accessSelect('LIST_USER_TRANSACTION_ADMIN_COUNT_REVISED', $condition);

		//if anything found
		if($availableCurrencies) {
			$currencies = array();

			//will get supported currency in db
			if($this -> getCurrencies()) {
				foreach($this -> getCurrencies() as $row) {
					$currencies[] = $this -> getColumnData($row, COLUMN_CURRENCY_NAME);
				}
			}

			//will fetch all supported currency in db
			if($currencies) {
				$sorted = array();

				foreach($currencies as $key => $value) {
					foreach($availableCurrencies as $c) {
						if($c['currency'] == $value) {
							array_push($sorted, $c);
						}
					}
				}

				foreach($sorted as $c) {
					if(!$this->getSCurrency()) {
						//if currency with transactiom matches the supported currencies in db
						if(in_array($c['currency'], $currencies)) {
							$currency = $c['currency'];

							$where = $this -> getWhere($currency);

							if ($limitType) {
								$where[] = ' LIMIT 50 OFFSET ' . $offset;
							} else {
								$where[] = NO_STRING;
							}

							$this -> setHistoryCount($c['currency'], $c['total']);
							$data = $this -> accessSelect('LIST_USER_TRANSACTION_ADMIN', $where);

							$this -> setHistory($currency, $data, $c['total']);
						}
					} else {
						if($c['currency'] == $this->getSCurrency()) {
							$currency = $c['currency'];

							$where = $this -> getWhere($currency);

							if ($limitType) {
								$where[] = ' LIMIT 50 OFFSET ' . $offset;
							} else {
								$where[] = NO_STRING;
							}

							if($this->getSCurrency()) {
								$this -> setHistoryCount($this->getSCurrency(), $c['total']);
							} else {
								$this -> setHistoryCount($c['currency'], $c['total']);
							}

							$data = $this -> accessSelect('LIST_USER_TRANSACTION_ADMIN', $where);
							$this -> setHistory($currency, $data, $c['total']);
						}
					}
				}
			}
		}
		// end modified mark

		// $ccy = $this -> getSCurrency();

		// $currencies = array();
		// if (empty($ccy)) {
		// 	foreach($this -> getCurrencies() as $row) {
		// 		$currencies[] = $this -> getColumnData($row, COLUMN_CURRENCY_NAME);
		// 	}
		// } else {
		// 	$currencies = explode(',', $ccy);
		// }
		// foreach($currencies as $currency) {
		// 	// 履歴情報
		// 	$where	= $this -> getWhere($currency);
		// 	$countData = $this -> accessSelect('LIST_USER_TRANSACTION_ADMIN_COUNT', $where);
		// 	$count = 0;
		// 	foreach($countData as $countRow) {
		// 		$count = $countRow['total'];
		// 		break;
		// 	}
		// 	if ($limitType) {
		// 		$where[] = ' LIMIT 20 OFFSET ' . $offset;
		// 	} else {
		// 		$where[] = NO_STRING;
		// 	}
		// 	$data = $this -> accessSelect('LIST_USER_TRANSACTION_ADMIN', $where);
		// 	$this -> setHistory($currency, $data, $count);
		// }
	}

	/*-------------------------------------------------------------------------
	* @function_name: 詳細の取得
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function select() {

		// データの取得
		$this -> setUserDetail($this -> getAccountCommon($this -> getDetailAccount()));

		// データの再設定
		$this -> restore();

		// バランスの取得
		$this -> setBalances($this -> accessSelect('SELECT_USER_BALANCES', array($this -> getDetailAccount())));

		// 通貨情報
		$this -> setCurrencies($this -> accessSelect('LIST_MST_CURRENCY_ACTIVE', array()));

		// カード情報
		$this -> setCards($this -> accessSelect('LIST_USER_CARDS', array($this -> getDetailAccount())));

		// Mikko 2019 0103 start
		$this -> setLinkUser($this -> accessSelect('SELECT_USER_LINK', array($this -> getDetailAccount())));
		
	}

	/*-------------------------------------------------------------------------
	* @function_name: ログイン状態の取得
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function selectLogin() {

		// ログイン状態の取得
		$this -> setLoginLock($this -> accessSelect('SELECT_LOGIN_FAIL', array($this -> getUserName())));
	}

	/*-------------------------------------------------------------------------
	* @function_name: ログインロックの解除
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function unlock() {

		// ログイン成功で回数をリセット
		$this -> clearFailCounter($this -> getUserName());
	}

	/*-------------------------------------------------------------------------
	* @function_name: 詳細の更新
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function update() {

		// 変数宣言部
		$pow	= NO_STRING;
		$kinds	= null;


		//if status is 6 or 7 to 3, update last lifted date
		$res = $this -> getRowData($this -> accessSelect('SELECT_USER_STATUS', array($this -> getDetailAccount())));
		$currStatus = $this -> getColumnData($res, 'status');

		if($currStatus == VAL_INT_7 || $currStatus == VAL_INT_6 || $currStatus == VAL_INT_4){
			if($this -> getStatus() == VAL_INT_3){
				$this -> accessModify('UPDATE_USER_LIFT_DATE', array($this -> getDetailAccount()), false);		//update lift_date
			}
		}
		// データの更新
		$this -> accessModify('UPDATE_USER', $this -> getUpdateDatas(),false);

// 		$this -> accessModify('UPDATE_LOGIN_USER_NAME', $params);	// ログインテーブル更新

		// 手数料の更新（手数料が発生した場合のみ）
		if($this -> isLoopData($this -> getFees())) {

			foreach($this -> getFees() as $currency => $amount) {

				$this -> registFeeCommon($this -> getDetailAccount()
										, $currency
										, $amount);
			}
		}

		// 所属WLの更新
		$this -> accessModify('UPDATE_USER_WL_ID', $this -> getUpdateWlIdDatas(), false);

		// 法人の場合は法人データも更新する
		if($this -> getAccountType() == VAR_CORP) {

			$param = $this -> getUpdateCorporationDatas();

			$this -> accessModify('DELETE_CORPORATION', $param, false);

			$this -> accessModify('INSERT_CORPORATION_ADMIN', $param, false);
		}

		// ステータスが閉鎖の場合は日時更新
		if($currStatus != VAL_INT_5){
			if($this -> getStatus() == VAL_INT_5) {
				$this -> accessModify('UPDATE_USER_CLOSE_DATE', array($this -> getDetailAccount()), false);							// 閉鎖日時更新
			}
		}


		// Update latest date of suspension
		if($currStatus != VAL_INT_7 && $currStatus != VAL_INT_6 && $currStatus != VAL_INT_4){
			if($this -> getStatus() == VAL_INT_4
				|| $this -> getStatus() == VAL_INT_6
				|| $this -> getStatus() == VAL_INT_7) {
				$this -> accessModify('UPDATE_USER_SUSPENDED_DATE', array($this -> getDetailAccount()), false);							// 閉鎖日時更新
			}
		}

		// ステータスが「閉鎖」「休止」の場合はバッチステータスを「不許可へ」
		if($this -> getStatus() == VAL_INT_4
			|| $this -> getStatus() == VAL_INT_6
			|| $this -> getStatus() == VAL_INT_7
			|| $this -> getStatus() == VAL_INT_5) {
			$this -> accessModify('UPDATE_USER_TRANSFER_BATCH_FLG', array($this -> getDetailAccount(), VAR_FLG_OFF), false);	// バッチフラグの不許可
		}

		// GPSデータの更新

		// 決済種別の作成
		$pow = '0000000000';

		$kinds = $this -> getGpsKindOfPayments();
		if($this -> isLoopData($kinds)) {


			foreach($kinds as $kind) {

				if($kind == PARAM_GPS_VISA) {							// VISAフラグが立った場合
					$pow = substr_replace($pow, VAL_INT_1, NO_COUNT, VAL_INT_1);
				} else if($kind == PARAM_GPS_GIFTCARD) {				// MASTERCARDフラグが立った場合
					$pow = substr_replace($pow, VAL_INT_1, VAL_INT_1, VAL_INT_1);
				} else if($kind == PARAM_GPS_VAL_INSTANTBANKTRANSFER) {	// 銀行送金フラグが立った場合
					$pow = substr_replace($pow, VAL_INT_1, VAL_INT_2, VAL_INT_1);
				} else if($kind == VAL_STR_CUP_NAME) {	// China Union Payフラグが立った場合
					$pow = substr_replace($pow, VAL_INT_1, VAL_INT_3, VAL_INT_1);
				} else if($kind == VAL_STR_VSMS_NAME) {	// Visa/Mastercard Directフラグが立った場合
					$pow = substr_replace($pow, VAL_INT_1, VAL_INT_4, VAL_INT_1);
				}
			}
		}

		// GPSデータを更新する
		$this -> accessModify('UPDATE_USER_GPS', array($this -> getDetailAccount(), $this -> getGPSAccountFlg(), $pow), false);

		$this -> popUpSessionMessage(INFO, 'I_COMPLATE_REGIST', array());
	}

	/*-------------------------------------------------------------------------
	* @function_name: ユーザの削除
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function delete() {
		$this -> accessModify('UPDATE_USER_DELETE', $this -> getUpdateUserDeleteDatas(), false);
	}

	/*-------------------------------------------------------------------------
	* @function_name: 詳細の更新
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function updateNote() {
		$this -> accessModify('UPDATE_USER_NOTE', $this -> getUpdateUserNoteDatas(), false);
	}
	function updateRisk() {
		$this -> accessModify('UPDATE_USER_RISK', $this -> getUpdateUserRiskDatas(), false);
	}

	/*-------------------------------------------------------------------------
	* @function_name: KYC書類の再確認を行う
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function rollBack() {
		$this -> accessModify('UPDATE_KYC_ROLL_BACK', array($this -> getDetailAccount()), false);
		$this -> popUpSessionMessage(INFO, 'I_COMPLATE_REGIST', array());
	}

	/*-------------------------------------------------------------------------
	* @function_name: 認証コードの再送信を行う
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function reSend() {

		$this -> sendRegistMailCommon($this -> getDetailAccount());

		// データの時間更新
		$this -> accessModify('UPDATE_VERI_DATE', array($this -> getDetailAccount()), false);

		$this -> popUpSessionMessage(INFO, 'I_COMPLETE_SEND_EMAIL', array());
	}

	/*-------------------------------------------------------------------------
	* @function_name: カードの登録
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function registCard() {
		$this -> accessModify('INSERT_USER_CARDS', $this -> getRegistCardDatas(),false);
	}


	/*-------------------------------------------------------------------------
	* @function_name: Link account //Mikko 2019
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function linkAccount() {
		$this -> accessModify('INSERT_USER_LINK', $this -> getUserLinkDatas(),false);
	}

	/*-------------------------------------------------------------------------
	* @function_name: 認証コードの再送信を行う
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function remove() {
		$this -> accessModify('DELETE_USER_CARDS', $this -> getDeleteCardDatas(),false);
	}

	/*------------------------Mikko 2019---------------------------------------
	* @function_name:Delete link
	* @parameter	:
	* @return		:
	-------------------------------------------------------------------------*/
	function removeLink() {
		$this -> accessModify('DELETE_USER_LINK', $this -> getDeleteUserLinkDatas(),false);
	}

	/*-------------------------------------------------------------------------
	* @function_name: パスワードの更新
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function updateKycValidateStatus() {
		$date = date("Y-m-d H:i:s");
		$this -> accessModifyCommon('UPDATE_USER_VALIDATE_STATUS', array( $date,$this->getDetailAccount()));

	}

	/*-------------------------------------------------------------------------
	* @function_name: 2fa更新
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function update2fa(){
		if ($this -> get2faAccount()) {
			$param = $this -> set2fa(false);
			if($param[3] == VAL_INT_1){
				//更新 sfa
				$this -> accessModify('UPDATE_2FA_ENABLE', $this -> get2faAll(), false);
				$this -> take2faChangeMail($param);
			}
		}
	}

	function updatePaymentAccess(){
		/*USER BYPASS SOLUTION ACCESS UPDATE START*/
		// if(!$this -> checkAdminUserAccess('PSCA', array('','1'))){
		// 	$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_FUNCTION_ACCESS', array());
		// }else{
			$newDepositAccess = $this -> getUserDepositBypassAccess();
			$newWithdrawAccess = $this -> getUserWithdrawBypassAccess();
			$currentDepositAccess = $this -> getUserBypassSolutionList(PARAM_DEPOSIT);
			$currentWithdrawAccess = $this -> getUserBypassSolutionList(PARAM_WITHDRAW);

			$commonDepositArray = array_intersect($newDepositAccess,$currentDepositAccess);
			$commonWithdrawArray = array_intersect($newWithdrawAccess,$currentWithdrawAccess);

			foreach($newDepositAccess as $val){
				if(!(in_array($val, $commonDepositArray))){
					$this -> accessModify('INSERT_USER_BYPASS_SOLUTION', $this -> getUpdateBypassAccessData(PARAM_DEPOSIT, $val), false);
				}
			}
			foreach($currentDepositAccess as $val){
				if(!(in_array($val, $commonDepositArray))){
					$this -> accessModify('DELETE_USER_BYPASS_SOLUTION', $this -> getUpdateBypassAccessData(PARAM_DEPOSIT, $val), false);
				}
			}

			foreach($newWithdrawAccess as $val){
				if(!(in_array($val, $commonWithdrawArray))){
					$this -> accessModify('INSERT_USER_BYPASS_SOLUTION', $this -> getUpdateBypassAccessData(PARAM_WITHDRAW, $val), false);
				}
			}
			foreach($currentWithdrawAccess as $val){
				if(!(in_array($val, $commonWithdrawArray))){
					$this -> accessModify('DELETE_USER_BYPASS_SOLUTION', $this -> getUpdateBypassAccessData(PARAM_WITHDRAW, $val), false);
				}
			}

			$this -> popUpSessionMessage(INFO, 'I_COMPLATE_REGIST', array());
		//}


		/*USER BYPASS SOLUTION ACCESS UPDATE END*/
	}
	/*-------------------------------------------------------------------------
	* @function_name: insertActivity
	* @parameter	:
	* @return		: 
	-------------------------------------------------------------------------*/
	function insertActivity(){
		$this -> accessModify('INSERT_ACTIVITY', $this -> getActivity(), false);
	}
}
?>
