<?php
// app/api/markers/list

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","order","numofrec"); 
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass;
    $sessionid = $_GET["sessionid"];
    $order = determinateOrder($_GET["order"]);
    $numofrec = $_GET["numofrec"];
    $time = determinateTime($_GET["time"]);
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    //COMENTAMOS DEBIDO A QUE NO SE ESTAN REALIZANDO OPERACIONES, MIENTRAS DATA DUMMY
    
    //Contamos la cantidad de pares que
    $sql = "SELECT count(pairs.id) AS qty".
    "       FROM pairs ".
    "       WHERE pairs.status = 1 ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    //Retornamos la cantidad de pares
    $out->numofrecords = (int)$row["qty"];
    
    //Consultamos los datos requeridos
    $sql = "SELECT pairs.refcurrencyid AS pairsrefcurrency, ".
    "       currencies.name AS currencyname, currencies.symbol AS currencysymbol, ".
    "       currencies.icon AS currencyicon, ".
    "       currencies.id AS currencyid, pairs.id AS pairsid,".
    "       currencies.decimals AS currencydecimals ".
    "       FROM pairs, currencies ".
    "       WHERE pairs.id AND".
    "       pairs.status = 1 AND ".
    "       currencies.id = pairs.currencyid ".
    "       GROUP BY pairs.id".
    "       ".$order.
    "       LIMIT ".$numofrec;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    while($pairdata = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int) $pairdata["pairsid"];
        
        //Obtenemos la ultima transaccion realizada
        $sql = "SELECT transactions.amount AS transactionamount FROM orders, transactions, accounts".
        "       WHERE orders.pairid = ".$record->id.
        "       AND accounts.currencyid = ".$pairdata["currencyid"].
        "       AND accounts.id = transactions.accountid ".
        "       AND transactions.amount > 0".
        "       AND transactions.datecreated = (SELECT MAX(transactions.datecreated) FROM transactions WHERE orders.id = transactions.orderid) ".
        "       AND transactions.datecreated >= DATE_SUB(NOW(), INTERVAL 10 DAY) ".
        "       ORDER BY transactions.datecreated DESC";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $res->fetch_assoc();
        
        $record->last = new stdClass();
        $record->last->number = (float)$row["transactionamount"];
        $record->last->formatted = number_format($record->last->number,$pairdata["currencydecimals"],",",".");
        
        //Obtenemos la cantidad total que se ha hecho
        $sql = "SELECT SUM(transactions.amount) AS transactionamount FROM orders, transactions, accounts".
        "       WHERE orders.pairid = ".$record->id.
        "       AND accounts.currencyid = ".$pairdata["currencyid"].
        "       AND accounts.id = transactions.accountid ".
        "       AND transactions.amount > 0".
        "       AND TRANSACTIONs.orderid = orders.id".
        "       AND transactions.datecreated >= DATE_SUB(NOW(), INTERVAL 10 DAY)";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $res->fetch_assoc();
        
        $record->volume = new stdClass();
        $record->volume->number = (float)$row["transactionamount"];
        $record->volume->formatted = number_format($record->volume->number,$pairdata["currencydecimals"],",",".");
        
        //Consultamos la ultima transaccion hace 24horas
        $sql = "SELECT transactions.amount AS transactionamount FROM orders, transactions, accounts ".
        "       WHERE orders.pairid = ".$record->id.
        "       AND accounts.currencyid = ".$pairdata["currencyid"].
        "       AND accounts.id = transactions.accountid ".
        "       AND transactions.amount > 0 ".
        "       AND TRANSACTIONs.orderid = orders.id ".
        "       AND transactions.datecreated <= DATE_SUB(NOW(), INTERVAL 1 DAY) ".
        "       LIMIT 1";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $res->fetch_assoc();
        
        $record->change = new stdClass();
        if($record->last->number == 0){
            $record->change->number = 0;
            $record->change->formatted = number_format($record->change->number,2,",",".")."%";
        }else{
            $record->change->number = (($record->last->number - $row['transactionamount'])*100)/$record->last->number ;
            $record->change->formatted = number_format($record->change->number,2,",",".")."%";
        }
        
        //Datos de moneda currency
        $record->currency = new stdClass();
        $record->currency->id = (int)$pairdata["currencyid"];
        $record->currency->dsc = $pairdata["currencyname"];
        $record->currency->symbol = $pairdata["currencysymbol"];
        $record->currency->icon = $pairdata["currencyicon"];
        $record->currency->decimals = (int)$pairdata["currencydecimals"];
        
        //Datos de refcurrency
        $record->refcurrency = new stdClass();
        
        $sql = "SELECT * FROM currencies WHERE id = ".$pairdata["pairsrefcurrency"];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
    
        $row = $res->fetch_assoc();
        
        $record->refcurrency->id = (int)$row["id"];
        $record->refcurrency->dsc = $row["name"];
        $record->refcurrency->symbol = $row["symbol"];
        $record->refcurrency->icon = $row["icon"];
        $record->refcurrency->decimals = (int)$row["decimals"];
        
        $records [] = $record;
    }
    
    $out->records = $records;
    
    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 = Nombre
    *   2 = Last
    *   3 = Porcentaje
    *   4 = Volumen
    */
    function determinateOrder($order){
        $str = "";
        
        switch($order){
            case 1:
                $str = "currencies.name ASC";
                break;
            /*case 2:
                $str = "orders.id DESC";
                break;
            case 3:
                $str = "percent ASC";
                break;
            case 4:
                $str = "volume ASC";
                break;*/
            default:
                $str = "pairs.id ASC";
                break;
        }
        
        return " ORDER BY ".$str;
    }
    
    function determinateTime($time){
        $query = "";
        
        switch($time){
            case 1:
                $query = " DATE_SUB(NOW(), INTERVAL 1 DAY) ";
                break;
            default:
                $query = " DATE_SUB(NOW(), INTERVAL 1 DAY) ";
                break;
        }
        
        return $query;
    }
?>