<?php
// cms/api/rates/history
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array('sessionid', 'offset', 'numofrec', 'order');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out= new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $filter = '';
    $order = determinateOrder(mysqli_real_escape_string($db, $_GET['order']));
    $offset = mysqli_real_escape_string($db, $_GET['offset']);
    $numofrec = mysqli_real_escape_string($db, $_GET['numofrec']);
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 82))
        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
        $filter = " AND ( ";
        
        //Separamos el filtro por el simbolo +
        $filterEl = separateFilter(mysqli_real_escape_string($db, $_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){
                $filter .= " DATE(rates.createddate) = DATE('".$dateel."') ".
                "           OR curr.symbol LIKE '%".$el."%'".
                "           OR curr.name LIKE '%".$el."%'".
                "           OR rates.amount LIKE '%".$el."%'";
            }else{
                $filter .= " OR DATE(rates.createddate) = DATE('".$dateel."') ".
                "           OR curr.symbol LIKE '%".$el."%'".
                "           OR curr.name LIKE '%".$el."%'".
                "           OR rates.amount LIKE '%".$el."%'";
            }
        }
        
        
        $filter .= " ) ";
    }
    
    // Obtenemos la cantidad de registros
    $sql = "SELECT COUNT(rates.id) AS qty ".
    "       FROM rateshistory rates, currencies curr ".
    "       WHERE rates.currencyid = curr.id ".
    "       ".$filter.
    "       ".$order;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    $out->numofrecords = (int)$row['qty'];
        
    // Obtenemos los datos del id
    $sql = "SELECT rates.id AS id, ".
    "       rates.amount AS amount, ".
    "       rates.createddate AS createddate, ".
    "       curr.id AS currencyid, ".
    "       curr.name AS currencyname, ".
    "       curr.symbol AS currencysymbol, ".
    "       curr.decimals AS decimals ".
    "       FROM rateshistory rates, currencies curr ".
    "       WHERE rates.currencyid = curr.id ".
    "       ".$filter.
    "       ".$order.
    "       LIMIT ".$offset.", ".$numofrec;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    while($row = $rs->fetch_assoc()){
        $record = new stdClass();
        $record->id = (int)$row['id'];
    
        $record->datecreated = new stdClass();
        $record->datecreated->date = date('Y-m-d H:i', strtotime($row['createddate']));//$row['createddate'];
        $record->datecreated->formatted = date('d-m-Y - H:i A', strtotime($row['createddate']));
        
        $record->amount = new stdClass();
        $record->amount->number = (float)$row['amount'];
        //AJUSTO A 2 DECIMALES PORQUE SIEMPRE ES MONTOS EN VES. LA TASA REFLEJA EL EQUIVALEN DE 1 DE X MONEDA A BS
        $record->amount->formatted = numberFormatt($record->amount->number, 2);//$row['decimals']);
        
        $record->currency = new stdClass();
        $record->currency->id = (int)$row['currencyid'];
        $record->currency->name = $row['currencyname'];
        $record->currency->symbol = $row['currencysymbol'];
        $record->currency->decimals = (int)$row['decimals'];
        
        $records [] = $record;
    }
    
    $out->records = $records;
        
    $out->privileges = new stdClass();
    $out->privileges->create = tienePrivilegio($db, $sessionid, 79);
    $out->privileges->read = tienePrivilegio($db, $sessionid, 82);
    $out->privileges->update = tienePrivilegio($db, $sessionid, 80);
    $out->privileges->delete = tienePrivilegio($db, $sessionid, 81);

    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    function determinateOrder($id){
        $str = '';
        
        switch($id){
            case 1:
                $str = 'ORDER BY rates.createddate ASC';
                break;
            case 2:
                $str = 'ORDER BY rates.amount ASC';
                break;
            case 3:
                $str = 'ORDER BY curr.name ASC';
                break;
            case -1:
                $str = 'ORDER BY rates.createddate DESC';
                break;
            case -2:
                $str = 'ORDER BY rates.amount DESC';
                break;
            case -3:
                $str = 'ORDER BY curr.name DESC';
                break;
            default:
                $str = 'ORDER BY rates.id DESC';
        }
        
        return $str;
    }
?>