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

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../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 = $_GET["sessionid"];
    $currencyid = $_GET['currencyid'];
    $usertype = $_GET['usertype'];
    $mindeposit = $_GET['mindeposit'];
    $minexchange = $_GET['minexchange'];
    $minwithdraw = $_GET['minwithdraw'];
    $minxfer = $_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"=>$db->error.$sql));
    
    $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"=>$db->error.$sql));
        
    $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"=>$db->error.$sql));
    
    $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();
?>
