<?php
// cms/api/exchanges/list

    header("Content-Type: application/json;");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'offset','numofrecords');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = $_GET["sessionid"];
    $offset = $_GET['offset'];
    $numofrecords = $_GET['numofrecords'];
    $filter = '';
    $order = determinateOrder($_GET['order']);
    $daterange = '';
    $type = '';
    $pairid = '';
    //Filtros para usuarios
    $filterCompany = '';
    $filterPerson = '';
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 42))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    //En caso de que el filter sea enviado, se construye el query
    if(isset($_GET["filter"]) && $_GET["filter"] != ""){
        // Iniciamos la cadena del query
        $filterCompany = " AND ( ";
        $filterPerson = " AND ( ";
        
        //Separamos el filtro por el simbolo +
        $filterEl = separateFilter($_GET["filter"]);
        
        //Recorremos cada elemento
        foreach($filterEl as $index => $el){
            
            //Si la fecha tiene / lo partimos en mil
            if(strpos($el, '/') !== false){
                $dateelements = explode("/",$el);
                
                foreach($dateelements as $i => $element){
                    if($i == 0){
                        $dateConverted .= $element;
                    }else{
                        $dateConverted .= "-".$element;
                    }
                }
                
                $dateel = strftime("%Y-%m-%d", strtotime($dateConverted));
            }else{
                $dateel = strftime("%Y-%m-%d", strtotime($el));
            }
            
            if($index == 0){
                $filterCompany .= " users.usr LIKE '%".$el."%'".
                "                   ".( validNumber($el) ? " OR t.txid = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR t.txid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR t.orderid = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR t.orderid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.id = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR orders.id = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.price = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR orders.price = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".parseFormattedNumber($el)."'" : "")).
                "                   OR usercompanies.name LIKE '%".$el."%' ".
                "                   OR DATE(t.datecreated) = DATE('".$dateel."') ".
                "                   OR (SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc ".
                "                       FROM currencies, pairs par ".
                "                       LEFT JOIN currencies cursec ON cursec.id = par.currencyid ".
                "                       WHERE par.refcurrencyid = currencies.id ".
                "                       AND par.id = orders.pairid) LIKE '".$el."%'".
                "                   OR IF(orders.type = 1, IF(orders.side = 2, 'Compra', 'Venta'), IF(orders.side = 1, 'Compra', 'Venta')) LIKE '".$el."%' ";
                
                $filterPerson .= " users.usr LIKE '%".$el."%'".
                "                   ".( validNumber($el) ? " OR t.txid = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR t.txid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR t.orderid = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR t.orderid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.id = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR orders.id = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.price = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR orders.price = '".parseFormattedNumber($el)."'" : "")).
                "                   OR userpersons.fname LIKE '%".$el."%' ".
                "                   OR DATE(t.datecreated) = DATE('".$dateel."')".
                "                   OR IF(orders.side = 1, 'Venta', 'Compra' ) LIKE '".$el."' ".
                "                   OR (SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc ".
                "                       FROM currencies, pairs par ".
                "                       LEFT JOIN currencies cursec ON cursec.id = par.currencyid ".
                "                       WHERE par.refcurrencyid = currencies.id ".
                "                       AND par.id = orders.pairid) LIKE '".$el."%'".
                "                   OR IF(orders.type = 1, IF(orders.side = 2, 'Compra', 'Venta'), IF(orders.side = 1, 'Compra', 'Venta')) LIKE '".$el."%' ";
            }else{
                
                $filterCompany .= " OR users.usr LIKE '%".$el."%'".
                "                   ".( validNumber($el) ? " OR t.txid = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR t.txid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR t.orderid = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR t.orderid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.id = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR orders.id = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.price = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR orders.price = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".floatval($el)."'" : (validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".parseFormattedNumber($el)."'" : "")).
                "                   OR usercompanies.name LIKE '%".$el."%' ".
                "                   OR DATE(t.datecreated) = DATE('".$dateel."') ".
                "                   OR (SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc ".
                "                       FROM currencies, pairs par ".
                "                       LEFT JOIN currencies cursec ON cursec.id = par.currencyid ".
                "                       WHERE par.refcurrencyid = currencies.id ".
                "                       AND par.id = orders.pairid) LIKE '".$el."%'".
                "                   OR IF(orders.type = 1, IF(orders.side = 2, 'Compra', 'Venta'), IF(orders.side = 1, 'Compra', 'Venta')) LIKE '".$el."%' ";
                
                $filterPerson .= " OR users.usr LIKE '%".$el."%'".
                "                   ".( validNumber($el) ? " OR t.txid = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR t.txid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR t.orderid = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR t.orderid = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.id = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR orders.id = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount) * orders.price) = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR ABS(IF(orders.side = 2, t.amount, tx.amount)) = '".parseFormattedNumber($el)."'" : "")).
                "                   ".( validNumber($el) ? " OR orders.price = '".floatval($el)."'" : ( validNumberFormatted($el) ? " OR orders.price = '".parseFormattedNumber($el)."'" : "")).
                "                   OR userpersons.fname LIKE '%".$el."%' ".
                "                   OR DATE(t.datecreated) = DATE('".$dateel."')".
                "                   OR IF(orders.side = 1, 'Venta', 'Compra' ) LIKE '".$el."' ".
                "                   OR (SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc ".
                "                       FROM currencies, pairs par ".
                "                       LEFT JOIN currencies cursec ON cursec.id = par.currencyid ".
                "                       WHERE par.refcurrencyid = currencies.id ".
                "                       AND par.id = orders.pairid) LIKE '".$el."%'".
                "                   OR IF(orders.type = 1, IF(orders.side = 2, 'Compra', 'Venta'), IF(orders.side = 1, 'Compra', 'Venta')) LIKE '".$el."%' ";
            }
        }
        
        $filterCompany .= " ) ";
        $filterPerson .= " ) ";
    }
    
    //En caso de que el pairid sea enviado, se construye el query
    if(isset($_GET["pairid"]) && $_GET["pairid"] != ""){
        $pairid = "AND orders.pairid = ".$_GET['pairid'];
    }
    
    //En caso de que el pairid sea enviado, se construye el query
    if(isset($_GET["daterange"]) && $_GET["daterange"] != ""){
        $daterange = determinateRange($_GET['daterange']);
    }
    
    //En caso de que el type sea enviado, se construye el query
    if(isset($_GET['type']) && $_GET['type'] != ""){
        $type = "AND IF(orders.type = 1, IF(orders.side = 1, 2, 1),orders.side) = ".$_GET['type'];
    }
    
    //Consultamos la cantidad total
    $sql = "SELECT SUM(num) AS qty FROM (".
    "   SELECT COUNT(orders.id) AS num ".
    "       FROM orders, accounts, users, userpersons, transactions t ".
    "           LEFT JOIN transactions tx ".
    "               ON t.orderid = tx.orderid ".
    "               AND t.txid = tx.txid ".
    "               AND tx.amount < 0 ".
    "               AND tx.dsc NOT LIKE 'Comisi%' ".
    "           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 t.id = t.txid ".
    "       AND t.dsc NOT LIKE 'Comisi%' ".
    "       AND accounts.id = orders.accountid ".
    "       AND accounts.userid = users.id ".
    "       AND userpersons.usrid = users.id ".
    "       ".$daterange.
    "       ".$pairid.
    "       ".$type.
    "       ".$filterPerson.
    "".
    "           UNION ALL ".
    "".
    "   SELECT COUNT(orders.id) AS num ".
    "       FROM orders, accounts, users, usercompanies, transactions t ".
    "           LEFT JOIN transactions tx ".
    "               ON t.orderid = tx.orderid ".
    "               AND t.txid = tx.txid ".
    "               AND tx.amount < 0 ".
    "               AND tx.dsc NOT LIKE 'Comisi%'".
    "           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 t.id = t.txid ".
    "       AND t.dsc NOT LIKE 'Comisi%'".
    "       AND accounts.id = orders.accountid ".
    "       AND accounts.userid = users.id ".
    "       AND usercompanies.usrid = users.id ".
    "       ".$daterange.
    "       ".$pairid.
    "       ".$type.
    "       ".$filterCompany.
    "       ) num";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    $row = $rs->fetch_assoc();
    $out->numofrecords = (int)$row['qty'];
    
    //Consultamos los detalles requeridos
    $sql = "SELECT orders.id AS orderid, ".
    "       orders.quantity AS orderqty, ".
    "       IF(orders.type = 1, orders.side, IF(orders.side = 1, 2, 1)) AS orderside, ".
    "       (SELECT ord.price FROM orders ord ".
    "       WHERE ord.type = 2 AND (ord.id = t.orderid OR ord.id = txother.orderid)) AS orderprice, ".
    "       orders.type AS ordertype, ".
    "       orders.pairid AS orderpair, ".
    "       orders.total AS ordertotal, ".
    "       t.id AS txid, ".
    "       t.txid AS exchangeid, ".
    "       t.orderid AS txotherorderid, ".
    "       t.datecreated AS datecreated, ".
    "       ABS(IF(orders.side = 2, t.amount, tx.amount)) AS qty, ".
    "       (IF(orders.side = 2, t.amount, tx.amount) * orders.price) AS totally, ".
    "       users.id AS usrid, ".
    "       users.usr AS usr, ".
    "       users.type AS usertype, ".
    "       CONCAT(userpersons.fname,' ', userpersons.sname) AS name, ".
    "       CONCAT(userpersons.flastname, ' ', userpersons.slastname) AS secondname ".
    "       FROM orders, accounts, users, userpersons, transactions t ".
    "           LEFT JOIN transactions tx ".
    "               ON t.orderid = tx.orderid ".
    "               AND t.txid = tx.txid ".
    "               AND tx.amount < 0 ".
    "               AND tx.dsc NOT LIKE 'Comisi%'".
    "           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 t.id = t.txid ".
    "       AND t.dsc NOT LIKE 'Comisi%'".
    "       AND accounts.id = orders.accountid ".
    "       AND accounts.userid = users.id ".
    "       AND userpersons.usrid = users.id ".
    "       ".$daterange.
    "       ".$pairid.
    "       ".$type.
    "       ".$filterPerson.
    "       GROUP BY t.txid".
    "".
    "           UNION ALL ".
    "".
    "       SELECT orders.id AS orderid, ".
    "       orders.quantity AS orderqty, ".
    "       IF(orders.type = 1, orders.side, IF(orders.side = 1, 2, 1)) AS orderside, ".
    "       (SELECT ord.price FROM orders ord ".
    "       WHERE ord.type = 2 AND (ord.id = t.orderid OR ord.id = txother.orderid)) AS orderprice, ".
    "       orders.type AS ordertype, ".
    "       orders.pairid AS orderpair, ".
    "       orders.total AS ordertotal, ".
    "       t.id AS txid, ".
    "       t.txid AS exchangeid, ".
    "       t.orderid AS txotherorderid, ".
    "       t.datecreated AS datecreated, ".
    "       ABS(IF(orders.side = 2, t.amount, tx.amount)) AS qty, ".
    "       (IF(orders.side = 2, t.amount, tx.amount) * orders.price) AS totally, ".
    "       users.id AS usrid, ".
    "       users.usr AS usr, ".
    "       users.type AS usertype, ".
    "       usercompanies.name AS name, ".
    "       usercompanies.comercialname AS secondname ".
    "       FROM orders, accounts, users, usercompanies, transactions t ".
    "           LEFT JOIN transactions tx ".
    "               ON t.orderid = tx.orderid ".
    "               AND t.txid = tx.txid ".
    "               AND tx.amount < 0 ".
    "               AND tx.dsc NOT LIKE 'Comisi%'".
    "           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 t.id = t.txid ".
    "       AND t.dsc NOT LIKE 'Comisi%'".
    "       AND accounts.id = orders.accountid ".
    "       AND accounts.userid = users.id ".
    "       AND usercompanies.usrid = users.id ".
    "       ".$daterange.
    "       ".$pairid.
    "       ".$type.
    "       ".$filterCompany.
    "       GROUP BY t.txid".
    "       ".$order.
    "       LIMIT ".$offset.", ".$numofrecords;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
        while($row = $rs->fetch_assoc()){
            $record = new stdClass();
            $record->id = (int)$row['exchangeid'];
            
            $record->date = new stdClass();
            $record->date->cannonical = date("Y-m-d H:i:s", strtotime($row['datecreated']));
            $record->date->formatted = date("d/m/Y H:i", strtotime($row['datecreated']));
            
            $record->orderbuy = $row['ordertype'] == 1 && $row['orderside'] == 1 ? (int)$row['orderid'] : (int)$row['txotherorderid'];
            $record->ordersell = $row['orderid'] != $record->orderbuy ? (int)$row['orderid'] : (int)$row['txotherorderid'];
            
            $record->side = new stdClass();
            $record->side->id = (int)$row['orderside'];
            $record->side->dsc = $record->side->id == 1 ? 'Venta' : 'Compra';
            
            $record->type = new stdClass();
            $record->type->id = (int)$row['ordertype'];
            $record->type->dsc = $record->type->id == 1 ? 'Market' : 'Limit' ;
            
            $record->pair = new stdClass();
            $record->pair->id = (int)$row['orderpair'];
            
            //Consultamos el nombre de la moneda ref
            $sql = "SELECT currencies.symbol AS symbol ".
            "       FROM currencies, pairs ".
            "       WHERE pairs.id = ".$row["orderpair"].
            "       AND pairs.refcurrencyid = currencies.id ".
            "       LIMIT 1";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $refcurrency = $res->fetch_assoc();
        
            //Consultamos el nombre de la moneda base
            $sql = "SELECT currencies.symbol AS symbol ".
            "       FROM currencies, pairs ".
            "       WHERE pairs.id = ".$row['orderpair'].
            "       AND pairs.currencyid = currencies.id ".
            "       LIMIT 1";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $currency = $res->fetch_assoc();
            
            $record->pair->dsc = $refcurrency['symbol'].'/'.$currency['symbol'];
            
            $record->user = new stdClass();
            $record->user->id = (int)$row['usrid'];
            $record->user->usr = $row['usr'];
            
            if($row["usertype"] == 1){
                $record->user->fullname = $row['name'].($row['secondname'] == "" ? "" : " ".$row['secondname']);
            }else{
                $record->user->fullname = $row['name'].($row['secondname'] == "" ? "" : " / ".$row['secondname']);
            }
            
            //Ordenamos el porcentaje
            $record->filled = new stdClass();
            $record->filled->number = (float)number_format((($row['qty'] * $row['orderprice'])*100)/$row['ordertotal'], 2);
            $record->filled->formatted = numberFormatt($record->filled->number, 2).'%';
            
            //Obtenemos los datos del par para obtener los decimales base
            $sql = "SELECT pairs.refcurrencyid AS pairscurrency, ".
            "       currencies.decimals AS currencydecimals ".
            "       FROM pairs, currencies ".
            "       WHERE pairs.id AND".
            "       pairs.status = 1 AND ".
            "       pairs.id = ".$row['orderpair']." AND ".
            "       currencies.id = pairs.currencyid ".
            "       GROUP BY pairs.id";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $currencydata = $res->fetch_assoc();
        
            //Obtenemos los datos del par para obtener los decimales ref
            $sql = "SELECT pairs.refcurrencyid AS pairscurrency, ".
            "       currencies.decimals AS currencydecimals ".
            "       FROM pairs, currencies ".
            "       WHERE pairs.id AND".
            "       pairs.status = 1 AND ".
            "       pairs.id = ".$row['orderpair']." AND ".
            "       currencies.id = pairs.refcurrencyid ".
            "       GROUP BY pairs.id";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $refcurrencydata = $res->fetch_assoc();
        
            $record->price = new stdClass();
            $record->price->number = (float)$row['orderprice'];
            $record->price->formatted = number_format($record->price->number,$currencydata['currencydecimals'],",",".");
        
            $record->qty = new stdClass();
            $record->qty->number = (float)abs($row['qty']);
            $record->qty->formatted = number_format($record->qty->number,$refcurrencydata['currencydecimals'],",",".");
            
            //$record->testing = $row;
            $record->total = new stdClass();
            $record->total->number = (float) $record->qty->number * $record->price->number;
            $record->total->formatted = number_format($record->total->number,$currencydata['currencydecimals'],",",".");
        
            $exchanges [] = $record;
        }
        
    $out->records = $exchanges;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para determinar el orden de los valores
    *   Esta recibe un parametro y a partir de el retorna:
    *   1 = Fecha ASCENDENTE
    *   2 = Usuario ASCENDENTE
    *   3 = Email ASCENDENTE
    *   4 = Moneda ASCENDENTE
    *   6 = Monto ASCENDENTE
    *   7 = Tipo ASCENDENTE
    *   -1 = Fecha DESCENDENTE
    *   -2 = Usuario DESCENDENTE
    *   -3 = Email DESCENDENTE
    *   -4 = Moneda DESCENDENTE
    *   -6 = Monto DESCENDENTE
    *   -7 = Tipo DESCENDENTE
    */
    function determinateOrder($order){
        $str = '';
        
        switch($order){
            case 1:
                $str = ' ORDER BY datecreated ASC, exchangeid DESC';
                break;
            case 2:
                $str = ' ORDER BY name ASC, exchangeid DESC';
                break;
            case 3:
                $str = ' ORDER BY usr ASC, exchangeid DESC';
                break;
            case 4:
                $str = ' ORDER BY orderpair ASC, exchangeid DESC';
                break;
            case 6:
                $str = ' ORDER BY qty ASC, exchangeid DESC';
                break;
            case 7:
                $str = ' ORDER BY orderside ASC, exchangeid DESC';
                break;
            case 8:
                $str = ' ORDER BY totally ASC, exchangeid DESC';
                break;
            case -1:
                $str = ' ORDER BY datecreated DESC, exchangeid DESC';
                break;
            case -2:
                $str = ' ORDER BY name DESC, exchangeid DESC';
                break;
            case -3:
                $str = ' ORDER BY usr DESC, exchangeid DESC';
                break;
            case -4:
                $str = ' ORDER BY orderpair DESC, exchangeid DESC';
                break;
            case -6:
                $str = ' ORDER BY qty DESC, exchangeid DESC';
                break;
            case -7:
                $str = ' ORDER BY orderside DESC, exchangeid DESC';
                break;
            case -8:
                $str = ' ORDER BY totally DESC, exchangeid DESC';
                break;
            default:
                $str = ' ORDER BY datecreated DESC, exchangeid DESC';
                break;
        }
        
        return $str;
    }
    
    /*  Funcion para determinar el orden de los resultados
    *   Esta recibe un parametro que retorna dependiendo del valor:
    *   1 = Hoy
    *   2 = Ultimos 7 Dias
    *   3 = Ultimos 30 dias
    *   4 = Ultimos 3 meses
    *   5 = Ultimos 6 meses
    */
    function determinateRange($range){
        $str = "";
        
        switch($range){
            case 1:
                $str = " AND DATE(t.datecreated) >= DATE_SUB(NOW(), INTERVAL 1 DAY)";
                break;
            case 2:
                $str = " AND DATE(t.datecreated) >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
                break;
            case 3:
                $str = " AND DATE(t.datecreated) >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
                break;
            case 4:
                $str = " AND DATE(t.datecreated) >= DATE_SUB(NOW(), INTERVAL 90 DAY)";
                break;
            case 5:
                $str = " AND DATE(t.datecreated) >= DATE_SUB(NOW(), INTERVAL 6 MONTH)";
                break;
            default: 
                badEnd("500", array("msg"=>"El parametro fecha solo puede ser 0, 1, 2, 3, 4 o 5"));
                break;
        }
        
        return $str;
    }
?>
