<?php
include_once('config.php');

class H2PDepositWebhook extends System {
    
    private $referenceId    = NO_STRING;
    private $status         = NO_STRING;
    private $lang           = NO_STRING; 
    
    private $responseURL    = NO_STRING;
    private $responseDbURL  = NO_STRING;
    
    public function __construct(){
        parent::__construct();
        
        $this -> setParameter();
        
        $this -> validation();
    }
    
    private function setParameter(){
        $this -> referenceId    = $this -> getDataPost("Reference");
        $this -> status         = $this -> getDataPost("Status");
        $this -> lang           = $this -> getDataGet("lang");
        
        $this -> responseURL 	= "Logs/H2P/deposit_response";
        $this -> responseDbURL 	= "Logs/H2P/deposit_db_response";
    }
    
    private function validation(){
        if(!file_exists($this -> responseURL)) {
            mkdir($this -> responseURL, 0777, true);
        }
        
        if(!file_exists($this -> responseDbURL)) {
            mkdir($this -> responseDbURL, 0777, true);
        }
    }
    
    private function commentTemplate($row){
        return "Bank:".$row['deposit_bank']
            .",Merchant:{$this -> getDataPost('Merchant')}"
            .",Status:{$this -> getDataPost('Status')}"
            .",Currency:{$this -> getDataPost('Currency')}"
            .",Amount:{$this -> getDataPost('Amount')}"
            .",Datetime:{$this -> getDataPost('Datetime')}"
            .",Customer:{$this -> getDataPost('Customer')}"
            .",Language:{$this -> getDataPost('Language')}"
            .",Reference:{$this -> getDataPost('Reference')}"
            .",ID:{$this -> getDataPost('ID')}"
            .",Key:{$this -> getDataPost('Key')}"
            .",Note:{$this -> getDataPost('Note')}";
    }
    
    private function creditingDepositData($tempDepositRowData){
        return [
            $this -> getColumnData($tempDepositRowData, COLUMN_TRANSACTION_NUMBER),
            $this -> getColumnData($tempDepositRowData, COLUMN_USER_ACCOUNT),
            $this -> getColumnData($tempDepositRowData, COLUMN_AMOUNT),
            $this -> getColumnData($tempDepositRowData, COLUMN_CURRENCY),
            $this -> getColumnData($tempDepositRowData, COLUMN_METHOD),
            "Local Bank Transfer(Southeast Asia)",
            $this -> getColumnData($tempDepositRowData, COLUMN_DEPOSIT_DATE),
            $this -> getColumnData($tempDepositRowData, COLUMN_FEE),
            $this -> commentTemplate($tempDepositRowData),
            $this -> getColumnData($tempDepositRowData, COLUMN_CREATE_TIME),
            NO_COUNT,
            NO_COUNT,
            "Local Bank Transfer(Southeast Asia)"
        ];
    }
    
    private function emailNoticeParams($tempDepositRowData, &$emailAddress, &$language){
        $userAccountNum = $this -> getColumnData($tempDepositRowData, COLUMN_USER_ACCOUNT);
        
        $accountDetails = $this -> getRowData($this -> getAccountCommon($userAccountNum));
        
        $fullName = "{$this -> getColumnData($accountDetails, COLUMN_FIRST_NAME)} {$this -> getColumnData($accountDetails, COLUMN_LAST_NAME)}";
        
        // pointer-referenced
        $emailAddress   = $this -> getColumnData($accountDetails, COLUMN_MAIL);
        $language       = $this -> getColumnData($accountDetails, COLUMN_LANGUAGE);
        
        $params = [];
        
        if($this -> isLoopData($accountDetails)){
            $params = [
                $userAccountNum,
                $fullName,
                $this -> getColumnData($tempDepositRowData, COLUMN_TRANSACTION_NUMBER),
                $this -> getColumnData($tempDepositRowData, COLUMN_CREATE_TIME),
                $this -> getColumnData($tempDepositRowData, COLUMN_CURRENCY),
                $this -> getAmountString(
                    $this -> getColumnData($tempDepositRowData, COLUMN_AMOUNT), 
                    $this -> getColumnData($tempDepositRowData, COLUMN_CURRENCY)
                ),
                $this -> getColumnData($tempDepositRowData, COLUMN_CURRENCY),
                $this -> getAmountString(
                    $this -> getColumnData($tempDepositRowData, COLUMN_AMOUNT) + 
                    $this -> getColumnData($tempDepositRowData, COLUMN_FEE),
                    $this -> getColumnData($tempDepositRowData, COLUMN_CURRENCY)
                ),
                $this -> getColumnData($accountDetails, COLUMN_COUNTRY)
            ];
        }
        
        return $params;
    }
    
    private function logTransactionDetails($content){
        $logDate        = date("Y-m-d");
        $logTimestamp   = date("[Y-m-d H:i:s]");
        
        error_log(
            "{$logTimestamp}\r\n{$content}\r\n", VAL_INT_3, 
            "{$this -> responseURL}/Log_{$logDate}.log");
    }
    
    public function listen(){
        $logPostVars    = print_r($_POST, true);
        $logGetVars     = print_r($_GET, true);
        
        $this -> logTransactionDetails("Accessed\r\nPOST: {$logPostVars}GET: {$logGetVars}");
                
        // fetches temporary transaction data
        $temporaryDepositData = $this -> accessSelect("SELECT_DEPOSIT_H2P_TEMP", [$this -> referenceId]);
        
        if($this -> isLoopData($temporaryDepositData)){
            // check deposit transaction
            $depositData = $this -> accessSelect("SELECT_DEPOSIT_BY_TRANSACTION_NUMBER", [$this -> referenceId]);
            
            if(!$this -> isLoopData($depositData)){
                switch($this -> status){
                    case "000":
                    case "006":{                        
                        $tempDepositRowData = $this -> getRowData($temporaryDepositData);
                        
                        $this -> accessModify(
                            "INSERT_WB_DEPOSIT_TRANSACTION", 
                            $this -> creditingDepositData($tempDepositRowData), 
                            false);

                        $address    = NO_STRING;
                        $language   = NO_STRING;
                        $params = $this -> emailNoticeParams($tempDepositRowData, $address, $language);
                        
                        if($address != NO_STRING){
                            $this -> sendMailByTmp("{$this -> lang}/help2pay_deposit_info.xml", 
                                $params, 
                                $address,
                                VAR_CS_MAIL_ADDRESS,
                                $language
                            );
                        }
                        
                        $this -> accessModifyCommon('UPDATE_DEPOSIT_ISSENDMAIL', [$this -> referenceId]);
                        
                        $this -> logTransactionDetails("{$this -> referenceId} -deposit_response:\r\n{$this -> status}");
                        
                        echo "0";
                        break;
                    }
                    default:
                        $this -> logTransactionDetails("Invalid Status Code\r\n{$this -> status}");
                        break;
                }
            }else
                $this -> logTransactionDetails("Transaction already credited\r\n{$this -> referenceId}");
        }else
            $this -> logTransactionDetails("Invalid H2P Deposit Transaction\r\n{$this -> referenceId}"); 
    }
}

$h2pWebhook = new H2PDepositWebhook();
$h2pWebhook -> listen();