<?php
/*
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    echo(json_encode(getPortfolio($db, 631, 0)));    */
    
    function getPortfolio($db, $userid, $totportfolio){
        $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();
                
        //$portfolio->total->number = 0;
        $totgral = 0;
        
        $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(TRUNCATE(B.balance,(C.decimals)), 0) balance " .
                "FROM       accounts A " .
                "INNER JOIN currencies C " .
                "ON         A.currencyid = C.id " .
                "LEFT JOIN  accountbalances B " .
                "ON         A.id = B.accountid " .
                "WHERE      A.userid=" . $userid . " ".
                "AND        A.paymentmethodid = -1 " .
                "AND        C.id > 0";
        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();
            
            //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 : exp_to_dec($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, 
                                                    "dsc"=>$symbols[$currencyid], 
                                                    "rate"=>(float)exp_to_dec($rate), 
                                                    "total"=>array( "number"=>exp_to_dec(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"];;
        
        return $portfolio;
    }

?>