<?php 
    //cms/api/pairs/list

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array('sessionid','order','offset','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']);
    $offset = $_GET['offset'];
    $numofrec = $_GET['numofrec'];
    $filter = '';
    
    //Validamos la session
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 61))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    // Si recibimos el filter, armamos el query
    if(isset($_GET['filter']) && $_GET['filter'] != ''){
        // Iniciamos la cadena del query
        $filter = " AND ( ";
        
        //Separamos el filtro por el simbolo +
        $filterEl = separateFilter($_GET["filter"]);
        
        //Recorremos cada elemento
        foreach($filterEl as $index => $el){
            if($index == 0){
                $filter .= " currencies.name LIKE '%".$el."%' ".
                "       OR currencies.symbol LIKE '%".$el."%' ".
                "       OR curr.name LIKE '%".$el."%' ".
                "       OR curr.symbol LIKE '%".$el."%' ".
                "       OR CONCAT(curr.symbol,'/',currencies.symbol) LIKE '%".$el."%' ".
                "       OR IF(par.status = 1, 'Activo', 'Inactivo') LIKE '%".$el."%' ";
            }else{
                $filter .= " OR currencies.name LIKE '%".$el."%' ".
                "       OR currencies.symbol LIKE '%".$el."%' ".
                "       OR curr.name LIKE '%".$el."%' ".
                "       OR curr.symbol LIKE '%".$el."%' ".
                "       OR CONCAT(curr.symbol,'/',currencies.symbol) LIKE '%".$el."%' ".
                "       OR IF(par.status = 1, 'Activo', 'Inactivo') LIKE '%".$el."%' ";
            }
        }
        
        $filter .= " ) ";
    }
    
    // COnsultamos la cantidad de registros
    $sql = "SELECT COUNT(par.id) AS qty ".
    "       FROM currencies, pairs par ".
    "       LEFT JOIN currencies curr ON par.refcurrencyid = curr.id".
    "       WHERE currencies.id = par.currencyid ".
    "       ".$filter;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    // Retornamos la cantidad de registros
    $out->numofrecords = (int)$row['qty'];
    
    // Consultamos los registros a detalle
    $sql = "SELECT currencies.name AS currencyname, currencies.symbol AS currencysymbol, ".
    "       currencies.icon AS currencyicon, ".
    "       currencies.id AS currencyid, par.id AS pairsid,".
    "       par.status AS status, ".
    "       currencies.decimals AS currencydecimals, ".
    "       curr.name AS currencyrefname, curr.symbol AS currencyrefsymbol, ".
    "       curr.icon AS currencyreficon, ".
    "       curr.id AS currencyrefid, curr.decimals AS currencyrefdecimals ".
    "       FROM currencies, pairs par ".
    "       LEFT JOIN currencies curr ON par.refcurrencyid = curr.id".
    "       WHERE currencies.id = par.currencyid ".
    "       ".$filter.
    "       GROUP BY par.id".
    "       ".$order;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    while($pairdata = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int) $pairdata["pairsid"];
        
        $record->status = new stdClass();
        $record->status->id = (int)$pairdata["status"];
        $record->status->dsc = $record->status->id == 1 ? 'Activo' : 'Inactivo';
        
        //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();
        $record->refcurrency->id = (int)$pairdata["currencyrefid"];
        $record->refcurrency->dsc = $pairdata["currencyrefname"];
        $record->refcurrency->symbol = $pairdata["currencyrefsymbol"];
        $record->refcurrency->icon = $pairdata["currencyreficon"];
        $record->refcurrency->decimals = (int)$pairdata["currencyrefdecimals"];
        
        $record->dsc = $record->refcurrency->symbol .'/'.$record->currency->symbol;
        $records [] = $record;
    }
    
    $out->records = $records;
    
    // Privilegios del usuario
    $privileges = new stdClass();
    $privileges->create = tienePrivilegio($db, $sessionid, 58);
    $privileges->read = tienePrivilegio($db, $sessionid, 61);
    $privileges->update = tienePrivilegio($db, $sessionid, 59);
    $privileges->delete = tienePrivilegio($db, $sessionid, 60);
    $out->privileges = $privileges;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para determinar el orden de los resultados, retorna si:
    *   1 = moneda izquierda ASC
    *   2 = moneda derecha ASC
    *   3 = staus ASC
    *   4 = id ASC
    *   -1 = moneda izquierda DESC
    *   -2 = moneda derecha DESC
    *   -3 = staus DESC
    *   -4 = id DESC
    */
    function determinateOrder($order){
        $str = '';
        
        switch($order){
            case 1:
                $str = ' ORDER BY curr.name ASC';
                break;
            case 2:
                $str = ' ORDER BY currencies.name ASC';
                break;
            case 3:
                $str = ' ORDER BY par.status ASC';
                break;
            case 4:
                $str = ' ORDER BY par.id ASC';
                break;
            case -1:
                $str = ' ORDER BY curr.name DESC';
                break;
            case -2:
                $str = ' ORDER BY currencies.name DESC';
                break;
            case -3:
                $str = ' ORDER BY par.status  DEC';
                break;
            case -4:
                $str = ' ORDER BY par.id DESC';
                break;
        }
        
        return $str;
    }
?>