<?php
// cms/api/preferences/entry

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../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 = $_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"));
        
    $out->entry->rates = new stdClass();
    
    // Consultamos los rates
    $sql = "SELECT cmsprefrates.* FROM cmsprefrates, currencies".
    "       WHERE cmsprefrates.currencyid = currencies.id ".
    "       AND currencies.status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    while($row = $rs->fetch_assoc()){
        $rate = new stdClass();
        
        //Consultamos el id de la moneda
        $sql = "SELECT * FROM currencies WHERE id = ".$row['currencyid'].
        "       AND status = 1";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $currencydata = $res->fetch_assoc();
        
        $rate->id = (int)$currencydata['id'];
        $rate->name = $currencydata['name'];
        $rate->symbol = $currencydata['symbol'];
        $rate->decimals = (int)$currencydata['decimals'];
        $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"=>$db->error));
            
        $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"=>$db->error));
            
        $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";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    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'];
        
        //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";
        if (!$resFee=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        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"=>$db->error));
            
            $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"=>$db->error));
            
            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;
        }
        
        //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";
        if (!$resFee=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        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"=>$db->error));
                
            $pairInfo = $res->fetch_assoc();
            
            $pair->id = (int)$pairInfo['id'];
            $pair->name = $pairInfo['pairdsc'];
            $pair->basedecimals = $pairInfo['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"=>$db->error));
            
            while($fees = $res->fetch_assoc()){
                //Validamos el tipo de usuario
                if($fees['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 = $fees['pctlimitfee'] == null ? null : (float)$fees['pctlimitfee'];
                    $pair->fees->natural->limit->pctfee->formatted = $fees['pctlimitfee'] == null ? null : numberFormatt($fees['pctlimitfee'], 2);
                    
                    $pair->fees->natural->limit->nmalfee = new stdClass();
                    $pair->fees->natural->limit->nmalfee->number = $fees['nmllimitfee'] == null ? null : (float)$fees['nmllimitfee'];
                    $pair->fees->natural->limit->nmalfee->formatted = numberFormatt($fees['nmllimitfee'], 10);
                    
                    // Comision orden market
                    $pair->fees->natural->market = new stdClass();
                    $pair->fees->natural->market->pctfee = new stdClass();
                    $pair->fees->natural->market->pctfee->number = $fees['pctmktfee'] == null ? null : (float)$fees['pctmktfee'];
                    $pair->fees->natural->market->pctfee->formatted = $fees['pctmktfee'] == null ? null : numberFormatt($fees['pctmktfee'], 2);
                    
                    $pair->fees->natural->market->nmalfee = new stdClass();
                    $pair->fees->natural->market->nmalfee->number = $fees['nmlmktfee'] == null ? null : (float)$fees['nmlmktfee'];
                    $pair->fees->natural->market->nmalfee->formatted = $fees['nmlmktfee'] == null ? null : numberFormatt($fees['nmlmktfee'], 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 = $fees['pctlimitfee'] == null ? null : (float)$fees['pctlimitfee'];
                    $pair->fees->juridic->limit->pctfee->formatted = $fees['pctlimitfee'] == null ? null : numberFormatt($fees['pctlimitfee'], 2);
                    
                    $pair->fees->juridic->limit->nmalfee = new stdClass();
                    $pair->fees->juridic->limit->nmalfee->number = $fees['nmllimitfee'] == null ? null : (float)$fees['nmllimitfee'];
                    $pair->fees->juridic->limit->nmalfee->formatted = $fees['nmllimitfee'] == null ? null : numberFormatt($fees['nmllimitfee'], 10);
                    
                    // Comision orden market
                    $pair->fees->juridic->market = new stdClass();
                    $pair->fees->juridic->market->pctfee = new stdClass();
                    $pair->fees->juridic->market->pctfee->number = $fees['pctmktfee'] == null ? null : (float)$fees['pctmktfee'];
                    $pair->fees->juridic->market->pctfee->formatted = $fees['pctmktfee'] == null ? null : numberFormatt($fees['pctmktfee'], 2);
                    
                    $pair->fees->juridic->market->nmalfee = new stdClass();
                    $pair->fees->juridic->market->nmalfee->number = $fees['nmlmktfee'] == null ? null : (float)$fees['nmlmktfee'];
                    $pair->fees->juridic->market->nmalfee->formatted = $fees['nmlmktfee'] == null ? null : numberFormatt($fees['nmlmktfee'], 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"=>$db->error));
        
    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"=>$db->error));
            
        $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";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    $out->entry->terms = $row['terms'];
    
    //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();
?>
