<?php
// app/api/orders/list

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","parid","numofrec");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass;
    $sessionid = $_GET["sessionid"];
    $numofrec = $_GET["numofrec"];
    $parid = $_GET["parid"];
    $own = $_GET['own'];
    $order = determinateOrder($_GET["order"]);
    $ownfilter = "";
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    //Si el own es 1 se traen las de el usuario
    if($own == 1){
        //Consultamos los datos del para para obtener las monedas
        $sql = "SELECT * FROM pairs WHERE id = ".$parid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $row = $rs->fetch_assoc();
        
        //Consultamos las cuentas del usuario por su moneda
        $sql = "SELECT accounts.id AS accountid ".
        "       FROM accounts, users".
        "       WHERE users.id = ".$userid.
        "       AND accounts.userid = users.id".
        "       AND accounts.paymentmethodid = -1".
        "       AND accounts.entityusrid = -1 ".
        "       AND (accounts.currencyid = ".$row['currencyid'].
        "       OR  accounts.currencyid = ".$row['refcurrencyid'].")";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        while($row = $rs->fetch_assoc()){
            $ownaccounts [] = $row['accountid'];
        }
        
        $qtyaccounts = sizeof($ownaccounts) - 1;
        foreach($ownaccounts as $index => $accountid){
            if($index == 0){
                $ownfilter = "AND (";
            }
            
            if($index != 0){
                $ownfilter .= " OR ";
            }
            
            $ownfilter .= " accountid = ".$accountid. ' OR paymentid = '.$accountid;
            
            if($index == $qtyaccounts){
                $ownfilter .= ')';
            }
        }
    }
    
    //Obtenemos la cantidad de ventas que hay
    $sql = "SELECT SUM(quantity) AS qty, COUNT(id) AS grouptx, ".
    "       price, side, id, total".
    "       FROM orders o".
    "       WHERE side = 1 AND canceled IS NULL AND pairid = ".$parid.
    "       ".$ownfilter.
    "       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 transactions.accountid = o.accountid) >= (CASE WHEN o.side = 1 THEN o.quantity ELSE o.total END) ".
    "               AND o.canceled IS NULL THEN 1 ".
    "           ELSE 0 ".
    "       END) = 0 ".
    "       GROUP BY price".
    "       ".$order.
    "       LIMIT ".$numofrec;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Ordenamos las ventas
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row["id"];
        $record->orders = (int)$row["grouptx"];
        
        $record->price = new stdClass();
        $record->price->number = (float)$row["price"];
        $record->price->formatted = number_format($record->price->number,2,",",".");
        
        $record->quantity = new stdClass();
        $record->quantity->number = (float)$row["qty"];
        $record->quantity->formatted = number_format($record->quantity->number,2,",",".");
        
        $record->total = new stdClass();
        $record->total->number =  (float)$record->price->number * $record->quantity->number;
        $record->total->formatted = number_format($record->total->number,2,",",".");
        
        $bids [] = $record;
    }
    
    $out->bids = $bids;
    
    
    //Obtenemos la cantidad de compras que hay
    $sql = "SELECT SUM(quantity) AS qty, COUNT(id) AS grouptx, ".
    "       price, side, id, total".
    "       FROM orders o".
    "       WHERE side = 2 AND canceled IS NULL AND pairid = ".$parid.
    "       ".$ownfilter.
    "       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 transactions.accountid = o.accountid) >= (CASE WHEN o.side = 1 THEN o.quantity ELSE o.total END) ".
    "               AND o.canceled IS NULL THEN 1 ".
    "           ELSE 0 ".
    "       END) = 0 ".
    "       GROUP BY price".
    "       ".$order.
    "       LIMIT ".$numofrec;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Ordenamos las compras
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row["id"];
        $record->orders = (int)$row["grouptx"];
        
        $record->price = new stdClass();
        $record->price->number = (float)$row["price"];
        $record->price->formatted = number_format($record->price->number,2,",",".");
        
        $record->quantity = new stdClass();
        $record->quantity->number = (float)$row["qty"];
        $record->quantity->formatted = number_format($record->quantity->number,2,",",".");
        
        $record->total = new stdClass();
        $record->total->number = (float)$record->price->number * $record->quantity->number;
        $record->total->formatted = number_format($record->total->number,2,",",".");
        
        $asks [] = $record;
    }
    
    $out->asks = $asks;

    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para determinar el orden de los datos, recibe un parametro order que puede ser:
    *   1 = price
    */
    function determinateOrder($order){
        $str = "";
        
        switch($order){
            case 1:
                $str = "price ASC, date DESC";
                break;
            default:
                $str = "price ASC, date DESC";
                break;
        }
        
        return " ORDER BY ".$str;
    }
?>