<?php
// cms/api/preferences/savemins

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'currencyid','usertype','mindeposit','minexchange','minwithdraw','minxfer');
    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"]);
    $currencyid = mysqli_real_escape_string($db, $_GET['currencyid']);
    $usertype = mysqli_real_escape_string($db, $_GET['usertype']);
    $mindeposit = mysqli_real_escape_string($db, $_GET['mindeposit']);
    $minexchange = mysqli_real_escape_string($db, $_GET['minexchange']);
    $minwithdraw = mysqli_real_escape_string($db, $_GET['minwithdraw']);
    $minxfer = mysqli_real_escape_string($db, $_GET['minxfer']);
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    
    // Validamos que exista los registros de la moneda
    $sql = "SELECT COUNT(levelid) AS qty FROM cmspreffees".
    "       WHERE currencyid = ".$currencyid.
    "       AND usertype = ".$usertype;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $row = $rs->fetch_assoc();
    
    // SI es = 0 no existen
    if($row['qty'] == 0){
        badEnd("204", array("msg"=>'Registro no existe'));
    }
    
    // Actualizamos los minimos
    $sql = "UPDATE cmspreffees SET ".
    "       mindeposit = ".$mindeposit.", ".
    "       minexchange = ".$minexchange.", ".
    "       minwithdraw = ".$minwithdraw.", ".
    "       minxfer = ".$minxfer.
    "       WHERE currencyid = ".$currencyid.
    "       AND usertype = ".$usertype;
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $out->currencyid = (int)$currencyid;
    $out->usertype = (int)$usertype;
    
    //Consultamos los datos de la moneda para la auditoria
    $sql = "SELECT id, name FROM currencies WHERE id = ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $row = $rs->fetch_assoc();
    
    //auditoria
    setAudit($db, "PREFERENCIAS", $sessionid, "CMS", "Se actualizaron los montos mínimos para ".$row['name'].", Persona ".($usertype == 1 ? 'Natural' : 'Jurídica'));   
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
