<?php
// app/api/accounts/portafolio

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","action");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out = new stdClass;
    $sessionid = $_GET['sessionid'];
    $action = $_GET['action'];
    $currencyid = "";
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    // Filtramos las cuentas por las acciones que pueden realizar
    /* 1 = Intercambio(Compra/Venta) (Debe existir en un PAR)
    *  2 = Deposito
    *  3 = Retiro
    *  4 = Transferencia
    */
    switch(intval($action)){
        case 1:
            // Intercambio
            $actionFilter = " AND (SELECT COUNT(pairs.currencyid) ".
            "                       FROM pairs ".
            "                       WHERE (pairs.currencyid = cur.id OR pairs.refcurrencyid = cur.id) ) > 0";
            break;
        case 2:
            // Deposito
            $actionFilter = " AND cur.interface != 3 ";
            break;
        case 3:
            // Retiro
            $actionFilter = " AND cur.interface != 3 ";
            break;
        case 4:
            // Transferencia
            $actionFilter = " AND cur.interface > 3 ";
            break;
        default:
            badEnd("500",array('msg'=>'El action debe ser 1, 2, 3 o 4'));
    }
    
    // Si se envia el currencyid, se arma el query
    if(isset($_GET['currencyid']) && $_GET['currencyid'] != ''){
        // Si se envia una moneda base, buscaremos las cuentas por las monedas ref de los pares donde se encuentre
        
        // Consultaremos las monedas ref de los pares donde esta la moneda base
        $sql = "SELECT refcurrencyid, currencyid ".
        "       FROM pairs ".
        "       WHERE currencyid = ".$_GET['currencyid'].
        "       OR refcurrencyid =".$_GET['currencyid'];
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
            
        $count = 0;
        $currencyid .= " AND (";
        
        // Con las monedas recogidas armamos la condicion
        while($row = $rs->fetch_assoc()){
            
            if($count == 0){
                $currencyid .= " cur.id = ".($_GET['currencyid'] == $row['currencyid'] ? $row['refcurrencyid'] : $row['currencyid']);
                $count++;
            }else{
                $currencyid .= " OR cur.id = ".($_GET['currencyid'] == $row['currencyid'] ? $row['refcurrencyid'] : $row['currencyid']);
            }
            
        }
        
        $currencyid .= " ) ";
    }
    
    // Consultamos la cantidad de cuentas a retornar
    $sql = "SELECT COUNT(accounts.id) AS qty ".
    "       FROM accounts, currencies cur ".
    "       WHERE accounts.userid = ".$userid.
    "       AND accounts.currencyid = cur.id ".
    "       AND cur.status = 1 ".
    "       AND accounts.paymentmethodid = -1 ".
    "       ".$actionFilter.
    "       ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    $row = $rs->fetch_assoc();
    $out->numofrecords = (int)$row['qty'];
    
    // Consultamos las cuentas junto a la moneda
    $sql = "SELECT accounts.id AS accountid, ".
    "       accounts.status AS accountstatus, ".
    "       cur.id AS currencyid, ".
    "       cur.symbol AS currencysymbol, ".
    "       cur.name AS currencyname, ".
    "       cur.decimals AS decimals, ".
    "       cur.interface AS interface ".
    "       FROM accounts, currencies cur ".
    "       WHERE accounts.userid = ".$userid.
    "       AND accounts.currencyid = cur.id ".
    "       AND cur.status = 1 ".
    "       AND accounts.paymentmethodid = -1 ".
    "       ".$actionFilter.
    "       ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    // Retornamos los datos de la cuenta
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row['accountid'];
        
        // Datos de la moneda
        $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['decimals'];
        $record->currency->interface = (int)$row['interface'];
        
        //Consultamos el balance disponible
        $sql = "SELECT SUM(amount) as qty FROM transactions WHERE accountid = ".$record->id;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $balancetx = $res->fetch_assoc();
            
        // Balance retenido por ordenes de intercambios
        $sql = "SELECT SUM(amount) AS qty ".
        "       FROM ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$record->id.
	    "           AND orders.canceled IS NULL ".
	    "           AND orders.type != 1 ".
        "       UNION ALL ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$record->id.
        "           AND orders.accountid = ".$record->id.
	    "           AND orders.canceled IS NULL ".
	    "           AND transactions.amount < 0 ".
	    "           AND orders.type != 1 ".
        "       ) amount";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
        
        $balanceorder = $res->fetch_assoc();
            
        //Balance disponible
        $record->avaliable = new stdClass();
        $record->avaliable->number = (float)($balancetx["qty"] - $balanceorder["qty"]);
        $record->avaliable->formatted = numberFormatt($record->avaliable->number,$row["decimals"]);
            
        //Balance retenido
        $record->committed = new stdClass();
        $record->committed->number = (float)$balanceorder["qty"];
        $record->committed->formatted = numberFormatt($record->committed->number,$row["decimals"]);
        
        //Balance pendiente de la cuenta
        $sql = "SELECT SUM(deposits.amount - deposits.fee) as qty ".
        "       FROM accounts, transactions".
        "       LEFT JOIN deposits ON transactions.id = deposits.transactionid ".
        "       AND deposits.rejected IS NULL AND deposits.valid IS NULL".
	    "       WHERE accounts.id = transactions.accountid AND accounts.id = ".$record->id.
	    "       AND transactions.amountghost >= 0";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
        
        $balance = $res->fetch_assoc();
        
        //Balance pendiente 
        $record->deferred = new stdClass();
        $record->deferred->number = (float)$balance["qty"];
        $record->deferred->formatted = numberFormatt($record->deferred->number,$row["decimals"]);
        
        // Balanace total
        $record->total = new stdClass();
        $record->total->number = $record->deferred->number + $record->committed->number + $record->avaliable->number;
        $record->total->formatted = numberFormatt($record->total->number,$row["decimals"]);
        
        // Estado de la cuenta
        $record->status = (int)$row['accountstatus'];
        
        // Validamos para retornar el maxbuy
        if($action != 1 || $currencyid == ''){
            $record->maxbuy = null;
        }else{
            
            // Consultamos el par para saber de donde contar la cantidad
            $sql = "SELECT COUNT(id) AS qty ".
            "       FROM pairs ".
            "       WHERE (currencyid = ".$_GET['currencyid'].
            "       AND refcurrencyid =".$record->currency->id." ) ".
            "       OR (currencyid = ".$record->currency->id.
            "       AND refcurrencyid = ".$_GET['currencyid']." ) ";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error.$sql));
        
            $max = $res->fetch_assoc();
            
            // Validamos que exista un par
            if($max['qty'] > 0){
                
                //COnsultamos los datos del par
                $sql = "SELECT id, refcurrencyid, currencyid ".
                "       FROM pairs ".
                "       WHERE (currencyid = ".$_GET['currencyid'].
                "       AND refcurrencyid =".$record->currency->id." ) ".
                "       OR (currencyid = ".$record->currency->id.
                "       AND refcurrencyid = ".$_GET['currencyid']." ) ";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>$db->error.$sql));
        
                $max = $res->fetch_assoc();
                
                // Obtenemos los decimales para el par
                $sql = "SELECT decimals FROM currencies WHERE id = ".$max['refcurrencyid'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>$db->error.$sql));
        
                $decimals = $res->fetch_assoc();
                
                //Consultamos la ultima venta
                $sql = "SELECT o.quantity AS qty, o.id AS grouptx, ".
                "       o.price, o.side, o.id, o.total".
                "       FROM orders o".
                "       WHERE o.side = 1 AND o.canceled IS NULL AND o.pairid = ".$max['id'].
                "       AND (CASE ".
                "           WHEN o.canceled IS NOT NULL THEN -1 ".
                "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
                "               AND o.canceled IS NULL THEN 1 ".
                "           ELSE 0 ".
                "       END) = 0 ".
                "       ORDER BY o.price ASC".
                "       LIMIT 1";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>$db->error.$sql));
                    
                $ask = $res->fetch_assoc();
        
                // Retornamos el ask del par
                $refPrice = (float)$ask['price'];
                
                $sql = "SELECT SUM(o.quantity) AS qty, COUNT(o.id) AS grouptx, o.price AS price, ".
                "       IF( ".
                "           (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) IS NOT NULL, ".
                "           (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)), ".
                "           0 ".
                "       ) AS totallyfilled ".
                "       FROM orders o".
                "       WHERE o.side = 1 AND o.canceled IS NULL AND o.pairid = ".$max['id'].
                "       AND (CASE ".
                "           WHEN o.canceled IS NOT NULL THEN -1 ".
                "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
                "               FROM transactions, orders ".
                "               WHERE orders.id = transactions.orderid ".
                "               AND orders.id = o.id ".
                "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
                "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
                "               AND o.canceled IS NULL THEN 1 ".
                "           ELSE 0 ".
                "       END) = 0 ".
                "       GROUP BY o.price".
                "       ORDER BY o.price ASC, o.date DESC";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>$db->error.$sql));
                    
                    
                $acum = $record->avaliable->number;
                $total = 0;
                while($pairquantity = $res->fetch_assoc()){
                    // Sacamos lo que tiene la orden en total con su precio para ver si podemos completarla toda o no
                    $tempRate = $refPrice * ($pairquantity["qty"] - $pairquantity['totallyfilled']);
                    $temptotal = 0;
                    
                    // Si la tasa es menor podemos completarla toda, restamos la orden
                    if($tempRate < $acum){
                        $acum = $acum - $tempRate;
                        
                        $temptotal = (float)($pairquantity["qty"] - $pairquantity['totallyfilled']);
                
                        $total += $temptotal;
                        
                    }else if($acum > 0){
                        // Si no, con lo que nos resta sacamos lo que podemos sacarle a la orden
                        $temptotal = (float)($acum / $refPrice);
                        
                        if($temptotal > $pairquantity["qty"] - $pairquantity['totallyfilled']){
                            $ttotal += $pairquantity["qty"] - $pairquantity['totallyfilled'];
                        }else{
                            $total += $temptotal;
                        }
                        
                        $acum = $acum - $refPrice;
                    }
                }
                
                $record->maxbuy = new stdClass();
                $record->maxbuy->number = (float)number_format($total,$decimals['decimals'],".","");;
                $record->maxbuy->formatted = number_format($record->maxbuy->number,$decimals['decimals'],",",".");
            }
        }
        
        $records [] = $record;
    }
    
    $out->records = $records;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
