<?php ini_set("memory_limit","-1")?>
<?php
// cms/api/exchanges/reportexchanges

    header("Content-Type: application/csv;");
    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 = t.orderid ".
    "       AND t.amount > 0 ".
    "       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 = t.orderid ".
    "       AND t.amount > 0 ".
    "       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, ".
    "       orders.price 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, ".
    "       orders.price 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['orderside'] == 1 ? (int)$row['orderid'] : (int)$row['txotherorderid'];
        $record->ordersell = $row['orderside'] == 2 ? (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';
        
        //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();
        
        //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();
        
        $csvarray [] = array('fecha'=>$record->date->formatted,
            'ref'=>$row['exchangeid'],
            'par'=>$refcurrency['symbol'].'/'.$currency['symbol'],
            'tipo'=>($record->side->dsc),
            'orderbuy'=>$record->orderbuy,
            'ordersell'=>$record->ordersell,
            'cantidad'=>numberFormatt(abs($row['qty']),$refcurrencydata['currencydecimals']),
            'precio'=>numberFormatt($row['orderprice'],$currencydata['currencydecimals']),
            'total'=>numberFormatt(abs($row['qty']) * $row['orderprice'],$currencydata['currencydecimals'],",",".")
        );
    }
        
    $BOM = "\xEF\xBB\xBF"."\xEF\xBB\xBF";
    $fp = fopen('php://output', 'wb');
    fwrite($fp, $BOM);
    
    $line = array('FECHA','REF','PAR','TIPO','O. DE VENTA','O. DE COMPRA','CANTIDAD','PRECIO','TOTAL');
    
    fputcsv($fp, $line, ';', '"');
    
    foreach($csvarray as $arr){
        fputcsv($fp,$arr,';');
    }
    
    fclose($fp);
    
    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, orderid DESC';
                break;
            case 2:
                $str = ' ORDER BY name ASC, orderid DESC';
                break;
            case 3:
                $str = ' ORDER BY usr ASC, orderid DESC';
                break;
            case 4:
                $str = ' ORDER BY orderpair ASC, orderid DESC';
                break;
            case 6:
                $str = ' ORDER BY qty ASC, orderid DESC';
                break;
            case 7:
                $str = ' ORDER BY orderside ASC, orderid DESC';
                break;
            case -1:
                $str = ' ORDER BY datecreated DESC, orderid DESC';
                break;
            case -2:
                $str = ' ORDER BY name DESC, orderid DESC';
                break;
            case -3:
                $str = ' ORDER BY usr DESC, orderid DESC';
                break;
            case -4:
                $str = ' ORDER BY orderpair DESC, orderid DESC';
                break;
            case -6:
                $str = ' ORDER BY qty DESC, orderid DESC';
                break;
            case -7:
                $str = ' ORDER BY orderside DESC, orderid DESC';
                break;
            default:
                $str = ' ORDER BY datecreated DESC, orderid 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;
    }
?>
