<?php

/**
 * 
 * @author antonio
 *
 */
trait UserBalances{
    public function generateBalances(ParamHolder $holder){
        $sys = $holder -> getSource();
       
        if($sys instanceof System){
            $holder -> userAccount = str_replace("&quot;", "\"", $holder -> userAccount);
            
            $accountBalanceData = [];
            
            if($sys -> checkJSONString($holder -> userAccount)){
                $holder -> userAccount = json_decode($holder -> userAccount);
                
                foreach($holder -> userAccount as $value){
                    $accountBalanceData["balanceData"][] = $this -> fetchUserBalanceData($sys, $value);
                }
            }else
                $accountBalanceData["balanceData"][] = $this -> fetchUserBalanceData($sys, $holder -> userAccount);
            
            echo json_encode($accountBalanceData); 
        }
    }
    
    private function fetchUserBalanceData(System $sys, String $userAccount){
        $account = $sys -> getRowData($sys -> getAccountCommon($userAccount), NO_COUNT);
        
        $balances = $sys -> accessSelect('SELECT_USER_BALANCES',
            [$sys -> getColumnData($account, PARAM_USER_ACCOUNT)]);
        
        // enhancements
        foreach($balances as &$balance){
            unset($balance["user_account"]);
            $balance["balance"] = $sys -> intToCurrency($balance["balance"], $balance["currency"]);
            $balance["withdraw_amount"] = $sys -> intToCurrency($balance["withdraw_amount"], $balance["currency"]);
            $balance["deposit_amount"]  = $sys -> intToCurrency($balance["deposit_amount"], $balance["currency"]);
        }
        
        $result = [
            "user_account" => $sys -> getColumnData($account, COLUMN_USER_ACCOUNT),
            "account_name" => $sys -> getColumnData($account, COLUMN_FIRST_NAME)." "
            .$sys -> getColumnData($account, COLUMN_LAST_NAME),
            "user_balances" => $balances
        ];
        
        return $result;
    }
}