<?php
// app/api/markers/entry

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass;
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    $time = determinateTime($_GET["time"]);
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Contamos para ver que exista el par
    $sql = "SELECT COUNT(id) AS qty FROM pairs WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $row = $rs->fetch_assoc();
    
    if($row['qty'] == 0){
        badEnd('404',array('msg'=>'Par no encontrado'));
    }
    
    //Consultamos los datos requeridos
    $sql = "SELECT pairs.refcurrencyid AS pairsrefcurrency, ".
    "       currencies.name AS currencyname, currencies.symbol AS currencysymbol, ".
    "       currencies.id AS currencyid, pairs.id AS pairsid, ".
    "       currencies.decimals AS decimals ".
    "       FROM pairs, currencies ".
    "       WHERE pairs.status = 1 AND ".
    "       pairs.id = ".$id." AND ".
    "       currencies.id = pairs.currencyid ".
    "       GROUP BY pairs.id";
    
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $pairdata = $rs->fetch_assoc();
    
    //Ordenamos los valores
    $out->entry = new stdClass();
    $out->entry->id = (int) $id;
    
    //Consultamos la ultima transaccion de ese par
    $sql = "SELECT transactions.amount AS transactionamount FROM orders, transactions".
    "       WHERE orders.pairid = ".$out->entry->id.
    "       AND transactions.amount > 0".
    "       AND transactions.datecreated = (SELECT MAX(transactions.datecreated) FROM transactions WHERE orders.id = transactions.orderid) ".
    "       ORDER BY transactions.datecreated DESC";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
            
    $row = $res->fetch_assoc();
        
    $out->entry->last = new stdClass();
    $out->entry->last->number = (int)$row["transactionamount"];
    $out->entry->last->formatted = number_format($out->entry->last->number,$pairdata["decimals"],",",".");
    
    //Consultamos la suma de las transacciones
    $sql = "SELECT SUM(ABS(transactions.amount)) AS transactionamount FROM orders, transactions".
    "       WHERE orders.pairid = ".$out->entry->id.
    //"       AND transactions.amount > 0".
    "       AND transactions.datecreated >=  DATE_SUB(NOW(), INTERVAL 1 DAY) ".
    "       AND transactions.orderid IS NOT NULL".
    "       AND orders.id = transactions.orderid".
    "       AND (CASE WHEN orders.side = 2 THEN orders.accountid ELSE orders.paymentid END) = transactions.accountid";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
            
    $row = $res->fetch_assoc();
    
    $out->entry->volume = new stdClass();
    $out->entry->volume->number = (float)$row['transactionamount'];
    $out->entry->volume->formatted = number_format($out->entry->volume->number,$pairdata["decimals"],",",".");
    
    //Datos aleatorios debido a que no existen registros
    $out->entry->change = new stdClass();
    $out->entry->change->number = rand(1,90)/1.2;
    $out->entry->change->formatted = number_format($out->entry->change->number,2,",",".")."%";
        
    //Consultamos la ultima venta
    $sql = "SELECT quantity AS qty, id AS grouptx, ".
    "       price, side, id, total".
    "       FROM orders o".
    "       WHERE side = 1 AND canceled IS NULL AND pairid = ".$out->entry->id.
    "       AND (CASE WHEN o.side = 2 THEN o.quantity ELSE o.total END) > IF( ".
    "           (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id) IS NOT NULL, ".
    "       (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id), ".
    "       0 ".
    "       )".
    "       ORDER BY price ASC, date DESC ".
    "       LIMIT 1";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $res->fetch_assoc();
    
    $out->entry->bid = new stdClass();
    $out->entry->bid->number = (float)$row['price'];
    $out->entry->bid->formatted = number_format($out->entry->bid->number,$pairdata["decimals"],",",".");
    
    //Consultamos los datos de la ultima compra
    $sql = "SELECT quantity AS qty, id AS grouptx, ".
    "       price, side, id, total".
    "       FROM orders o".
    "       WHERE side = 2 AND canceled IS NULL AND pairid = ".$out->entry->id.
    "       AND (CASE WHEN o.side = 2 THEN o.quantity ELSE o.total END) > IF( ".
    "           (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id) IS NOT NULL, ".
    "       (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id), ".
    "       0 ".
    "       )".
    "       ORDER BY price ASC, date DESC ".
    "       LIMIT 1";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $res->fetch_assoc();
    
    $out->entry->ask = new stdClass();
    $out->entry->ask->number = (float)$row['price'];
    $out->entry->ask->formatted = number_format($out->entry->ask->number,$pairdata["decimals"],",",".");
    
    //Consultamos la orden mas barata durante todo 1 dia
    $sql = "SELECT MIN(price) AS lowprice ".
    "       FROM orders o".
    "       WHERE canceled IS NULL AND pairid = ".$out->entry->id.
    "       AND date >=  DATE_SUB(NOW(), INTERVAL 1 DAY) ".
    "       AND (CASE WHEN o.side = 2 THEN o.quantity ELSE o.total END) > IF( ".
    "           (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id) IS NOT NULL, ".
    "       (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id), ".
    "       0 ".
    "       )";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $res->fetch_assoc();
    
    $out->entry->low = new stdClass();
    $out->entry->low->number = (float)$row['lowprice'];
    $out->entry->low->formatted = number_format($out->entry->low->number,$pairdata["decimals"],",",".");
    
    //Consultamos la orden mas barata durante todo 1 dia
    $sql = "SELECT MAX(price) AS highprice ".
    "       FROM orders o".
    "       WHERE canceled IS NULL AND pairid = ".$out->entry->id.
    "       AND date >=  DATE_SUB(NOW(), INTERVAL 1 DAY) ".
    "       AND (CASE WHEN o.side = 2 THEN o.quantity ELSE o.total END) > IF( ".
    "           (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id) IS NOT NULL, ".
    "       (SELECT SUM(transactions.amount) ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND orders.id = o.id), ".
    "       0 ".
    "       )";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $res->fetch_assoc();
    
    $out->entry->high = new stdClass();
    $out->entry->high->number = (float)$row['highprice'];
    $out->entry->high->formatted = number_format($out->entry->high->number,$pairdata["decimals"],",",".");
    
    //Datos de moneda refcurrency
    $out->entry->currency = new stdClass();
    $out->entry->currency->id = (int)$pairdata["currencyid"];
    $out->entry->currency->dsc = $pairdata["currencyname"];
    $out->entry->currency->symbol = $pairdata["currencysymbol"];
        
    //Datos de currency
    $out->entry->refcurrency = new stdClass();
        
    $sql = "SELECT * FROM currencies WHERE id = ".$pairdata["pairsrefcurrency"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $row = $res->fetch_assoc();
        
    $out->entry->refcurrency->id = (int)$row["id"];
    $out->entry->refcurrency->dsc = $row["name"];
    $out->entry->refcurrency->symbol = $row["symbol"];
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    function determinateTime($time){
        $query = "";
        
        switch($time){
            case 1:
                $query = " AND orders.date >=  DATE_SUB(NOW(), INTERVAL 1 DAY) ";
                break;
            default:
                $query = " AND orders.date >=  DATE_SUB(NOW(), INTERVAL 1 DAY) ";
                break;
        }
        
        return $query;
    }
?>