<?php
// app/api/balance/accounts

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
        
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $out->total = new stdClass();
    $sessionid = $_GET["sessionid"];
    $offset = "";
    $limit = "";
    $filter = "";
    $dateAndHour = false;
    //$currencyid = $_GET["currencyid"];
    
    //Validamos que la session del usuario sea valida para continuar
    $userid = isSessionValid($db, $sessionid);
    
    //En caso de que el offset sea enviado, se construye el query
    $filter = "";
    if(isset($_GET["filter"]) && $_GET["filter"] != ""){
        $filter = "AND (C.name LIKE '%".$_GET["filter"]."%' OR C.symbol LIKE '%".$_GET["filter"]."%')";  
    }
    
    //En caso de que el offset sea enviado, se construye el query
    if(isset($_GET["offset"]) && $_GET["offset"] != ""){
        $offset = $_GET["offset"];
    }else{
        $offset = "0";
    }
    
    //En caso de que el numofrec sea enviado, se construye el query
    if(isset($_GET["numofrec"]) && $_GET["numofrec"] != ""){
        $numofrec = $_GET["numofrec"];
    }
    
    if($offset != 0 && $numofrec == ""){
        $limit = " LIMIT ".$offset.", 18446744073709551615";
    }else if($offset != 0 && $numofrec != ""){
        $limit = " LIMIT ".$offset.", ".$numofrec;
    }else if($offset == 0 && $numofrec != ""){
        $limit = " LIMIT ".$numofrec;
    }else{
        $limit = " LIMIT ".$offset.", 18446744073709551615";
    }
    
    $portfolio = new stdClass();
        
    // calcular totales
    $sql =  "SELECT     R.rate, R.currencyid, C.name currencyname, C.symbol currencysymbol, C.decimals " .
            "FROM       cmsprefrates R " .
            "INNER JOIN currencies C " .
            "ON         R.currencyid = C.id " .
            "WHERE      C.status = 1 " .
            "AND        C.id > 0 ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $portfolio->total = new stdClass();
    $portfolio->total->currencies = array();
    $rates = array();
    $symbols = array();
    $totals = array();
    $decimals = array();
    while($row = $rs->fetch_assoc()){
        //$portfolio->total->currencies[] = array("id"=>(int)$row["currencyid"], "dsc"=>$row["currencysymbol"], "rate"=>(float)$row["rate"]);
        $rates[$row["currencyid"]] = (float)$row["rate"];
        $symbols[$row["currencyid"]] = $row["currencysymbol"];
        $totals[$row["currencyid"]] = 0;
        $decimals[$row["currencyid"]] = (int)$row["decimals"];
    }
    
    $portfoliototals = new stdClass();
            
    $totgral = 0;

    $lasttx = "SELECT MAX(T.datecreated) AS datecreated, accountid FROM transactions T GROUP BY T.accountid";
    
    $sql =  "SELECT     A.id accountid,  " .
            "           A.status accountstatus, " .
            "           A.paymentmethodid, " .
            "           C.id currencyid, " .
            "           C.name AS currencyname, " .
            "           C.symbol AS currencysymbol, " .
            "           C.decimals AS currencydecimals, " .
            "           C.status AS currencystatus, " .
            "           C.interface AS currencyinterface, " .
            "           C.icon AS currencyicon, " .
            "           C.xfer AS currencyxfer, " .
            "           IFNULL(B.commited, 0) commited, " .
            "           IFNULL(B.deferred, 0) deferred, " .
            "           IFNULL(B.balance, 0) balance, " .
            "           IFNULL(T.datecreated, '-') lasttx " .
            "FROM       accounts A " .
            "INNER JOIN currencies C " .
            "ON         A.currencyid = C.id " .
            "LEFT JOIN  accountbalances B " .
            "ON         A.id = B.accountid " .
            "LEFT JOIN  (".$lasttx.") T " .
            "ON         A.id = T.accountid " .
            "WHERE      A.userid=" . $userid . " ".
            "AND        A.paymentmethodid = -1 " .
            "AND        C.id > 0 ".$filter.
            "       ".$limit;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    

    $portfolio->accounts = new stdClass();
    $records = array();
        
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        
        $record->last = $row['lasttx'] == "-" ? '' : date("d/m/Y", strtotime($row["lasttx"]))." - ".date("h:i a", strtotime($row["lasttx"]));

        //Cuenta
        $record->id = (int)$row["accountid"];
        $record->status = (int)$row["accountstatus"];
        //Metodo de pago
        $record->paymentmethod = new stdClass();
        $record->paymentmethod->id = (int)$row["paymentmethodid"];
        $record->paymentmethod->dsc = "AFX";

        //Moneda de la cuenta
        $record->currency = new stdClass();
        $record->currency->id = (int)$row["currencyid"];
        $record->currency->dsc = $row["currencyname"];
        $record->currency->symbol = $row["currencysymbol"];
        $record->currency->decimals = (int)$row["currencydecimals"];
        $record->currency->status = (int)$row['currencystatus'];
        $record->currency->interface = (int)$row['currencyinterface'];
        $record->currency->icon = $row['currencyicon'];
        $record->currency->xfer = (int)$row['currencyxfer'];

        //Balance a partir de las transacciones
        $record->balance = new stdClass();
        $record->balance->number = $row['balance']*1;
        $record->balance->number = $record->balance->number < 0 ? 0 : $record->balance->number;
        $record->balance->formatted = numberFormatt($record->balance->number,$row["currencydecimals"]);
        
        //Balance a partir de las transacciones
        $record->committed = new stdClass();
        $record->committed->number = $row['commited']*1;
        $record->committed->formatted = numberFormatt($record->committed->number,$row["currencydecimals"]);
            
        $record->deferred = new stdClass();
        $record->deferred->number = $row['deferred']*1;
        $record->deferred->formatted = numberFormatt($record->deferred->number,$row["currencydecimals"]);
        
        $record->total = new stdClass();
        $record->total->number = $record->total->balance+$record->total->commited+$record->total->deferred;
        $record->total->formatted = numberFormatt($record->total->number,$row["currencydecimals"]);

         //Porcentaje que representa
        $record->pct = new stdClass();
        $record->pct->number = 0;
        $record->pct->formatted = numberFormatt($record->pct->number,2)."%";
        
        if($record->balance->number>0){    
            $totals[$row["currencyid"]] += $record->balance->number / $rates[$row["currencyid"]];
            $totgral += $record->balance->number / $rates[$row["currencyid"]];
        }else{
            $totals[$row["currencyid"]] += 0;
            $totgral += 0;
        }

        $records [] = $record;
    }
    
    foreach ($records as $record){
        if ($totgral <> 0)
            $record->pct->number = $totals[$record->currency->id] * 100 / $totgral;
        else
            $record->pct->number = 0;
        $record->pct->formatted = numberFormatt($record->pct->number,2)."%";
    }
    
    
    $portfoliototals->number = $totals[$records[0]->currency->id];
    $portfoliototals->id = $records[0]->currency->id;
    $portfoliototals->dsc = $records[0]->currency->symbol;
    $portfoliototals->formatted = $totals[$records[0]->currency->symbol];
    
    $portfolio->total = $portfoliototals;
    $portfolio->accounts = $records;
    
    foreach($rates as $currencyid => $rate ){
        $portfolio->total->currencies[] = array("id"=>(int)$currencyid, 
                                                "symbol"=>$symbols[$currencyid], 
                                                "decimals"=>$decimals[$currencyid], 
                                                "rate"=>(float)$rate, 
                                                "total"=>array( "number"=>round($totgral*$rate, $decimals[$currencyid]),
                                                                "formatted"=>numberFormatt($totgral*$rate, $decimals[$currencyid])));
    }

    $portfolio->total->number = $portfolio->total->currencies[0]["total"]["number"];
    $portfoliototals->id = $portfolio->total->currencies[0]["id"];
    $portfoliototals->dsc = $portfolio->total->currencies[0]["dsc"];
    $portfoliototals->formatted = $portfolio->total->currencies[0]["total"]["formatted"];;
    
    $out = $portfolio;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
