<?php 

class ModelAccountTransactions extends ModelClassEx {
    
    private $detailAccount;
    
    private $sUserAccount;
    private $transactionType;
    private $transactionNumber;
    
    private $sEmail;
    
    private $from;
    private $to;
    
    private $currency;
    private $start;
    
    private $currencies;
    private $currencyTxnCounter;
    private $rs;
    
    private $lang;
    
    private $accountData;
    
    private $arrValidate;
    
    public function __construct(){
        parent::__construct();
    }
    
    public function init() {
        try {
            // パラメータの設定
            $this -> setParameter();
            
            // チェック
            $this -> validate(); 
        } catch (Exception $e) {
            throw new Exception(NO_STRING);
        }
    }
    
    private function setParameter(){
        $this -> detailAccount      = ($this -> getDataPost(PARAM_DETAIL_ACCOUNT) != NO_STRING) ?
                                            $this -> getDataPost(PARAM_DETAIL_ACCOUNT, true) : $this -> getDataGet(PARAM_DETAIL_ACCOUNT);	;
        $this -> transactionType    = $this -> getDataPost(PARAM_TRANSACTION_TYPE, true);
        $this -> transactionNumber  = $this -> getDataPost(PARAM_TRANSACTION_NUMBER, true);
        $this -> sUserAccount       = $this -> getDataPost(PARAM_S_ACCOUNT, true);
        $this -> sEmail             = $this -> getDataPost(PARAM_S_EMAIL);
        
        // GETがあったら、GETを入れる
        if($this -> getDataGet(PARAM_S_CURRENCY) != NO_STRING) {
            $this -> currency	= $this -> getDataGet(PARAM_S_CURRENCY, true);
        }
        
        // POSTがあったら、POSTを優先
        if($this -> getDataPost(PARAM_S_CURRENCY) != NO_STRING) {
            $this -> currency	= $this -> getDataPost(PARAM_S_CURRENCY, true);
        }
        
        // Fromの日付は確定させないとダメ
        if($this -> getDataPost(PARAM_S_FROM) == NO_STRING) {
            // $this -> from = date('Y/m/1', strtotime('-1 month'));
            $this -> from = date('Y/m/d', strtotime('-1 month'));
        } else {
            $this -> from		= $this -> getDataPost(PARAM_S_FROM, true);
        }
        
        $this -> to			 = $this -> getDataPost(PARAM_S_TO, true);
        $this -> lang        = $this -> getLangage();
        
        $this -> accountData = $this -> getColumnData($this -> getAccountCommon($this -> detailAccount), 0);
        
        $this -> initKYCValidationArray();
    }
    
    /*-------------------------------------------------------------------------
     * @function_name: サーバ側データチェック
     * @parameter	: なし
     * @return		: TRUE:成功、FALSE:失敗
     -------------------------------------------------------------------------*/
    public function validate() {
        // ログインチェック
        if(!$this -> checkAdminUserLogin()) {
            throw new Exception(NO_STRING);
        }
    }

    
    private function initKYCValidationArray(){
        $this -> arrValidate = [
            VAR_KYC_VALIDATE_STATUS_1,
            VAR_KYC_VALIDATE_STATUS_2,
            VAR_KYC_VALIDATE_STATUS_3,
            VAR_KYC_VALIDATE_STATUS_4,
            VAR_KYC_VALIDATE_STATUS_5,
            VAR_KYC_VALIDATE_STATUS_6,
            VAR_KYC_VALIDATE_STATUS_7,
            VAR_KYC_VALIDATE_STATUS_8,
            VAR_KYC_VALIDATE_STATUS_9,
            VAR_KYC_VALIDATE_STATUS_10,
            VAR_KYC_VALIDATE_STATUS_11,
            VAR_KYC_VALIDATE_STATUS_12,
            VAR_KYC_VALIDATE_STATUS_13,
            VAR_KYC_VALIDATE_STATUS_14,
            VAR_KYC_VALIDATE_STATUS_15,
            VAR_KYC_VALIDATE_STATUS_16,
            VAR_KYC_VALIDATE_STATUS_17,
            VAR_KYC_VALIDATE_STATUS_18,
            VAR_KYC_VALIDATE_STATUS_19,
            VAR_KYC_VALIDATE_STATUS_20,
        ];
    }
    
    private function createCurrencyTransactionsTable($cur){
        $displayLabel = VAL_STR_DISPLAY;
        $prevPage = VAL_STR_PREVIOUS_PAGE;
        $nextPage = VAL_STR_NEXT_PAGE;
        $searchResult = VAL_STR_SEARCH_RESULT;
        $accountHistory = VAL_STR_ACCOUNT_HISTORY;
        $elapsedTime = VAL_STR_ELAPSED_TIME;
        $seconds = VAL_STR_SECONDS;
        
        $titleData = '<tr>'
            . '<th class="w5p">&nbsp;</th>'
            . '<th class="w7p">'.VAL_STR_HEADER_TRANSACTION_TYPE.'</th>'
            . '<th class="w7p">'.VAL_STR_USER_ACCOUNT.'</th>'
            . '<th class="w10p">'.VAL_STR_USER_ACCOUNT_NAME.'</th>'
            . '<th class="w7p">'.VAL_DEPOSIT_AMOUNT.'</th>'
            . '<th class="w7p">'.VAL_WITHDRAWAL_AMOUNT.'</th>'
            . '<th class="w7p">'.VAL_STR_FEE.'</th>'
            . '<th class="w7p">'.VAL_STR_DATE_REQUESTED.'</th>'
            . '<th class="w7p">'.VAL_STR_PROCESSING_DATE.'</th>'
            . '<th class="w7p">'.VAL_STR_TRANSACTION_NUMBER.'</th>'
            . '<th class="w15p">'.VAL_STR_MESSAGE.'</th>'
            . '<th class="w7p">'.VAL_STR_TYPE.'</th>'
            . '<th class="w5p">'.VAL_STR_CURRENT_STATUS.'</th>'
            . '<th class="w7p">'.VAL_STR_HEADER_BALANCE.'</th>'
            . '</tr>';
        
        $html =<<<HTMLSTRING
        
        <div class="caption" data-toggle="collapse" href="#{$cur}" aria-expanded="true" aria-controls="$cur">
            <span>{$cur} {$accountHistory}</span><i class="icontop" aria-hidden="true"></i>
        </div>
        
        <div class="t_collapse_box collapse" id="{$cur}" aria-expanded="true">
            <div class="cur-table tbl_{$cur}">
                <input type="hidden" value="{$cur}"/>
                <table class="table col bdr default odd calign w100p fontXS">
                    <thead>
                       {$titleData}
                    </thead>
                    <tbody id="transaction_body_{$cur}">
                    </tbody>
                </table>
			</div>
			
			<div class="article-bottom mt-0">
                &nbsp;&nbsp;{$elapsedTime}: <span id="elapsed_time_{$cur}"></span> {$seconds}
      			<div class="pager"> {$searchResult} 
                    <span id="rowCount_{$cur}"></span>&nbsp;Page 
          			<span id="currentPageNum_{$cur}"></span> / <span id="pageTotal_{$cur}"></span>&nbsp;

          			<input id="move_page_high_{$cur}" class="px30 ralign" type="text">&nbsp;
          			<input id="express_{$cur}" value=" {$displayLabel} " class="btn bg-default px60 hi22" focused-cur="{$cur}" type="button"/>&nbsp;

          			<input id="prev_{$cur}" value=" {$prevPage} " class="btn2 bg-default px90 hi22" focused-cur="{$cur}" type="button"/>&nbsp;
          			<input id="next_{$cur}" value=" {$nextPage} " class="btn2 bg-default px90 hi22" focused-cur="{$cur}" type="button"/>&nbsp;

          			<input id="crnt_page_{$cur}" type="hidden">
                    <input id="total_page_{$cur}" type="hidden">
                </div>
   			</div>
		</div><br/>
HTMLSTRING;
        
        return $html;
    }
    
    public function echoTransactionTables(){ 
        if(empty($this -> currency)){
            if($this -> isLoopData($this -> currencyTxnCounter)){
                foreach($this -> currencyTxnCounter as $counter){                    
                    echo $this -> createCurrencyTransactionsTable($counter["currency"]);
                }
            }
        }else
            echo $this -> createCurrencyTransactionsTable($this -> currency);
    }
    
    public function echoJavascriptLabels(){
        $labels = [
            "progressIndicator" => VAL_STR_LOADING_TRANSACTIONS,
            "internalTransfer" => VAL_STR_TRANSFER,
            "internalTransferTrash" => VAL_STR_TRANSFER_TRASH,
            "depositIndicator" => VAL_STR_DEPOSIT,
            "exchangeIndicator" => VAL_STR_EXCHANGE,
            "requestIndicator" => VAL_STR_REQUEST,
            "withdrawIndicator" => VAL_STR_WITHDARAW,
            "feeIndicator" => VAL_STR_FEE,
            "noResultsFound" => $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()),
            
            "headTransactionType" => VAL_STR_HEADER_TRANSACTION_TYPE,
            "headUserAccount" => VAL_STR_USER_ACCOUNT,
            "headUserAccountName" => VAL_STR_USER_ACCOUNT_NAME,
            "headCurrency" => VAL_STR_CURRENCY,
            "headDepositAmount" => VAL_DEPOSIT_AMOUNT,
            "headWithdrawalAmount" => VAL_WITHDRAWAL_AMOUNT,
            "headFee" => VAL_STR_FEE,
            "headDateRequested" => VAL_STR_DATE_REQUESTED,
            "headProcessngDate" => VAL_STR_PROCESSING_DATE,
            "headTransactionNumber" => VAL_STR_TRANSACTION_NUMBER,
            "headMessage" => VAL_STR_MESSAGE,
            "headType" => VAL_STR_TYPE,
            "headCurrentStatus" => VAL_STR_CURRENT_STATUS,
            "headBalance" => VAL_STR_HEADER_BALANCE,
            
            "statusApply" => VAL_STR_APPLY,
            "statusRemittanceAccepted" => VAL_STR_REMITTANCE_ACCEPTED,
            "statusRemittanceAlready" => VAL_STR_REMITTANCE_ALREADY,
            "statusDeficiencyChecking" => VAL_STR_DEFICIENCIES_CHECKING,
            "statusRefund" => VAL_STR_REFUND,
            "statusCancellation" => VAL_STR_CANCELLATION,
            "statusCancel" => VAL_STR_CANCEL,
            "statusComplete" => VAL_STR_STATUS_COMP
        ];
        
        $labelBuilder = NO_STRING;
        
        foreach($labels as $key => $label){
            $labelBuilder .= "\t<input type=\"hidden\" id=\"{$key}\" value=\"{$label}\"/>\n";
        }
        
        echo <<<HTMLSTRING
            <span class="hidediv js-labels">
                {$labelBuilder}
            </span>
HTMLSTRING;
    }
    
    public function getWhere() {
        $rtn = array();
        
        $rtn[] = $this -> detailAccount;
        $rtn[] = $this -> currency;
        $whereStr = NO_STRING;
        // 取引番号
        if($this -> transactionNumber != NO_STRING) {
            $whereStr .= ' AND transaction_number = (\')' . $this -> transactionNumber . '(\')';
        }
        // メールアドレス
        if($this -> sEmail != NO_STRING) {
            $whereStr .= ' AND (withdraw_user.mail LIKE (\')%' . $this -> sEmail . '%(\') OR deposit_user.mail LIKE (\')%' . $this -> sEmail . '%(\'))';
        }
        // 口座番号
        if($this -> sUserAccount != NO_STRING) {
            $whereStr .= ' AND (deposit_account_number = (\')' . $this -> sUserAccount . '(\') OR withdraw_account_number = (\')' . $this -> sUserAccount . '(\'))';
        }
        
        // 開始日
        if($this -> from != NO_STRING) {
            $whereStr .= ' AND transaction_time >= (\')' . $this -> from . '(\')';
        } else {
            $whereStr .= ' AND transaction_time >= (\')' . date('Y/m/01', strtotime('-2 month')) . '(\')';
        }
        // 終了日
        if($this -> to != NO_STRING) {
            $whereStr .= ' AND transaction_time < DATE_ADD((\')' . $this -> to . '(\'), INTERVAL 1 DAY)';
        } else {
            $whereStr .= ' AND transaction_time < DATE_ADD((\')' . date('Y/m/d') . '(\'), INTERVAL 1 DAY)';
        }
        
        // anton
        if($this -> transactionType != NO_STRING) {
            switch($this -> transactionType){
                case VAL_INT_1:
                    $whereStr .= ' AND transaction_type = (\')1(\')';					// 入金
                    break;
                case VAL_INT_2:
                    $whereStr .= ' AND (transaction_type IN ((\')9(\'), (\')10(\'), (\')12(\')) OR (transaction_type = (\')2(\') AND type = (\')0(\')))';	// 出金
                    break;
                case VAL_INT_3:
                    $whereStr .= ' AND transaction_type IN ((\')3(\'), (\')4(\'))';					// 通貨両替
                    break;
                case VAL_INT_4:
                    $whereStr .= ' AND (transaction_type IN ((\')5(\'), (\')6(\')) OR (transaction_type = (\')2(\') AND type = (\')3(\')))';				// 口座振替
                    break;
                case VAL_INT_5:
                    $whereStr .= ' AND transaction_type IN ((\')7(\'), (\')8(\'))';					// 引き落し
                    break;
                case VAL_INT_6:
                    $whereStr .= ' AND (transaction_type = (\')11(\') OR trans.type = (\')1(\'))';					// 引き落し
                    break;
                default:
                    break;
            }
            
        }
        
        $rtn[] = $whereStr;
        
        return $rtn;
    }
   
    public function setResult($rs){
        $this -> rs = $rs;
    }
    
    public function getDefaultPageCount(){
        return VAR_DEFAULT_PAGE_COUNT;
    }
    
    public function getCurrency(){
        return $this -> currency;
    }
    
    public function getDetailAccount(){
        return $this -> detailAccount;
    }
    
    public function echoDetailAccount(){
        echo $this -> detailAccount;
    }
    
    public function echoSUserAccount(){
        echo $this -> sUserAccount;
    }
    
    public function echoAccountInfo($key){
        switch($key){
            case "tier_level":
                echo ($this -> accountData[$key] != NO_STRING) ? $this -> getValueByList($this -> getTierStatusList(), $this -> accountData[$key]) : "";
                break;
            case "risk_level":
                echo ($this -> accountData[$key] != NO_STRING) ? $this -> getValueByList($this -> getRiskLevels(), $this -> accountData[$key]) : "";
                break;
            case "kyc_validate_status":
                $isUpload = $this -> accessSelect('COUNT_KYC_DOCUMENT', array($this -> detailAccount));
                echo empty($isUpload) || $this -> accountData[$key] == 99 ? '' : 
                '<a href="kyc?type=detail&user_account='.$this -> detailAccount.'" target="_blank">'
                    .$this -> arrValidate[$this -> accountData[$key]].'</a>';
                break;
            case "status":
                echo $this -> dispUserStatusCommon($this -> accountData["status"]);
                break;
            case "account_type":
                echo $this -> dispUserAccountTypeCommon($this -> accountData["account_type"]);
                break;
            default:
                echo $this -> accountData[$key];
                break;
        }
    }
    
    public function echoSEmail(){
        echo $this -> sEmail;
    }
    
    public function setCurrencyTxnCounter($currencyTxnCounter){
        $this -> currencyTxnCounter = $currencyTxnCounter;
    }
    
    public function setCurrencies($currencies){
        $this -> currencies = $currencies;
    }
    
    public function setStart($start){
        $this -> start = $start;
    }
    
    public function echoTransactionNumber(){
        echo $this -> transactionNumber;
    }
    
    public function echoFrom() {
        echo $this -> from;
    }
    
    public function echoTo() {
        echo $this -> to;
    }
    
    public function echoCurrencyList() {
        // 変数宣言部
        $lists	= array();
        if($this -> isLoopData($this -> currencies)) {
            
            foreach($this -> currencies as $row) {
                $lists[] = array(
                    PARAM_DATA_KEY	     => $this -> getColumnData($row, COLUMN_CURRENCY_NAME),
                    PARAM_DATA_VALUE	 => $this -> getColumnData($row, COLUMN_CURRENCY_NAME)
                );
            }
        }
         
        echo $this -> dispListOption($lists, $this -> currency);
    }
    
    public function dispTransactionTypeList() {
        echo $this -> dispListOption($this -> getTransactionTypeList(), $this -> transactionType);
    }
    
    public function dispHTML() {
        return array();
    }
}