<?php
// cms/api/preferences/entry
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid");
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $out->entry = new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    
    //Validamos que la session del usuario sea valida para continuar  
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 57))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
    
    // Consultamos las configuraciones de pago movil
    $sql = "SELECT pagomovilbanks, pagomovildefaults ".
    "       FROM cmspreferences";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    $out->entry->pagomovil = new stdClass();
    
    // Convertimos la data en objetos para retornarlos
    $banks = json_decode($row['pagomovilbanks'], true);
    $banks = $banks['banks'];
    $out->entry->pagomovil->banks = $banks;
    
    $default = json_decode($row['pagomovildefaults'], true);
    $default = $default['default'];
    $out->entry->pagomovil->default = $default;
        
    // Consultamos las configuraciones de PAY
    $sql = "SELECT cmspreffees.*, currencies.decimals AS decimals ".
    "       FROM cmspreffees, currencies".
    "       WHERE cmspreffees.currencyid = -1 ".
    "       AND currencies.id = cmspreffees.currencyid";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    $out->entry->pay = new stdClass();
    
    // Tiempo de operacion del cron
    $out->entry->pay->maxtimereverse = new stdClass();
    $out->entry->pay->maxtimereverse->number = (int)$row['maxtimereversepay'];
    $out->entry->pay->maxtimereverse->formatted = numberFormatt($out->entry->pay->maxtimereverse->number, 2);
    
    $out->entry->pay->maxamountsend = new stdClass();
    $out->entry->pay->maxamountsend->number = (float)$row['maxamountopsendpay'];
    $out->entry->pay->maxamountsend->formatted = numberFormatt($out->entry->pay->maxamountsend->number, $row['decimals']);
    
    $out->entry->pay->pctreverse = new stdClass();
    $out->entry->pay->pctreverse->number = (int)$row['pctreversepay'];
    $out->entry->pay->pctreverse->formatted = numberFormatt($out->entry->pay->pctreverse->number, 2);
    
    //Consultamos las preferencias
    $sql = "SELECT cmspreferences.* ".
    "       FROM cmspreferences ".
    "       WHERE cmspreferences.id = 1 ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    $out->entry->pay->sessidtime = new stdClass();
    $out->entry->pay->sessidtime->number = (int)$row['paysessidtime'];
    $out->entry->pay->sessidtime->formatted = numberFormatt($out->entry->pay->sessidtime->number, 2);
    
    $out->entry->pay->optime = new stdClass();
    $out->entry->pay->optime->number = (int)$row['payoptime'];
    $out->entry->pay->optime->formatted = numberFormatt($out->entry->pay->optime->number, 2);
    
    $out->entry->rates = new stdClass();
    
    // Consultamos los rates
    $sql = "SELECT cmsprefrates.* FROM cmsprefrates, currencies".
    "       WHERE cmsprefrates.currencyid = currencies.id ".
    "       AND currencies.status = 1 ORDER BY currencies.id";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    while($row = $rs->fetch_assoc()){
        $rate = new stdClass();
        
        //Consultamos el id de la moneda
        $sql = "SELECT * FROM currencies WHERE id = ".$row['currencyid'];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $currencydata = $res->fetch_assoc();
        
        $rate->id = (int)$currencydata['id'];
        $rate->name = $currencydata['name'];
        $rate->symbol = $currencydata['symbol'];
        $rate->status = (int)$currencydata['status'];
        $rate->decimals = (int)$currencydata['decimals'];
        $rate->payref = (int)$currencydata['payref'] == 0 ? '0' : $currencydata['payref'];
        
        // Obtenemos la moneda de referencia en cms se mantiene -1 para estas tasas
        $sql = "SELECT * ".
        "       FROM currencies ".
        "       WHERE id = -1";
//      "       WHERE id = ".($currencydata['payref'] == 0 ? '-1' : $currencydata['id']);
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $currencydatapayref = $res->fetch_assoc();
        
        $rate->ref = $currencydatapayref['symbol'];
        
        $rate->rate = new stdClass();
        $rate->rate->number = (float)$row['rate'];
        $rate->rate->formatted = numberFormatt($rate->rate->number, $rate->decimals);
        
        //Consultamos los minimos de la moneda (NATURAL)
        $sql = "SELECT mindeposit, minexchange, minwithdraw, minxfer ".
        "       FROM cmspreffees ".
        "       WHERE currencyid = ".$row['currencyid'].
        "       AND usertype = 1".
        "       LIMIT 1";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $min = $res->fetch_assoc();
        
        $rate->minnatural = new stdClass();
        $rate->minnatural->deposits = new stdClass();
        $rate->minnatural->deposits->numeric = (float)$min['mindeposit'];
        $rate->minnatural->deposits->formatted = numberFormatt($rate->minnatural->deposits->numeric, $rate->decimals);
        
        $rate->minnatural->withdrawals = new stdClass();
        $rate->minnatural->withdrawals->numeric = (float)$min['minwithdraw'];
        $rate->minnatural->withdrawals->formatted = numberFormatt($rate->minnatural->withdrawals->numeric, $rate->decimals);
        
        $rate->minnatural->xfer = new stdClass();
        $rate->minnatural->xfer->numeric = (float)$min['minxfer'];
        $rate->minnatural->xfer->formatted = numberFormatt($rate->minnatural->xfer->numeric, $rate->decimals);
        
        $rate->minnatural->exchanges = new stdClass();
        $rate->minnatural->exchanges->numeric = (float)$min['minexchange'];
        $rate->minnatural->exchanges->formatted = numberFormatt($rate->minnatural->exchanges->numeric, $rate->decimals);
        
        //Consultamos los minimos de la moneda (NATURAL)
        $sql = "SELECT mindeposit, minexchange, minwithdraw, minxfer ".
        "       FROM cmspreffees ".
        "       WHERE currencyid = ".$row['currencyid'].
        "       AND usertype = 2".
        "       LIMIT 1";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $min = $res->fetch_assoc();
        
        $rate->minjuridic = new stdClass();
        $rate->minjuridic->deposits = new stdClass();
        $rate->minjuridic->deposits->numeric = (float)$min['mindeposit'];
        $rate->minjuridic->deposits->formatted = numberFormatt($rate->minjuridic->deposits->numeric, $rate->decimals);
        
        $rate->minjuridic->withdrawals = new stdClass();
        $rate->minjuridic->withdrawals->numeric = (float)$min['minwithdraw'];
        $rate->minjuridic->withdrawals->formatted = numberFormatt($rate->minjuridic->withdrawals->numeric, $rate->decimals);
        
        $rate->minjuridic->xfer = new stdClass();
        $rate->minjuridic->xfer->numeric = (float)$min['minxfer'];
        $rate->minjuridic->xfer->formatted = numberFormatt($rate->minjuridic->xfer->numeric, $rate->decimals);
        
        $rate->minjuridic->exchanges = new stdClass();
        $rate->minjuridic->exchanges->numeric = (float)$min['minexchange'];
        $rate->minjuridic->exchanges->formatted = numberFormatt($rate->minjuridic->exchanges->numeric, $rate->decimals);
        
        $rates [] = $rate;
    }
    
    $out->entry->rates->currencies = $rates;
        
    // Consultamos los datos de los niveles
    $sql = "SELECT * FROM levels WHERE id >0 ORDER BY `orden`  ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    while($row = $rs->fetch_assoc()){
        
        //Retornamos los datos basicos de el nivel
        $record = new stdClass();
        $record->level = (int)$row['id'];
        $record->name = $row['name'];
        $record->dsc = $row['dsc'];
        $record->dsc_eng = $row['dsc_eng'];
        
        // Consultamos los datos del pago movil
        $natpagomovil = "    SELECT  cmspreffees.pagomovilpct AS natpagomovilpct, ".
        "                   cmspreffees.levelid AS levelid, ".        
        "                   cmspreffees.currencyid AS currencyid, ".
        "                   cmspreffees.pagomovilmaxsend AS natpagomovilmaxsend " .
        "               FROM    cmspreffees " .
        "               WHERE   cmspreffees.usertype = 1 " . 
        "               AND     cmspreffees.currencyid IS NOT NULL "; //Este lado devuelve todos los naturales

        $jurpagomovil = "    SELECT  cmspreffees.pagomovilpct AS jurpagomovilpct, ".
        "                   cmspreffees.levelid AS levelid, ".
        "                   cmspreffees.currencyid AS currencyid, ".
        "                   cmspreffees.pagomovilmaxsend AS jurpagomovilmaxsend " .
        "               FROM    cmspreffees " .
        "               WHERE   cmspreffees.usertype = 2 " . 
        "               AND     cmspreffees.currencyid IS NOT NULL "; //Este lado devuelve todos los jurídicos
        //original
        /*
        $sqlpagomovil = "      SELECT natpagomovil.*, jurpagomovil.*, currencies.decimals AS decimals " .
        "               FROM  cmspreffees, currencies " .
        "               INNER JOIN   (".$natpagomovil.") natpagomovil ON natpagomovil.levelid = ".$record->level.
        "               INNER JOIN   (".$jurpagomovil.") jurpagomovil ON jurpagomovil.levelid = ".$record->level.
        "               WHERE cmspreffees.currencyid = 1 ".
        "               AND currencies.id =  cmspreffees.currencyid";*/
        //Modificado
        $sqlpagomovil ="SELECT  natpagomovil.*, jurpagomovil.*, currencies.decimals AS decimals " .
        "               FROM    cmspreffees " .
        "               LEFT JOIN   currencies ON currencies.id = cmspreffees.currencyid " .
        "               LEFT JOIN   (".$natpagomovil.") natpagomovil ON natpagomovil.levelid = cmspreffees.levelid " .
        "               AND     natpagomovil.currencyid =  cmspreffees.currencyid".
        "               LEFT JOIN   (".$jurpagomovil.") jurpagomovil ON jurpagomovil.levelid = cmspreffees.levelid " .
        "               AND     jurpagomovil.currencyid =  cmspreffees.currencyid".
        "               WHERE   cmspreffees.currencyid = 1 ".
        "               AND     cmspreffees.levelid = " .$record->level;
        if (!$resPagoMovil=$db->query($sqlpagomovil))
            badEnd("500", array("msg"=>determinateDBError($db),"sql"=>$sqlpagomovil));
        
        $pagomovilRow = $resPagoMovil->fetch_assoc();
        
        
        // Retorno de pago movil en nivel
        $record->pagomovil = new stdClass();
        
        // Retorno de pago movil natural
        $record->pagomovil->natural = new stdClass();
        $record->pagomovil->sql = $sqlpagomovil;
        
        $record->pagomovil->natural->maxperday = new stdClass();
        $record->pagomovil->natural->maxperday->number = (float)$pagomovilRow['natpagomovilmaxsend'];
        $record->pagomovil->natural->maxperday->formatted = numberFormatt($record->pagomovil->natural->maxperday->number, $pagomovilRow['decimals']);
        
        $record->pagomovil->natural->pctfee = new stdClass();
        $record->pagomovil->natural->pctfee->number = (float)$pagomovilRow['natpagomovilpct'];
        $record->pagomovil->natural->pctfee->formatted = numberFormatt($record->pagomovil->natural->pctfee->number, 2);
        
        $record->pagomovil->juridic = new stdClass();
        
        $record->pagomovil->juridic->maxperday = new stdClass();
        $record->pagomovil->juridic->maxperday->number = (float)$pagomovilRow['jurpagomovilmaxsend'];
        $record->pagomovil->juridic->maxperday->formatted = numberFormatt($record->pagomovil->juridic->maxperday->number, $pagomovilRow['decimals']);
        
        $record->pagomovil->juridic->pctfee = new stdClass();
        $record->pagomovil->juridic->pctfee->number = (float)$pagomovilRow['jurpagomovilpct'];
        $record->pagomovil->juridic->pctfee->formatted = numberFormatt($record->pagomovil->juridic->pctfee->number, 2);
        
        //Consultamos los datos de las monedas
        $sql = "SELECT DISTINCT cmspreffees.levelid, cmspreffees.currencyid FROM cmspreffees, currencies ".
        "       WHERE cmspreffees.levelid = ".$record->level.
        "       AND cmspreffees.currencyid IS NOT NULL".
        "       AND currencies.id = cmspreffees.currencyid".
        "       AND currencies.status = 1 ORDER BY currencies.id";
        if (!$resFee=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        while($feedata = $resFee->fetch_assoc()){
            $currency = new stdClass();
            
            // Consultamos los datos de la moneda
            $sql = "SELECT * FROM currencies WHERE id = ".$feedata['currencyid'];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $curInfo = $res->fetch_assoc();
            
            // Datos de la moneda
            $currency->id = (int)$curInfo['id'];
            $currency->name = $curInfo['name'];
            $currency->symbol = $curInfo['symbol'];
            $currency->decimals = $curInfo['decimals'];
            
            //Retornamos los maximos de cada tipo de operacion
            $currency->max = new stdClass();
            $currency->fees = new stdClass();
            
            $sql = "SELECT * FROM cmspreffees ".
            "       WHERE levelid = ".$record->level.
            "       AND currencyid = ".$currency->id;
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            while($fees = $res->fetch_assoc()){
                //Validamos si es natural o juridico
                if($fees['usertype'] == 1){
                    $currency->max->natural = new stdClass();
                    $currency->fees->natural = new stdClass();
                
                    // Maximo para Depositos
                    $currency->max->natural->deposits = new stdClass();
                    $currency->max->natural->deposits->amount = new stdClass();
                    $currency->max->natural->deposits->amount->number = (float)$fees['maxamountmonthlyopdeposits'];
                    $currency->max->natural->deposits->amount->formatted = numberFormatt($fees['maxamountmonthlyopdeposits'], $curInfo['decimals']);
                    $currency->max->natural->deposits->operations = new stdClass();
                    $currency->max->natural->deposits->operations->number = (int)$fees['maxqtymonthlyopdeposits'];
                    $currency->max->natural->deposits->operations->formatted = $fees['maxqtymonthlyopdeposits'];
                    
                    // Comision para Depositos
                    $currency->fees->natural->deposits = new stdClass();
                    $currency->fees->natural->deposits->pctfee = new stdClass();
                    $currency->fees->natural->deposits->pctfee->number = $fees['pctfeedeposits'] == null ? null : (float)$fees['pctfeedeposits'];
                    $currency->fees->natural->deposits->pctfee->formatted = $fees['pctfeedeposits'] == null ? null : numberFormatt($fees['pctfeedeposits'], 2);
                    $currency->fees->natural->deposits->nmlfee = new stdClass();
                    $currency->fees->natural->deposits->nmlfee->number = $fees['nmlfeedeposits'] == null ? null : (float)$fees['nmlfeedeposits'];
                    $currency->fees->natural->deposits->nmlfee->formatted = $fees['nmlfeedeposits'] == null ? null : numberFormatt($fees['nmlfeedeposits'], $curInfo['decimals']);
                    
                    // Maximo para Retiros
                    $currency->max->natural->withdrawals = new stdClass();
                    $currency->max->natural->withdrawals->amount = new stdClass();
                    $currency->max->natural->withdrawals->amount->number = (float)$fees['maxamountmonthlyopwithdrawals'];
                    $currency->max->natural->withdrawals->amount->formatted = numberFormatt($fees['maxamountmonthlyopwithdrawals'], $curInfo['decimals']);
                    $currency->max->natural->withdrawals->operations = new stdClass();
                    $currency->max->natural->withdrawals->operations->number = (int)$fees['maxqtymonthlyopwithdrawals'];
                    $currency->max->natural->withdrawals->operations->formatted = $fees['maxqtymonthlyopwithdrawals'];
                    
                    // Comision para Retiros
                    $currency->fees->natural->withdrawals = new stdClass();
                    $currency->fees->natural->withdrawals->pctfee = new stdClass();
                    $currency->fees->natural->withdrawals->pctfee->number = $fees['pctfeewithdrawals'] == null ? null : (float)$fees['pctfeewithdrawals'];
                    $currency->fees->natural->withdrawals->pctfee->formatted = $fees['pctfeewithdrawals'] == null ? null : numberFormatt($fees['pctfeewithdrawals'], 2);
                    $currency->fees->natural->withdrawals->nmlfee = new stdClass();
                    $currency->fees->natural->withdrawals->nmlfee->number = $fees['nmlfeewithdrawals'] == null ? null : (float)$fees['nmlfeewithdrawals'];
                    $currency->fees->natural->withdrawals->nmlfee->formatted = $fees['nmlfeewithdrawals'] == null ? null : numberFormatt($fees['nmlfeewithdrawals'], $curInfo['decimals']);
                    
                    // Maximo para Transferencias
                    $currency->max->natural->xfer = new stdClass();
                    $currency->max->natural->xfer->amount = new stdClass();
                    $currency->max->natural->xfer->amount->number = (float)$fees['maxamountmonthlyopxfer'];
                    $currency->max->natural->xfer->amount->formatted = numberFormatt($fees['maxamountmonthlyopxfer'], $curInfo['decimals']);
                    $currency->max->natural->xfer->operations = new stdClass();
                    $currency->max->natural->xfer->operations->number = (int)$fees['maxqtymonthlyopxfer'];
                    $currency->max->natural->xfer->operations->formatted = $fees['maxqtymonthlyopxfer'];
                    
                    // Comision para Transferencias
                    $currency->fees->natural->xfer = new stdClass();
                    $currency->fees->natural->xfer->pctfee = new stdClass();
                    $currency->fees->natural->xfer->pctfee->number = $fees['pctfeexfer'] == null ? null : (float)$fees['pctfeexfer'];
                    $currency->fees->natural->xfer->pctfee->formatted = $fees['pctfeexfer'] == null ? null : numberFormatt($fees['pctfeexfer'], 2);
                    $currency->fees->natural->xfer->nmlfee = new stdClass();
                    $currency->fees->natural->xfer->nmlfee->number = $fees['nmlfeesxfer'] == null ? null : (float)$fees['nmlfeesxfer'];
                    $currency->fees->natural->xfer->nmlfee->formatted = $fees['nmlfeesxfer'] == null ? null : numberFormatt($fees['nmlfeesxfer'], $curInfo['decimals']);
                
                }else if($fees['usertype'] == 2){
                    $currency->max->juridic = new stdClass();
                    $currency->fees->juridic = new stdClass();
                    
                    // Maximo para Depositos
                    $currency->max->juridic->deposits = new stdClass();
                    $currency->max->juridic->deposits->amount = new stdClass();
                    $currency->max->juridic->deposits->amount->number = (float)$fees['maxamountmonthlyopdeposits'];
                    $currency->max->juridic->deposits->amount->formatted = numberFormatt($fees['maxamountmonthlyopdeposits'], $curInfo['decimals']);
                    $currency->max->juridic->deposits->operations = new stdClass();
                    $currency->max->juridic->deposits->operations->number = (int)$fees['maxqtymonthlyopdeposits'];
                    $currency->max->juridic->deposits->operations->formatted = $fees['maxqtymonthlyopdeposits'];
                    
                    // Comision para Depositos
                    $currency->fees->juridic->deposits = new stdClass();
                    $currency->fees->juridic->deposits->pctfee = new stdClass();
                    $currency->fees->juridic->deposits->pctfee->number = $fees['pctfeedeposits'] == null ? null : (float)$fees['pctfeedeposits'];
                    $currency->fees->juridic->deposits->pctfee->formatted = $fees['pctfeedeposits'] == null ? null : numberFormatt($fees['pctfeedeposits'], 2);
                    $currency->fees->juridic->deposits->nmlfee = new stdClass();
                    $currency->fees->juridic->deposits->nmlfee->number = $fees['nmlfeedeposits'] == null ? null : (float)$fees['nmlfeedeposits'];
                    $currency->fees->juridic->deposits->nmlfee->formatted = $fees['nmlfeedeposits'] == null ? null : numberFormatt($fees['nmlfeedeposits'], $curInfo['decimals']);
                    
                    // Maximo para Retiros
                    $currency->max->juridic->withdrawals = new stdClass();
                    $currency->max->juridic->withdrawals->amount = new stdClass();
                    $currency->max->juridic->withdrawals->amount->number = (float)$fees['maxamountmonthlyopwithdrawals'];
                    $currency->max->juridic->withdrawals->amount->formatted = numberFormatt($fees['maxamountmonthlyopwithdrawals'], $curInfo['decimals']);
                    $currency->max->juridic->withdrawals->operations = new stdClass();
                    $currency->max->juridic->withdrawals->operations->number = (int)$fees['maxqtymonthlyopwithdrawals'];
                    $currency->max->juridic->withdrawals->operations->formatted = $fees['maxqtymonthlyopwithdrawals'];
                    
                    // Comision para Retiros
                    $currency->fees->juridic->withdrawals = new stdClass();
                    $currency->fees->juridic->withdrawals->pctfee = new stdClass();
                    $currency->fees->juridic->withdrawals->pctfee->number = $fees['pctfeewithdrawals'] == null ? null : (float)$fees['pctfeewithdrawals'];
                    $currency->fees->juridic->withdrawals->pctfee->formatted = $fees['pctfeewithdrawals'] == null ? null : numberFormatt($fees['pctfeewithdrawals'], 2);
                    $currency->fees->juridic->withdrawals->nmlfee = new stdClass();
                    $currency->fees->juridic->withdrawals->nmlfee->number = $fees['nmlfeewithdrawals'] == null ? null : (float)$fees['nmlfeewithdrawals'];
                    $currency->fees->juridic->withdrawals->nmlfee->formatted = $fees['nmlfeewithdrawals'] == null ? null : numberFormatt($fees['nmlfeewithdrawals'], $curInfo['decimals']);
                    
                    // Maximo para Transferencias
                    $currency->max->juridic->xfer = new stdClass();
                    $currency->max->juridic->xfer->amount = new stdClass();
                    $currency->max->juridic->xfer->amount->number = (float)$fees['maxamountmonthlyopxfer'];
                    $currency->max->juridic->xfer->amount->formatted = numberFormatt($fees['maxamountmonthlyopxfer'], $curInfo['decimals']);
                    $currency->max->juridic->xfer->operations = new stdClass();
                    $currency->max->juridic->xfer->operations->number = (int)$fees['maxqtymonthlyopxfer'];
                    $currency->max->juridic->xfer->operations->formatted = $fees['maxqtymonthlyopxfer'];
                    
                    // Comision para Transferencias
                    $currency->fees->juridic->xfer = new stdClass();
                    $currency->fees->juridic->xfer->pctfee = new stdClass();
                    $currency->fees->juridic->xfer->pctfee->number = $fees['pctfeexfer'] == null ? null : (float)$fees['pctfeexfer'];
                    $currency->fees->juridic->xfer->pctfee->formatted = $fees['pctfeexfer'] == null ? null : numberFormatt($fees['pctfeexfer'], 2);
                    $currency->fees->juridic->xfer->nmlfee = new stdClass();
                    $currency->fees->juridic->xfer->nmlfee->number = $fees['nmlfeesxfer'] == null ? null : (float)$fees['nmlfeesxfer'];
                    $currency->fees->juridic->xfer->nmlfee->formatted = $fees['nmlfeesxfer'] == null ? null : numberFormatt($fees['nmlfeesxfer'], $curInfo['decimals']);
                    
                }
            }
            
            $record->currencies [] = $currency;
        }
        

        $pairsinfo="    SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc, par.id AS pairid, " .
        "               currencies.decimals AS currendecimals, cursec.decimals AS cursecdecimals, par.status    " .
        "               FROM pairs par " .
        "               LEFT JOIN currencies ON currencies.id = par.refcurrencyid " .
        "               LEFT JOIN currencies cursec ON cursec.id = par.currencyid " .
        "               WHERE par.refcurrencyid = currencies.id"; //Info de los pares
        
        $pairsinfo="    SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc, par.id AS pairid, " .
        "               currencies.decimals AS currendecimals, cursec.decimals AS cursecdecimals, par.status    " .
        "               FROM pairs par " .
        "               LEFT JOIN currencies ON currencies.id = par.refcurrencyid " .
        "               LEFT JOIN currencies cursec ON cursec.id = par.currencyid " .
        "               WHERE par.refcurrencyid = currencies.id"; //Info de los pares

        $natfees = "    SELECT  cmspreffees.pairid AS pairid, cmspreffees.levelid AS levelid, " .
        "                       cmspreffees.nmlmktfee AS natnmlmktfee, " .
        "                       cmspreffees.pctmktfee AS natpctmktfee, " .
        "                       cmspreffees.nmllimitfee AS natnmllimitfee, " .
        "                       cmspreffees.pctlimitfee AS natpctlimitfee " .
        "               FROM    cmspreffees " .
        "               WHERE   cmspreffees.usertype = 1 " . 
        "               AND     cmspreffees.pairid IS NOT NULL AND currencyid IS NULL "; //Este lado devuelve todos los naturales

        $jurfees = "    SELECT  cmspreffees.pairid AS pairid, cmspreffees.levelid AS levelid, " .
        "                       cmspreffees.nmlmktfee AS jurnmlmktfee, " .
        "                       cmspreffees.pctmktfee AS jurpctmktfee, " .
        "                       cmspreffees.nmllimitfee AS jurnmllimitfee, " .
        "                       cmspreffees.pctlimitfee AS jurpctlimitfee " .
        "               FROM    cmspreffees " .
        "               WHERE   cmspreffees.usertype = 2 " . 
        "               AND     cmspreffees.pairid IS NOT NULL AND currencyid IS NULL "; //Este lado devuelve todos los jurídicos

        $sqlnw = "      SELECT pairs.*, natfees.*, jurfees.* " .
        "               FROM   (".$pairsinfo.") pairs " .
        "               INNER JOIN   (".$natfees.")      natfees ON natfees.pairid = pairs.pairid AND natfees.levelid = ".$record->level. //Solo trae el par si existe en ambos
        "               INNER JOIN   (".$jurfees.")      jurfees ON jurfees.pairid = pairs.pairid AND jurfees.levelid = ".$record->level.
        "               WHERE pairs.status = 1 ".
        "               ORDER BY pairs.pairdsc, pairs.pairid";
/*  
        //Consultamos los datos de los pares para este nivel
        $sql = "SELECT DISTINCT cmspreffees.pairid, cmspreffees.levelid FROM cmspreffees, pairs ".
        "       WHERE cmspreffees.levelid = ".$record->level.
        "       AND cmspreffees.pairid IS NOT NULL".
        "       AND cmspreffees.pairid = pairs.id".
        "       AND pairs.status = 1 ORDER BY pairs.id";*/
        if (!$resFee=$db->query($sqlnw))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        while($feedata = $resFee->fetch_assoc()){
            $pair = new stdClass();
            
            // Obtenemos el nombre del par
            /*
            $sql = "SELECT CONCAT(currencies.symbol,'/',cursec.symbol) AS pairdsc, par.id AS id, ".
            "       currencies.decimals AS currendecimals, cursec.decimals AS cursecdecimals".
            "       FROM currencies, pairs par ".
            "       LEFT JOIN currencies cursec ON cursec.id = par.currencyid ".
            "       WHERE par.refcurrencyid = currencies.id ".
            "       AND par.id = ".$feedata['pairid'];
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
                
            $pairInfo = $res->fetch_assoc();*/
            
            $pair->id = (int)$feedata['pairid'];
            $pair->name = $feedata['pairdsc'];
            $pair->basedecimals = $feedata['currendecimals'];
            $pair->fees = new stdClass();
            /*
            // Consultamos los datos de ese par
            $sql = "SELECT * FROM cmspreffees ".
            "       WHERE levelid = ".$record->level.
            "       AND pairid = ".$pair->id;
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            while($fees = $res->fetch_assoc()){*/
                //Validamos el tipo de usuario
                //if($feedata['usertype'] == 1){
                    $pair->fees->natural = new stdClass();
                    
                    // Comision orden limit
                    $pair->fees->natural->limit = new stdClass();
                    $pair->fees->natural->limit->pctfee = new stdClass();
                    $pair->fees->natural->limit->pctfee->number = $feedata['natpctlimitfee'] == null ? null : (float)$feedata['natpctlimitfee'];
                    $pair->fees->natural->limit->pctfee->formatted = $feedata['natpctlimitfee'] == null ? null : numberFormatt($feedata['natpctlimitfee'], 2);
                    
                    $pair->fees->natural->limit->nmalfee = new stdClass();
                    $pair->fees->natural->limit->nmalfee->number = $feedata['natnmllimitfee'] == null ? null : (float)$feedata['natnmllimitfee'];
                    $pair->fees->natural->limit->nmalfee->formatted = numberFormatt($feedata['natnmllimitfee'], 10);
                    
                    // Comision orden market
                    $pair->fees->natural->market = new stdClass();
                    $pair->fees->natural->market->pctfee = new stdClass();
                    $pair->fees->natural->market->pctfee->number = $feedata['natpctmktfee'] == null ? null : (float)$feedata['natpctmktfee'];
                    $pair->fees->natural->market->pctfee->formatted = $feedata['natpctmktfee'] == null ? null : numberFormatt($feedata['natpctmktfee'], 2);
                    
                    $pair->fees->natural->market->nmalfee = new stdClass();
                    $pair->fees->natural->market->nmalfee->number = $feedata['natnmlmktfee'] == null ? null : (float)$feedata['natnmlmktfee'];
                    $pair->fees->natural->market->nmalfee->formatted = $feedata['natnmlmktfee'] == null ? null : numberFormatt($feedata['natnmlmktfee'], 10);
                //}else{
                    $pair->fees->juridic = new stdClass();
                    
                    // Comision orden limit
                    $pair->fees->juridic->limit = new stdClass();
                    $pair->fees->juridic->limit->pctfee = new stdClass();
                    $pair->fees->juridic->limit->pctfee->number = $feedata['jurpctlimitfee'] == null ? null : (float)$feedata['jurpctlimitfee'];
                    $pair->fees->juridic->limit->pctfee->formatted = $feedata['jurpctlimitfee'] == null ? null : numberFormatt($feedata['jurpctlimitfee'], 2);
                    
                    $pair->fees->juridic->limit->nmalfee = new stdClass();
                    $pair->fees->juridic->limit->nmalfee->number = $feedata['jurnmllimitfee'] == null ? null : (float)$feedata['jurnmllimitfee'];
                    $pair->fees->juridic->limit->nmalfee->formatted = $feedata['jurnmllimitfee'] == null ? null : numberFormatt($feedata['jurnmllimitfee'], 10);
                    
                    // Comision orden market
                    $pair->fees->juridic->market = new stdClass();
                    $pair->fees->juridic->market->pctfee = new stdClass();
                    $pair->fees->juridic->market->pctfee->number = $feedata['jurpctmktfee'] == null ? null : (float)$feedata['jurpctmktfee'];
                    $pair->fees->juridic->market->pctfee->formatted = $feedata['jurpctmktfee'] == null ? null : numberFormatt($feedata['jurpctmktfee'], 2);
                    
                    $pair->fees->juridic->market->nmalfee = new stdClass();
                    $pair->fees->juridic->market->nmalfee->number = $feedata['jurnmlmktfee'] == null ? null : (float)$feedata['jurnmlmktfee'];
                    $pair->fees->juridic->market->nmalfee->formatted = $feedata['jurnmlmktfee'] == null ? null : numberFormatt($feedata['jurnmlmktfee'], 10);
                //}
            //}
            
            
            $record->pairs [] = $pair;
        }
        
        $records [] = $record;
    }
    $out->entry->levels = $records;
    
    //Obtenemos los datos de las imagenes requeridas
    $sql = "SELECT * FROM cmsprefuploads";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    while($row = $rs->fetch_assoc()){
        $upload = new stdClass();
        
        $upload->id = str_pad($row["id"], 2, "0", STR_PAD_LEFT);
        $upload->name = $row['dsc'];
        $upload->active = (int)$row['activo'] == 1 ? true : false;
        
        //Consultamos los datos del nivel
        $sql = "SELECT * FROM levels";
        if (!$resUp=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $upload->level = new stdClass();
        while($levelsTemp = $resUp->fetch_assoc()){
            
            $levelsarrTemp = explode("-",$levelsTemp["cmsprefuploads"]);
            foreach($levelsarrTemp as $whichlevel){
                if($row["id"] == $whichlevel){
                    $upload->level->id = (int)$levelsTemp["id"];
                    $upload->level->dsc = $levelsTemp["name"];
                }
            }
        }
        
        $uploads [] = $upload;
    }
    
    $out->entry->uploads = $uploads;
    
    // Consultamos los terminos y condiciones
    $sql = "SELECT * FROM cmspreferences WHERE id = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    $out->entry->terms = $row['terms'];
    $out->entry->terms_eng = $row['terms_eng'];
    
    //Retornamos los privilegios del usuario actual
    $access = new stdClass;
    $access->read =   tienePrivilegio($db, $sessionid, 57);
    $access->update = tienePrivilegio($db, $sessionid, 56);
    $out->privileges = $access;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
