<?php
// cms/api/rates/entry
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array('sessionid','id');
    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"]);
    $id = mysqli_real_escape_string($db, $_GET["id"]);
    
    //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"));
        
    // Validamos que exista
    $sql = "SELECT COUNT(id) AS qty FROM rateshistory WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    // Retornamos 404 cuando la busqueda no obtiene resutados
    if($row["qty"] == 0){
        badEnd("404", array("msg"=>"No se encuentra el registro"));
    }
        
    // Obtenemos los datos del id
    $sql = "SELECT * FROM rateshistory WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    $out->entry = new stdClass();
    
    $out->entry->id = (int)$row['id'];
    
    $out->entry->datecreated = new stdClass();
    $out->entry->datecreated->date = $row['createddate'];
    $out->entry->datecreated->formatted = date('d-m-Y - H:i A', strtotime($row['createddate']));

    // Obtenemos los datos de la moneda
    $sql = "SELECT id, name, symbol, decimals FROM currencies WHERE id = ".$row['currencyid'];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currencydata = $rs->fetch_assoc();
    
    $out->entry->amount = new stdClass();
    $out->entry->amount->number = (float)$row['amount'];
    $out->entry->amount->formatted = numberFormatt($out->entry->amount->number, $currencydata['decimals']);
    
    $out->entry->currency = new stdClass();
    $out->entry->currency->id = (int)$currencydata['id'];
    $out->entry->currency->name = $currencydata['name'];
    $out->entry->currency->symbol = $currencydata['symbol'];
    $out->entry->currency->decimals = (int)$currencydata['decimals'];
    
    $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();
?>