<?php
// app/api/orders/details

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","currencyid","refcurrencyid","action");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass();
    $out->entry = new stdClass();
    $sessionid = $_GET["sessionid"];
    $currencyid = $_GET["currencyid"];
    $refcurrencyid = $_GET["refcurrencyid"];
    $action = $_GET['action'];
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    //Consultamos para verificar que exista un par con las monedas
    $sql = "SELECT COUNT(id) AS qty FROM pairs ".
    "       WHERE ((currencyid = ".$currencyid.
    "       AND refcurrencyid = ".$refcurrencyid.") ".
    "       OR (currencyid = ".$refcurrencyid.
    "       AND refcurrencyid = ".$currencyid.")) ".
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    // Validamos que haya conseguido registros con los parametros
    if($row['qty'] == 0){
        badEnd("204", array("msg"=>"Registro no encontrado"));
    }
    
    //Consultamos para verificar que exista un par con las monedas
    $sql = "SELECT id, currencyid, refcurrencyid ".
    "       FROM pairs ".
    "       WHERE ((currencyid = ".$currencyid.
    "       AND refcurrencyid = ".$refcurrencyid.") ".
    "       OR (currencyid = ".$refcurrencyid.
    "       AND refcurrencyid = ".$currencyid.")) ".
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $pairdata = $rs->fetch_assoc();
    
    //Retornamos el id del par
    $out->entry->id = (int)$pairdata['id'];
    
    // Consultamos los datos de la moneda base
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$pairdata['currencyid'].
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $basecurrency = $rs->fetch_assoc();
    
    //Guardamos los detalles de la moneda base
    $out->entry->currency = new stdClass();
    $out->entry->currency->id = (int)$basecurrency['id'];
    $out->entry->currency->dsc = $basecurrency['name'];
    $out->entry->currency->symbol = $basecurrency['symbol'];
    $out->entry->currency->decimals = (int)$basecurrency['decimals'];
    $out->entry->currency->interface = (int)$basecurrency['interface'];
    
    // Consultamos los datos de la moneda ref
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$pairdata['refcurrencyid'].
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $refcurrency = $rs->fetch_assoc();
    
    //Guardamos los detalles de la moneda ref
    $out->entry->refcurrency = new stdClass();
    $out->entry->refcurrency->id = (int)$refcurrency['id'];
    $out->entry->refcurrency->dsc = $refcurrency['name'];
    $out->entry->refcurrency->symbol = $refcurrency['symbol'];
    $out->entry->refcurrency->decimals = (int)$refcurrency['decimals'];
    $out->entry->refcurrency->interface = (int)$refcurrency['interface'];
    
    // Orden de la accion
    $out->entry->orden = new stdClass();
    $out->entry->orden->basecurrencyid = $out->entry->currency->id;
    $out->entry->orden->refcurrencyid = $out->entry->refcurrency->id;
    
    //Determinamos el tipo de orden donde
    // 1 = venta
    // 2 = compra
    if($action == 1 && $out->entry->orden->basecurrencyid != $currencyid){
        $out->entry->orden->type = 2;
    }else{
        $out->entry->orden->type = 1;
    }
    
    
    //Obtenemos la ultima transaccion realizada
    $sql = "SELECT (SELECT ord.price FROM orders ord ".
    "       WHERE ord.type = 2 AND (ord.id = t.orderid OR ord.id = txother.orderid)) AS lastprice ".
    "       FROM orders, accounts, transactions t  ".
    "           LEFT JOIN transactions txother ".
    "               ON t.orderid != txother.orderid ".
    "               AND t.txid = txother.txid  ".
    "               AND txother.amount > 0 ".
    "               AND txother.dsc NOT LIKE 'Comisi%' ".
    "       WHERE t.orderid IS NOT NULL ".
    "       AND orders.id = txother.orderid ".
    "       AND orders.pairid = ".$out->entry->id.
    "       AND t.id = t.txid ".
    "       AND t.dsc NOT LIKE 'Comisi%' ".
    "       AND accounts.id = orders.accountid ".
    "       GROUP BY t.txid ".
    "       ORDER BY t.datecreated DESC, t.id DESC".
    "       LIMIT 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
                
    $row = $rs->fetch_assoc();
        
    // Retornamos el precio del ultimo intercambio
    $out->entry->last = new stdClass();
    $out->entry->last->number = (float)$row["lastprice"];
    $out->entry->last->formatted = numberFormatt($out->entry->last->number,$basecurrency['decimals']);
    
    //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 = ".$out->entry->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 (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    $row = $rs->fetch_assoc();
    
    // Retornamos el ask del par
    $out->entry->ask = new stdClass();
    $out->entry->ask->number = (float)$row['price'];
    $out->entry->ask->formatted = numberFormatt($out->entry->ask->number,$basecurrency['decimals']);
    
    //Consultamos los datos de la ultima compra
    $sql = "SELECT o.quantity AS qty, o.id AS grouptx, ".
    "       o.price, o.side, o.id, o.total".
    "       FROM orders o".
    "       WHERE o.side = 2 AND o.canceled IS NULL AND o.pairid = ".$out->entry->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 DESC".
    "       LIMIT 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    $row = $rs->fetch_assoc();
    
    // Retornamos el bid del par
    $out->entry->bid = new stdClass();
    $out->entry->bid->number = (float)$row['price'];
    $out->entry->bid->formatted = numberFormatt($out->entry->bid->number,$basecurrency['decimals']);
    
    // Necesitamos obtener el saldo del usuario
    // Consultamos su cuenta (COMPRA)
    if($action == 2){
        $sql = "SELECT accounts.id AS accountid ".
        "       FROM accounts, currencies cur ".
        "       WHERE accounts.userid = ".$userid.
        "       AND accounts.currencyid = cur.id ".
        "       AND cur.status = 1 ".
        "       AND accounts.paymentmethodid = -1 ".
        "       AND cur.id = ".$out->entry->currency->id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
            
        $row = $rs->fetch_assoc();
        
        $accountid = $row['accountid'];
        
        //Consultamos el balance disponible
        $sql = "SELECT SUM(amount) as qty FROM transactions WHERE accountid = ".$accountid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $balancetx = $rs->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 = ".$accountid.
	    "           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 = ".$accountid.
        "           AND orders.accountid = ".$accountid.
	    "           AND orders.canceled IS NULL ".
	    "           AND transactions.amount < 0 ".
	    "           AND orders.type != 1 ".
        "       ) amount";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
        
        $balanceorder = $rs->fetch_assoc();
    
        $acum = number_format($balancetx["qty"] - $balanceorder["qty"], $out->entry->currency->decimals, '.', '');
    }else{
        $sql = "SELECT accounts.id AS accountid ".
        "       FROM accounts, currencies cur ".
        "       WHERE accounts.userid = ".$userid.
        "       AND accounts.currencyid = cur.id ".
        "       AND cur.status = 1 ".
        "       AND accounts.paymentmethodid = -1 ".
        "       AND cur.id = ".$out->entry->refcurrency->id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
            
        $row = $rs->fetch_assoc();
        
        $accountid = $row['accountid'];
        
        //Consultamos el balance disponible
        $sql = "SELECT SUM(amount) as qty FROM transactions WHERE accountid = ".$accountid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $balancetx = $rs->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 = ".$accountid.
	    "           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 = ".$accountid.
        "           AND orders.accountid = ".$accountid.
	    "           AND orders.canceled IS NULL ".
	    "           AND transactions.amount < 0 ".
	    "           AND orders.type != 1 ".
        "       ) amount";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
        
        $balanceorder = $rs->fetch_assoc();
    
        $acum = number_format($balancetx["qty"] - $balanceorder["qty"], $out->entry->refcurrency->decimals, '.', '');
    }
    
    $out->test1 = $acum;
    
    // COnsultamos las ordenes para obtener el mayor de compra
    $sql = "SELECT SUM(o.quantity) AS qty, COUNT(o.id) AS grouptx, ".
    "       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 = ".($action == 2 ? 1 : 2)." AND o.canceled IS NULL AND o.pairid = ".$out->entry->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));
        
        
    $total = 0;
    
    $refPrice = number_format($out->entry->ask->number, $basecurrency['decimals'], '.', '');
    $out->test2 = $refPrice;
    while($pairquantity = $res->fetch_assoc()){
        
        if($action == 2){
            // 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;
            }
        }else{
            
            $tempRate = ($pairquantity["qty"] - $pairquantity['totallyfilled']);
            $temptotal = 0;
            
            if($tempRate < $acum){
                $acum = $acum - $tempRate;
            
                $temptotal = (float)($pairquantity["qty"] - $pairquantity['totallyfilled']);
                
                $total += $temptotal;
                
            }else if($acum > 0){
                $temptotal = $acum;
            
                $total += $temptotal;
                $acum -= $acum;
            }
        }
    }
    
    $out->entry->max = new stdClass();
    $out->entry->max->number = (float)number_format($total,$out->entry->refcurrency->decimals,".","");;
    $out->entry->max->formatted = number_format($out->entry->max->number,$out->entry->refcurrency->decimals,",",".");
    
    //Consultamos los datos del usuario para encontrar su fee
    $sql = "SELECT id, usr, type, level ".
    "       FROM users WHERE id = ".$userid;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
            
    $userdata = $res->fetch_assoc();
    
    //Inicializamos el nivel en 1
    $level = 1;
    
    //Si el usuario es nivel 0, le colocamos comision de nivel 1
    if($userdata["level"] == 0){
        $level = 1;
    }else{
        $level = $userdata["level"];
    }
    
    // Consultamos las comisiones del par
    $sql = "SELECT * FROM cmspreffees ".
    "       WHERE levelid = ".$level.
    "       AND pairid = ".$out->entry->id.
    "       AND usertype = ".$userdata["type"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
            
    $feedata = $res->fetch_assoc();
    
    $out->entry->fees = new stdClass();
    
    //Comisiones para market
    $out->entry->fees->market = new stdClass();
    
    //Si el porcentaje es 0, guardamos el nominal y retornamos el pct en null, y si no, lo hacemos al reves
    if($feedata["pctmktfee"] == 0){
        $out->entry->fees->market->pctfee = null;
        
        $out->entry->fees->market->nmalfee = new stdClass();
        $out->entry->fees->market->nmalfee->number = (float)$feedata['nmlmktfee'];
        $out->entry->fees->market->nmalfee->formatted = number_format($feedata['nmlmktfee'],($action == 1 ? $out->entry->refcurrency->decimals : $out->entry->currency->decimals),",",".");
        
    }else{
        $out->entry->fees->market->pctfee = new stdClass();
        $out->entry->fees->market->pctfee->number = (float)$feedata['pctmktfee'];
        $out->entry->fees->market->pctfee->formatted = number_format($feedata['pctmktfee'],2,",",".");
        
        $out->entry->fees->market->nmalfee = null;
    }
        
    //Comisiones para limit
    $out->entry->fees->limit = new stdClass();
    
    //Si el porcentaje es 0, guardamos el nominal y retornamos el pct en null, y si no, lo hacemos al reves
    if($feedata["pctlimitfee"] == 0){
        $out->entry->fees->limit->pctfee = null;
        
        $out->entry->fees->limit->nmalfee = new stdClass();
        $out->entry->fees->limit->nmalfee->number = (float)$feedata['nmllimitfee'];
        $out->entry->fees->limit->nmalfee->formatted = number_format($feedata['nmllimitfee'],($action == 1 ? $out->entry->refcurrency->decimals : $out->entry->currency->decimals),",",".");
        
    }else{
        $out->entry->fees->limit->pctfee = new stdClass();
        $out->entry->fees->limit->pctfee->number = (float)$feedata['pctlimitfee'];
        $out->entry->fees->limit->pctfee->formatted = number_format($feedata['pctlimitfee'],2,",",".");
        
        $out->entry->fees->limit->nmalfee = null;
    }
    
    
    // Consultamos el minimo en la moneda base
    $sql = "SELECT minexchange ".
    "       FROM cmspreffees ".
    "       WHERE currencyid = ".$out->entry->refcurrency->id.
    "       AND usertype = ".$userdata["type"].
    "       LIMIT 1";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $min = $res->fetch_assoc();
    
    // Retornamos el valor
    $out->entry->min = new stdClass();
    $out->entry->min->number = (float)$min['minexchange'];
    $out->entry->min->formatted = numberFormatt($out->entry->min->number, $out->entry->refcurrency->decimals);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>