<?php
// cms/api/preferences/savebalfees

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid",'levelid','currencyid','usertype');
    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"]);
    $levelid = mysqli_real_escape_string($db, $_GET['levelid']);
    $currencyid = mysqli_real_escape_string($db, $_GET['currencyid']);
    $usertype = mysqli_real_escape_string($db, $_GET['usertype']);
    $updateString = '';
    $pagomovilpctfee = null;
    
    if ($currencyid == 1) {
        $parmsob = array("pagomovilpctfee");
        if (!parametrosValidos($_GET, $parmsob))
            badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
            
        $pagomovilpctfee = mysqli_real_escape_string($db, $_GET['pagomovilpctfee']);
    }
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 56))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    
    // Validamos que recibimos los datos DEPOSIT
    if(isset($_GET['pctfeedeposit']) && $_GET['pctfeedeposit'] != '' && isset($_GET['nmlfeedeposit']) && $_GET['nmlfeedeposit'] != ''){
        badEnd('500',array('msg'=>'Debe ser enviado pctfeedeposit o nmlfeedeposit, no ambos'));
    }else if(isset($_GET['pctfeedeposit']) && $_GET['pctfeedeposit'] != ''){
        $updateString .= " pctfeedeposits = ".(validNumber($_GET['pctfeedeposit']) ? floatval($_GET['pctfeedeposit']) : (validNumberFormatted($_GET['pctfeedeposit']) ? parseFormattedNumber($_GET['pctfeedeposit'])  : 'NULL')).", ".
        "               nmlfeedeposits = NULL,";
    }else if(isset($_GET['nmlfeedeposit']) && $_GET['nmlfeedeposit'] != ''){
        $updateString .= " nmlfeedeposits = ".(validNumber($_GET['nmlfeedeposit']) ? floatval($_GET['nmlfeedeposit']) : (validNumberFormatted($_GET['nmlfeedeposit']) ? parseFormattedNumber($_GET['nmlfeedeposit'])  : 'NULL')).", ".
        "               pctfeedeposits = NULL,";
    }else{
        badEnd('500',array('msg'=>'Debe ser enviado pctfeedeposit o nmlfeedeposit'));
    }
    
    // Validamos que recibimos los datos WITHDRAW
    if(isset($_GET['pctfeewidthdraw']) && $_GET['pctfeewidthdraw'] != '' && isset($_GET['nmlfeewidthdraw']) && $_GET['nmlfeewidthdraw'] != ''){
        badEnd('500',array('msg'=>'Debe ser enviado pctfeewidthdraw o nmlfeewidthdraw, no ambos'));
    }else if(isset($_GET['pctfeewidthdraw']) && $_GET['pctfeewidthdraw'] != ''){
        $updateString .= " pctfeewithdrawals = ".(validNumber($_GET['pctfeewidthdraw']) ? floatval($_GET['pctfeewidthdraw']) : (validNumberFormatted($_GET['pctfeewidthdraw']) ? parseFormattedNumber($_GET['pctfeewidthdraw'])  : 'NULL')).", ".
        "               nmlfeewithdrawals = NULL,";
    }else if(isset($_GET['nmlfeewidthdraw']) && $_GET['nmlfeewidthdraw'] != ''){
        $updateString .= " nmlfeewithdrawals = ".(validNumber($_GET['nmlfeewidthdraw']) ? floatval($_GET['nmlfeewidthdraw']) : (validNumberFormatted($_GET['nmlfeewidthdraw']) ? parseFormattedNumber($_GET['nmlfeewidthdraw'])  : 'NULL')).", ".
        "               pctfeewithdrawals = NULL,";
    }else{
        badEnd('500',array('msg'=>'Debe ser enviado pctfeewidthdraw o nmlfeewidthdraw'));
    }
    
    // Validamos que recibimos los datos XFER
    if(isset($_GET['pctfeexfer']) && $_GET['pctfeexfer'] != '' && isset($_GET['nmlfeexfer']) && $_GET['nmlfeexfer'] != ''){
        badEnd('500',array('msg'=>'Debe ser enviado pctfeexfer o nmlfeexfer, no ambos'));
    }else if(isset($_GET['pctfeexfer']) && $_GET['pctfeexfer'] != ''){
        $updateString .= " pctfeexfer = ".(validNumber($_GET['pctfeexfer']) ? floatval($_GET['pctfeexfer']) : (validNumberFormatted($_GET['pctfeexfer']) ? parseFormattedNumber($_GET['pctfeexfer'])  : 'NULL')).", ".
        "               nmlfeesxfer = NULL,";
    }else if(isset($_GET['nmlfeexfer']) && $_GET['nmlfeexfer'] != ''){
        $updateString .= " nmlfeesxfer = ".(validNumber($_GET['nmlfeexfer']) ? floatval($_GET['nmlfeexfer']) : (validNumberFormatted($_GET['nmlfeexfer']) ? parseFormattedNumber($_GET['nmlfeexfer'])  : 'NULL')).", ".
        "               pctfeexfer = NULL,";
    }else{
        badEnd('500',array('msg'=>'Debe ser enviado pctfeexfer o nmlfeexfer'));
    }
    
    //Validamos que exista el registro a modificar
    $sql = "SELECT COUNT(levelid) AS qty ".
    "       FROM cmspreffees ".
    "       WHERE levelid = ".$levelid.
    "       AND currencyid = ".$currencyid.
    "       AND usertype = ".$usertype;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $row = $rs->fetch_assoc();
    
    //SI es igual a 0 no existe
    if($row['qty'] == 0){
        badEnd('204',array('msg'=>'Registro no encontrado'));
    }
    
    // Actualizamos los limites
    $sql = "UPDATE cmspreffees SET ".
    (($currencyid == 1) ? ("       pagomovilpct = ".$pagomovilpctfee.", ") : " ") . //Si es BS se actualiza el pago móvil (si no se pone la validación al no recibirlo da error 500)
    "       ".substr($updateString, 0, -1).
    "       WHERE levelid = ".$levelid.
    "       AND currencyid = ".$currencyid.
    "       AND usertype = ".$usertype;
    if (!$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));

    //Consultamos el nombre de la moneda para mostrarlo en la auditoria
    $sql = "SELECT 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 las comisiones para la moneda ".$row['name'].", Persona ".($usertype == 1 ? 'Natural' : 'Jurídica').", Nivel ".$levelid);  
    
    $out->levelid = (int)$levelid;
    $out->currencyid = (int)$currencyid;
    $out->usertype = (int)$usertype;
        
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>