<?php
require_once __DIR__."/../system/lib/config.php";

class MerchantBalance extends System {
    
    /**
     *
     * integrator's input
     * @var string
     */
    private $pnum;
    
    /**
     * 
     * integrator's input
     * @var string
     */
    private $password;
    
    /**
     * 
     * auto
     * @var string
     */
    private $requestMethod;
    
    /**
     * 
     * auto
     * @var string
     */
    private $userAccount;
    
    /**
     * 
     * auto
     * @var string
     */
    private $remoteAddress;
    
    public function __construct(){
        parent::__construct();      
        $this -> setParameter();
        $this -> validation();
    }
    
    /**
     * 
     * initializing user inputs and automated values to properties indicated within the function
     */
    private function setParameter(){
        header("Content-type: text/json");
        
        $this -> pnum           = $this -> getColumnData($_SERVER, "HTTP_PROGRAM_CODE");
        $this -> password       = $this -> getColumnData($_SERVER, "HTTP_SECRET_KEY");
        $this -> requestMethod  = $this -> getColumnData($_SERVER, "REQUEST_METHOD");
        $this -> remoteAddress  = $this -> getColumnData($_SERVER, "REMOTE_ADDR");
    }
    
    /**
     * 
     * process validations to whatever the integrator has passed to the headers
     */
    private function validation(){        
        $invalid = [];
        
        if($this -> requestMethod == "POST"){
            $macc = $this -> getAPISignatureCommon($this -> pnum);
            
            if($this -> isLoopData($macc)){
                $this -> credentialCheck($macc, $invalid);
            }else
                $invalid[] = "Account doesn't exist: {{$this -> userAccount}}";
        }else
            $invalid[] = "Invalid Request Method: {{$this -> requestMethod}}";
        
        if($this -> isLoopData($invalid)){
            header("HTTP/1.1 403 Forbidden due to validation results");
            $remarks = print_r($invalid, true);
            $remarks = print_r(apache_request_headers(), true)."\n\n{$remarks}";
            $this -> logDetails($remarks);
            die(print_r($invalid, true));
        }
    }
    
    /**
     * 
     * @param array $macc
     * @param array $invalid
     */
    private function credentialCheck($macc, &$invalid){
        $macc = $this -> getRowData($macc);
        
        $registPassword = $this -> getColumnData($macc, COLUMN_PASSWORD);
        
        if($this -> password == $registPassword){
            $wlistSettings = $this -> getColumnData($macc, COLUMN_WHITELIST_SETTING);
            
            if($this -> checkJSONString($wlistSettings)){
                $wlistSettings = json_decode($wlistSettings);
                
                if(isset($wlistSettings -> allow_merchant_balance) && $wlistSettings -> allow_merchant_balance){
                    $wIpAddresses = $this -> getColumnData($macc, COLUMN_IP_ADDRESS);
                    $wIpAddresses = explode(DELIMIT_COMMA, $wIpAddresses);
                    
                    if(in_array($this -> remoteAddress, $wIpAddresses)){
                        $this -> userAccount = $this -> getAccountCommon($this -> getColumnData($macc, COLUMN_USER_ACCOUNT));
                        
                        if($this -> isLoopData($this -> userAccount)){
                            $this -> userAccount = $this -> getRowData($this -> userAccount);
                        }else
                            $invalid[] = "Account for pnum {$this -> pnum} doesn't exist.";
                    }else
                        $invalid[] = "Invalid IP Address: {{$this -> remoteAddress}}";
                    
                }else
                    $invalid[] = "Balance API isn't enabled to pnum {{$this -> pnum}}";
            }else
                $invalid[] = "Internal Error Occurred";
        }else
            $invalid[] = "Incorrect Password";
    }
    
    /**
     *
     * @param string $content
     */
    private function logDetails($content){
        $timestamp = date("Y-m-d H:i:s");
        
        $logDir = SITE_ROOT."api/Logs/settlement/checkbal";
        
        if(!@file_exists($logDir))
            mkdir($logDir, 0777, true);
            
        $logFile = "{$logDir}/Log_".date("Y-m-d").".log";
        error_log("[{$timestamp}]\n\n{$content}\n\n", VAL_INT_3, $logFile);
    }
    
    /**
     * 
     * main method
     */
    public function listen(){
        $accNum = $this -> getColumnData($this -> userAccount, COLUMN_USER_ACCOUNT);
        $balances = $this -> accessSelect('SELECT_USER_BALANCES', [$accNum]);
        
        foreach($balances as &$balance){
            unset($balance[COLUMN_USER_ACCOUNT]);
            
            $props = [
                COLUMN_BALANCE, 
                COLUMN_WITHDRAW_AMOUNT, 
                COLUMN_DEPOSIT_AMOUNT
            ];
            
            foreach($props as $prop){
                if(is_numeric($balance[$prop])){
                    $currency = $balance[COLUMN_CURRENCY];
                    $balance[$prop] = $this -> intToCurrency($balance[$prop], $currency);
                }
            }            
        }
        
        echo json_encode($balances);
        
        $this -> logDetails(print_r(apache_request_headers(), true)."\n\nChecked Balance");
    }
}

$bal = new MerchantBalance();
$bal -> listen();