<?php
class AccountDuplicateComModelClass extends ModelClassEx {

	/*-------------------------------------------------------------------------
	* @ メンバ変数
	-------------------------------------------------------------------------*/
	private $rs 			= null;
	private $Mail			= NO_STRING;
	private $accountNumber	= NO_STRING;	// 口座番号
	private $lastName		= NO_STRING;	// 姓
	private $firstName		= NO_STRING;	// 名
	private $status			= NO_STRING;	// 状態
	private $birth			= NO_STRING;
	private $accountType 	= NO_STRING;
	private $country		= NO_STRING;	// 国
	private $address		= NO_STRING;	// 番地1
	private $loginFrom		= NO_STRING;	// 開始日（最終ログイン日）
	private $loginTo		= NO_STRING;	// 終了日（最終ログイン日）
	private $closeFrom		= NO_STRING;	// 開始日（口座閉鎖日）
	private $closeTo		= NO_STRING;	// 終了日（口座閉鎖日）
	private $loginFlg		= NO_STRING;	// ログイン日検索フラグ
	private $closeFlg		= NO_STRING;	// 閉鎖日検索フラグ
	private $arrValidate	= array();
	private $createTime     = NO_STRING;

	//search parameters
	private $sMail			= NO_STRING;
	private $sAccountNumber	= NO_STRING;
	private $sName 			= NO_STRING;
	private $sDOB			= NO_STRING;
	private $sAccountStatus = NO_STRING;
	private $sAddress		= NO_STRING;
	private $ipAddress      = NO_STRING;
	
	
	/**
	 *
	 * anton
	 *
	 */
	private $lang					= NO_STRING;
	private $cAccountNumber			= NO_STRING;
	private $sort                   = NO_STRING;
	
	/*-------------------------------------------------------------------------
	* @function_name: コントロールパネルシステムindexモデルクラスコンストラクタ
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function __construct() {
		// スーパークラスコンストラクタ呼び出し
		parent::__construct();
	}

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

		try {

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

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

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

	/*-------------------------------------------------------------------------
	* @function_name: パラメータの設定
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function setParameter() {
		$this -> sAccountNumber				=	(!empty($this -> getDataPost(PARAM_USER_ACCOUNT)) ? $this -> getDataPost(PARAM_USER_ACCOUNT)
				: $this -> getDataGet(PARAM_USER_ACCOUNT));
		
		$this -> sMail						= 	$this -> getDataPost(PARAM_EMAIL);
		$this -> sName 						= 	$this -> getDataPost(PARAM_NAME);
		$this -> sDOB						=	$this -> getDataPost(PARAM_BIRTH);
		$this -> sAccountStatus				=	$this -> getDataPost(PARAM_ACCOUNT_STATUS);
		$this -> cAccountNumber				= 	$this -> getDataPost("child_account"); // 5055 (ed)
		$this -> sAddress					= 	$this -> getDataPost(PARAM_ADDRESS);
		$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('PDAC', array(''))){
		 	$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_PAGE_ACCESS', array());
		 	header('Location: /'.$redirect.'menu');
		 	exit();
		 }

		return $rtn;
	}

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

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

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

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

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

			$listCount	= count($this -> rs);
			$start		= ($this -> getTargetPage() - VAL_INT_1) * VAR_DEFAULT_PAGE_COUNT;
			$end		= $this -> getTargetPage() * VAR_DEFAULT_PAGE_COUNT;
			
			for($cnt = $start; $cnt < $end && $cnt < $listCount; $cnt++) {

				$row = $this -> getRowData($this -> rs, $cnt);
				$rtn .= '<tr>'
						. '<td>' . $this -> getColumnData($row, COLUMN_MAIL) . '</td>'
						. '<td> <a href="account_edit?detail_account=' . $this -> getColumnData($row, COLUMN_USER_ACCOUNT) . '">'. $this -> getColumnData($row, COLUMN_USER_ACCOUNT) .'</a></td>'
						. '<td>' . $this -> getColumnData($row, COLUMN_LAST_NAME) . '&nbsp;' . $this -> getColumnData($row, COLUMN_FIRST_NAME) . '</td>'
						. '<td>' . $this -> dispKYCStatusCommon($this -> getColumnData($row, COLUMN_KYC_STATUS)) . '</td>'
						. '<td>' . date("Y-m-d", strtotime($this -> getColumnData($row, COLUMN_BIRTH))) . '</td>'
						. '<td>' . $this -> dispUserStatusCommon($this -> getColumnData($row, COLUMN_STATUS)) . '</td>'
						// . '<td>' . $this -> dispCountryCommon($this -> getColumnData($row , COLUMN_COUNTRY)) . '</td>'
						. '<td>' . $this -> getColumnData($row, COLUMN_ADDRESS) . '</td>'
						//. '<td>' . $this -> getColumnData($row, COLUMN_CREATE_TIME) . '</td>'
						// . '<td>' . $this -> getColumnData($row, COLUMN_CLOSE_TIME) . '</td>'
						. '<td>' . $this -> getColumnData($row, COLUMN_USER_THRESHOLD) . '</td>'
						//. '<td class="blocka"><a href="javascript:actionDelete(\'' . $this -> getColumnData($row, COLUMN_F_ID) . '\');"><span class="fa fa-trash fa-lg"></span></a></td>'
						. '</tr>';
			}

		} else {
			$rtn = '<tr><td colspan="16">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}

		echo $rtn;
	}
	
	/**
	 * 
	 * anton
	 * 
	 */
	public function echoJson(){		  
		$result = json_decode($this -> dupjson);
		
		$rtn = NO_STRING;
		
		if(count($result) > 0){
		    // foreach($result as $k => $v)
		    
		    $start		= ($this -> getTargetPage() - VAL_INT_1) * VAR_DEFAULT_PAGE_COUNT;
		    $end		= $this -> getTargetPage() * VAR_DEFAULT_PAGE_COUNT;
		    
		    // $cnt = $start; $cnt < $end && $cnt < $listCount; $cnt++
		    
		    
		    
		    for($k = $start; $k < $end && count($result); $k++){
		        if(!isset($result[$k])) continue;
		  
		        $v = $result[$k];
		        
		        $reasonDesc = NO_STRING;
                $v->reason = (Array) $v->reason;
		        
		        if(count($v->reason) > 0){
		            foreach($v->reason as $kr => $rfound){
		                $this -> appendReasons($reasonDesc, $kr, $rfound);
		            }
		        }else
		            $reasonDesc = VAL_STR_NO_MATCHES_FOUND;
		        
				$rtn .= '<tr>'
						. '<td>' . $v->emailAddress. '</td>'
						. '<td> <a href="account_edit?detail_account=' . $v->accountNo . '">'. $v->accountNo .'</a></td>'
						. '<td>' . $v->lastName . '&nbsp;' . $v->firstName . '</td>'
						. '<td>' . $v->dateOfBirth . '</td>'
						. '<td>' . $this -> dispUserStatusCommon($v->status) . '</td>'
						// . '<td>' . $this -> dispCountryCommon($this -> getColumnData($row , COLUMN_COUNTRY)) . '</td>'
						. '<td>' . $v->homeAddress . '</td>'
						. '<td>' . $v->ipAddress . '</td>'
						. '<td>' . $this -> dispCountryCommon($v->country) . '</td>'
						. '<td><a href="#" class="reason-data" reason-id="'.$k.'"><span style="display:none;" id="reason_'.$k.'">'.$reasonDesc.'</span>' .VAL_STR_CLICK_HERE. '</a></td>'
						//. '<td>' . $this -> getColumnData($row, COLUMN_CREATE_TIME) . '</td>'
						// . '<td>' . $this -> getColumnData($row, COLUMN_CLOSE_TIME) . '</td>'
						. '<td>' . $v -> threshold . '</td>'
						. '<td class="blocka"><a href="javascript:actionDeleteChildDuplicate(\'' . $this -> sAccountNumber . '\', \''
								    .$v->accountNo.'\');"><span class="fa fa-trash fa-lg"></span></a></td>'
					. '</tr>';
			}
		}else{
			$rtn = '<tr><td colspan="16">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}
		
		echo $rtn;
	}
	
	/**
	 * 
	 * anton
	 * 
	 * @param unknown $reasonDesc
	 * @desc echoJson helper
	 * 
	 */
	private function appendReasons(&$reasonDesc, $kr, $rfound){
	    $reasonDesc .= "<b>[{$kr}]</b><br/>";
	    if(is_object($rfound)){
	        $reasonDesc .= "Input: {$rfound->focus}<br/>";
	        if(isset($rfound->result)){
	            if($kr == "RandomChecking")
	                $reasonDesc .= "{$rfound->description}<br/>";
	                $reasonDesc .= "Reference: {$this -> highlightMatches($rfound)}<br/><br/>";
	        }else
	            $reasonDesc .= "Reference: <b>{$rfound->focus}</b><br/><br/>";
	    }
	}
	
	/**
	 * anton
	 * 
	 * @param unknown $element
	 * @return string
	 */
	private function highlightMatches($element){
	    $combination = "";
	    
	    $commons = (Array) $element->result->commons;
	    
	    usort($commons, function($a, $b){
	        return $a->sourceIndex - $b->sourceIndex;
	    });
	        
	    $startsWith = 0;
	    
	    foreach($commons as $k => $obj){
	        if($k === 0 && $obj->sourceIndex > 0){
	            $combination .= substr($element->reference, 0, $obj->sourceIndex);
	        }
	        
	        $nextIndex = 0;
	        
	        if(isset($commons[$k + 1])){
	            $nextIndex = $commons[$k + 1]->sourceIndex;
	        }
	        
	        $startsWith = $obj->sourceIndex + strlen($obj->phrase);
	        
	        $data = [
	            "phrase" => substr($element->reference, $obj->sourceIndex, strlen($obj->phrase)),
	            "remaining" => substr($element->reference, $startsWith, $nextIndex - $startsWith),
	        ];
	        
	        $combination .= "<b>{$data["phrase"]}</b>{$data["remaining"]}";
	        $startsWith = $obj->sourceIndex + strlen($obj->phrase);
	    }
	    
	    if($startsWith < strlen($element->reference)){
	        $combination .= substr($element->reference, $startsWith);
	    }
	    
	    return $combination;
	}
	
	/**
	 * DN053
	 */
	public function echoCount(){
	    echo count(json_decode($this -> dupjson));
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: 一覧データの設定
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function setResult($rs) {
		$this -> rs = $rs;
	}
/*-------------------------------------------------------------------------
	* @function_name: 口座状態の表示
	* @parameter	: なし
	* @return		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	function dispStatuses() {
		// 変数宣言部
		$rtn		= NO_STRING;
		$sStatus	= array();
		$checked	= array();

		// 口座状態リストの取得
		$sStatus = $this -> getStatusList();

		// チェックリストの作成（デフォルト全取得）
		if(!is_array($this -> sStatus)) {
			if($this -> getType() == NO_STRING) {
				if($this -> isLoopData($sStatus)) {
					foreach($sStatus as $row)
						$checked[$this -> getColumnData($row, PARAM_DATA_KEY)] = $this -> getColumnData($row, PARAM_DATA_KEY);
				}
			}
		} else {
			foreach($this -> sStatus as $row)
				$checked[$row] = $row;
		}

		if($this -> isLoopData($sStatus)) {
			foreach($sStatus as $row)
				$rtn .= '<label>' . $this -> makeCheckOne(PARAM_STATUSES . $row[PARAM_DATA_KEY], PARAM_STATUSES . '[]', $row[PARAM_DATA_KEY], $row[PARAM_DATA_VALUE] , $this -> getColumnData($checked, $row[PARAM_DATA_KEY])) . '</label>&emsp;';
		}

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

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

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

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

		// メールアドレス
		if($this -> sMail != NO_STRING) {
			$where .= ' AND mail LIKE (\')%' . $this -> sMail . '%(\')';
		}

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

		$page = ' LIMIT ' . $start . DELIMIT_COMMA . VAL_INT_50;

		//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		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	function dispOpenFlg() {
		echo '<label>'
				. $this -> makeCheckOne(PARAM_DATE_TAGGED
											, PARAM_DATE_TAGGED
											, VAL_INT_1
											, NO_STRING, $this -> sDateTagged)
				. '</label>';
	}

	function restore(){
		$acc = $this -> getAccountCommon($this -> sAccountNumber);
		
		$this -> sName            = "{$this -> getColumnData($acc[0], COLUMN_FIRST_NAME)} {$this -> getColumnData($acc[0], COLUMN_LAST_NAME)}";
		$this -> sMail            = $this -> getColumnData($acc[0], COLUMN_MAIL);
		$this -> sDOB             = date("Y-m-d", strtotime($this -> getColumnData($acc[0], COLUMN_BIRTH)));
		$this -> sAccountStatus   = $this -> dispUserStatusCommon($this -> getColumnData($acc[0], COLUMN_STATUS));
		$this -> sAddress         = $this -> getColumnData($acc[0], COLUMN_ADDRESS);
		$this -> ipAddress        = $this -> getColumnData($acc[0], "create_ip_address");
		$this -> dupjson          = $this -> getColumnData($acc[0], COLUMN_DUPLICATE_SOURCE);
		$this -> country          = $this -> dispCountryCommon($this -> getColumnData($acc[0], COLUMN_COUNTRY));
		$this -> createTime       = $this -> getColumnData($acc[0], COLUMN_CREATE_TIME);
	}
	
	public function setDupJson($dupjson){
		$this -> dupjson = $dupjson;
	}
	
	/**
	 * (ed)
	 * @return string|unknown
	 */
	public function getDupJson(){
		return $this -> dupjson;
	}
	
	/**
	 * (ed)
	 * @return string|unknown
	 */
	public function getChildAccount(){
		return $this -> cAccountNumber;	
	}
	
	/**
	 * 
	 * @return string|unknown
	 */
	public function getUserAccount(){
		return $this -> sAccountNumber;	
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function echoTagFrom() {
		echo $this -> sTagFrom;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function echoTagTo() {
		echo $this -> sTagTo;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function echoName() {
		echo $this -> sName;
	}

	/*-------------------------------------------------------------------------
	 * @function_name:
	 * @parameter	:
	 * @return		:
	 -------------------------------------------------------------------------*/
	function echoIPAddress() {
	    echo $this -> ipAddress;
	}
	
	/*-------------------------------------------------------------------------
	 * @function_name:
	 * @parameter	:
	 * @return		:
	 -------------------------------------------------------------------------*/
	function echoCountry() {
	    echo $this -> country;
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: 口座番号の表示
	* @parameter	: なし
	* @return		: 口座番号
	-------------------------------------------------------------------------*/
	function echoAccountNumber() {
		echo $this -> sAccountNumber;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function echoMail() {
		echo $this -> sMail;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function echoBirth() {
		echo $this -> sDOB;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function echoAccountStatus() {
		echo $this -> sAccountStatus;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function echoAddress() {
		echo $this -> sAddress;
	}
	
	/*-------------------------------------------------------------------------
	 * @function_name:
	 * @parameter	:
	 * @return		:
	 -------------------------------------------------------------------------*/
	function echoCreateTime() {
	    echo $this -> createTime;
	}

	/*-------------------------------------------------------------------------
	* @function_name: makeExportData()
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	function makeExportData(){

		
		
		$data = ($this -> lang == "en" ?  "Email Address,Account Number,Name,Date of Birth,Review Status, Address, Date of Account Opening, Threshold\n" 
				: 'メールアドレス,口座番号,名前,生年月日,審査状況,住所,開設日,しきい値' . "\n"); 

		$result = json_decode($this -> dupjson);
		
		if($this -> isLoopData($result)){

			foreach($result as $v){
				$row = (array) $v;
				$arr = array();

				$arr[] = $this -> getColumnData($row, COLUMN_MAIL);	
				$arr[] = $this -> getColumnData($row, COLUMN_USER_ACCOUNT);	
				$arr[] = $this -> getColumnData($row, COLUMN_LAST_NAME) .' '.  $this -> getColumnData($row, COLUMN_FIRST_NAME);				
				/* $arr[] = $this -> getColumnData($row, COLUMN_VALIDATE_STATUS); */					
				$arr[] = $this -> getColumnData($row, COLUMN_BIRTH);					
				$arr[] = $this -> getColumnData($row, COLUMN_STATUS);							
				/* $arr[] = $this -> getColumnData($row, COLUMN_COUNTRY); */		
				$arr[] = $this -> getColumnData($row, COLUMN_ADDRESS);			
				$arr[] = $this -> getColumnData($row, COLUMN_CREATE_TIME_STRING);			
				/* $arr[] = $this -> getColumnData($row, COLUMN_CLOSE_TIME); */			
				$arr[] = $this -> getColumnData($row, COLUMN_USER_THRESHOLD);					

                $data .= '"'. implode('"' . DELIMIT_COMMA . '"', $arr) . '"' . "\n";

			}

		}

		$this -> setExportDataCommon($data);
	}

}
?>