<?php
// app/api/orders/details
    
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","currencyid","refcurrencyid","action");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass();
    $out->entry = new stdClass();
    $sessionid = $_GET["sessionid"];
    $currencyid = $_GET["currencyid"];
    $refcurrencyid = $_GET["refcurrencyid"];
    $action = $_GET['action'];
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    //Consultamos para verificar que exista un par con las monedas
    $sql = "SELECT COUNT(id) AS qty FROM pairs ".
    "       WHERE ((currencyid = ".$currencyid.
    "       AND refcurrencyid = ".$refcurrencyid.") ".
    "       OR (currencyid = ".$refcurrencyid.
    "       AND refcurrencyid = ".$currencyid.")) ".
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    // Validamos que haya conseguido registros con los parametros
    if($row['qty'] == 0){
        badEnd("204", array("msg"=>"Registro no encontrado"));
    }
    
    //Consultamos para verificar que exista un par con las monedas
    $sql = "SELECT id, currencyid, refcurrencyid ".
    "       FROM pairs ".
    "       WHERE ((currencyid = ".$currencyid.
    "       AND refcurrencyid = ".$refcurrencyid.") ".
    "       OR (currencyid = ".$refcurrencyid.
    "       AND refcurrencyid = ".$currencyid.")) ".
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $pairdata = $rs->fetch_assoc();
    
    //Retornamos el id del par
    $out->entry->id = (int)$pairdata['id'];
    
    // Consultamos los datos de la moneda base
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$pairdata['refcurrencyid'].
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $basecurrency = $rs->fetch_assoc();
    
    //Guardamos los detalles de la moneda base
    $out->entry->currency = new stdClass();
    $out->entry->currency->id = (int)$basecurrency['id'];
    $out->entry->currency->dsc = $basecurrency['name'];
    $out->entry->currency->symbol = $basecurrency['symbol'];
    $out->entry->currency->decimals = (int)$basecurrency['decimals'];
    $out->entry->currency->interface = (int)$basecurrency['interface'];
    
    // Consultamos los datos de la moneda ref
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$pairdata['currencyid'].
    "       AND status = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $refcurrency = $rs->fetch_assoc();
    
    //Guardamos los detalles de la moneda ref
    $out->entry->refcurrency = new stdClass();
    $out->entry->refcurrency->id = (int)$refcurrency['id'];
    $out->entry->refcurrency->dsc = $refcurrency['name'];
    $out->entry->refcurrency->symbol = $refcurrency['symbol'];
    $out->entry->refcurrency->decimals = (int)$refcurrency['decimals'];
    $out->entry->refcurrency->interface = (int)$refcurrency['interface'];
    
    // Orden de la accion
    $out->entry->orden = new stdClass();
    $out->entry->orden->basecurrencyid = $out->entry->currency->id;
    $out->entry->orden->refcurrencyid = $out->entry->refcurrency->id;
    
    //Determinamos el tipo de orden donde
    // 1 = venta
    // 2 = compra
    if($action == 1 && $out->entry->orden->basecurrencyid == $currencyid){
        $out->entry->orden->type = 2;
    }else if($action == 2 && $out->entry->orden->basecurrencyid != $currencyid){
        $out->entry->orden->type = 1;
    }else if($action == 2 && $out->entry->orden->basecurrencyid == $currencyid){
        $out->entry->orden->type = 2;
    }else if($action == 1 && $out->entry->orden->basecurrencyid != $currencyid){
        $out->entry->orden->type = 1;
    }else{
        $out->entry->orden->type = 2;
    }
    
    
    //Obtenemos la ultima transaccion realizada
    $sql = "SELECT (SELECT ord.price FROM orders ord ".
    "       WHERE ord.type = 2 AND (ord.id = t.orderid OR ord.id = txother.orderid)) AS lastprice ".
    "       FROM orders, accounts, transactions t  ".
    "           LEFT JOIN transactions txother ".
    "               ON t.orderid != txother.orderid ".
    "               AND t.txid = txother.txid  ".
    "               AND txother.amount > 0 ".
    "               AND txother.dsc NOT LIKE 'Comisi%' ".
    "       WHERE t.orderid IS NOT NULL ".
    "       AND orders.id = txother.orderid ".
    "       AND orders.pairid = ".$out->entry->id.
    "       AND t.id = t.txid ".
    "       AND t.dsc NOT LIKE 'Comisi%' ".
    "       AND accounts.id = orders.accountid ".
    "       AND accounts.entityusrid = -1 ".
    "       GROUP BY t.txid ".
    "       ORDER BY t.datecreated DESC, t.id DESC".
    "       LIMIT 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
                
    $row = $rs->fetch_assoc();
        
    // Retornamos el precio del ultimo intercambio
    $out->entry->last = new stdClass();
    $out->entry->last->number = (float)$row["lastprice"];
    $out->entry->last->formatted = numberFormatt($out->entry->last->number,$refcurrency['decimals']);
    
    //Consultamos la ultima venta
    $sql = "SELECT o.quantity AS qty, o.id AS grouptx, ".
    "       o.price, o.side, o.id, o.total".
    "       FROM orders o".
    "       WHERE o.side = 1 AND o.canceled IS NULL AND o.pairid = ".$out->entry->id.
    "       AND (CASE ".
    "           WHEN o.canceled IS NOT NULL THEN -1 ".
    "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
    "               FROM transactions, orders ".
    "               WHERE orders.id = transactions.orderid ".
    "               AND orders.id = o.id ".
    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
    "               AND o.canceled IS NULL THEN 1 ".
    "           ELSE 0 ".
    "       END) = 0 ".
    "       ORDER BY o.price ASC".
    "       LIMIT 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    // Retornamos el ask del par
    $out->entry->ask = new stdClass();
    $out->entry->ask->number = (float)$row['price'];
    $out->entry->ask->formatted = numberFormatt($out->entry->ask->number,$refcurrency['decimals']);
    
    //Consultamos los datos de la ultima compra
    $sql = "SELECT o.quantity AS qty, o.id AS grouptx, ".
    "       o.price, o.side, o.id, o.total".
    "       FROM orders o".
    "       WHERE o.side = 2 AND o.canceled IS NULL AND o.pairid = ".$out->entry->id.
    "       AND (CASE ".
    "           WHEN o.canceled IS NOT NULL THEN -1 ".
    "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
    "               FROM transactions, orders ".
    "               WHERE orders.id = transactions.orderid ".
    "               AND orders.id = o.id ".
    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
    "               AND o.canceled IS NULL THEN 1 ".
    "           ELSE 0 ".
    "       END) = 0 ".
    "       ORDER BY o.price DESC".
    "       LIMIT 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    
    // Retornamos el bid del par
    $out->entry->bid = new stdClass();
    $out->entry->bid->number = (float)$row['price'];
    $out->entry->bid->formatted = numberFormatt($out->entry->bid->number,$refcurrency['decimals']);
    
    // Necesitamos obtener el saldo del usuario
    // Consultamos su cuenta (COMPRA)
    if($out->entry->orden->type == 1){
        $sql = "SELECT accounts.id AS accountid ".
        "       FROM accounts, currencies cur ".
        "       WHERE accounts.userid = ".$userid.
        "       AND accounts.currencyid = cur.id ".
        "       AND cur.status = 1 ".
        "       AND accounts.entityusrid = -1 ".
        "       AND accounts.paymentmethodid = -1 ".
        "       AND cur.id = ".$out->entry->currency->id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        
        $accountid = $row['accountid'];
        
        //Consultamos el balance disponible
        $sql = "SELECT SUM(amount) as qty FROM transactions WHERE accountid = ".$accountid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $balancetx = $rs->fetch_assoc();
        
        // Balance retenido por ordenes de intercambios
        $sql = "SELECT SUM(amount) AS qty ".
        "       FROM ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1 ".
        "       UNION ALL ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$accountid.
        "           AND orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1 ".
    	"       UNION ALL ".
    	"           SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)".
    	"      UNION ALL ".
    	"           SELECT SUM(ABS(withdrawals.amount) + ABS(withdrawals.fee)) AS amount ".
    	"           FROM transactions, withdrawals ".
    	"           WHERE transactions.id = withdrawals.transactionid ".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND withdrawals.valid IS NUll ".
    	"           AND withdrawals.rejected IS NULL ".
        "       ) amount";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $balanceorder = $res->fetch_assoc();
        $acum = number_format($balancetx["qty"] - $balanceorder["qty"], $out->entry->currency->decimals, '.', '');
        
    }else if($out->entry->orden->basecurrencyid == $currencyid && $action == 1){
        $sql = "SELECT accounts.id AS accountid ".
        "       FROM accounts, currencies cur ".
        "       WHERE accounts.userid = ".$userid.
        "       AND accounts.currencyid = cur.id ".
        "       AND cur.status = 1 ".
        "       AND accounts.entityusrid = -1 ".
        "       AND accounts.paymentmethodid = -1 ".
        "       AND cur.id = ".$out->entry->currency->id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        
        $accountid = $row['accountid'];
        
        //Consultamos el balance disponible
        $sql = "SELECT SUM(amount) as qty FROM transactions WHERE accountid = ".$accountid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $balancetx = $rs->fetch_assoc();
        
        // Balance retenido por ordenes de intercambios
        $sql = "SELECT SUM(amount) AS qty ".
        "       FROM ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1 ".
        "       UNION ALL ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$accountid.
        "           AND orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1 ".
    	"       UNION ALL ".
    	"           SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)".
    	"      UNION ALL ".
    	"           SELECT SUM(ABS(withdrawals.amount) + ABS(withdrawals.fee)) AS amount ".
    	"           FROM transactions, withdrawals ".
    	"           WHERE transactions.id = withdrawals.transactionid ".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND withdrawals.valid IS NUll ".
    	"           AND withdrawals.rejected IS NULL ".
        "       ) amount";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $balanceorder = $res->fetch_assoc();
    
        //$acum = number_format($balancetx["qty"] - $balanceorder["qty"], $out->entry->currency->decimals, '.', '');
        $val = ($balancetx["qty"] - $balanceorder["qty"]);
        $acum = bcdiv(number_format($val,13,'.', ''), '1', $out->entry->currency->decimals);
    }else{
        $sql = "SELECT accounts.id AS accountid ".
        "       FROM accounts, currencies cur ".
        "       WHERE accounts.userid = ".$userid.
        "       AND accounts.currencyid = cur.id ".
        "       AND cur.status = 1 ".
        "       AND accounts.entityusrid = -1".
        "       AND accounts.paymentmethodid = -1 ".
        "       AND cur.id = ".$out->entry->refcurrency->id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        
        $accountid = $row['accountid'];
        
        //Consultamos el balance disponible
        $sql = "SELECT SUM(amount) as qty FROM transactions WHERE accountid = ".$accountid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $balancetx = $rs->fetch_assoc();
        
        // Balance retenido por ordenes de intercambios
        $sql = "SELECT SUM(amount) AS qty ".
        "       FROM ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1 ".
        "       UNION ALL ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$accountid.
        "           AND orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1 ".
    	"       UNION ALL ".
    	"           SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)".
    	"      UNION ALL ".
    	"           SELECT SUM(ABS(withdrawals.amount) + ABS(withdrawals.fee)) AS amount ".
    	"           FROM transactions, withdrawals ".
    	"           WHERE transactions.id = withdrawals.transactionid ".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND withdrawals.valid IS NUll ".
    	"           AND withdrawals.rejected IS NULL ".
        "       ) amount";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $balanceorder = $res->fetch_assoc();
    
        //$acum = number_format($balancetx["qty"] - $balanceorder["qty"], $out->entry->refcurrency->decimals, '.', '');
        $val = ($balancetx["qty"] - $balanceorder["qty"]);
        $acum = bcdiv(number_format($val,13,'.', ''), '1', $out->entry->refcurrency->decimals);
    }
    
    // COnsultamos las ordenes para obtener el mayor de compra
    $sql = "SELECT SUM(o.quantity) AS qty, COUNT(o.id) AS grouptx, o.price AS price,".
    "       IF( ".
    "           (SELECT SUM(ABS(transactions.amount)) ".
    "               FROM transactions, orders ".
    "               WHERE orders.id = transactions.orderid ".
    "               AND orders.id = o.id ".
    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) IS NOT NULL, ".
    "           (SELECT SUM(ABS(transactions.amount)) ".
    "               FROM transactions, orders ".
    "               WHERE orders.id = transactions.orderid ".
    "               AND orders.id = o.id ".
    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)), ".
    "           0 ".
    "       ) AS totallyfilled ".
    "       FROM orders o".
    "       WHERE o.side = ".($out->entry->orden->type == 2 ? ($out->entry->orden->basecurrencyid == $currencyid && $action == 1 ? 2 : 1 ) : 2)." AND o.canceled IS NULL AND o.pairid = ".$out->entry->id.
    "       AND (CASE ".
    "           WHEN o.canceled IS NOT NULL THEN -1 ".
    "           WHEN (SELECT SUM(ABS(transactions.amount)) ".
    "               FROM transactions, orders ".
    "               WHERE orders.id = transactions.orderid ".
    "               AND orders.id = o.id ".
    "               AND IF(o.side = 2, transactions.amount > 0, transactions.amount < 0) ".
    "               AND transactions.accountid = (CASE WHEN o.side = 1 THEN o.accountid ELSE o.paymentid END)) >= o.quantity ".
    "               AND o.canceled IS NULL THEN 1 ".
    "           ELSE 0 ".
    "       END) = 0 ".
    "       GROUP BY o.price".
    "       ORDER BY ".($out->entry->orden->type == 2 ? "o.price ASC" : "o.price DESC").", o.date DESC";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
        
    $total = 0;
    
    $refPrice = number_format($out->entry->ask->number, $basecurrency['decimals'], '.', '');
    //$out->test2 = $refPrice;
    while($pairquantity = $res->fetch_assoc()){
        
        if($out->entry->orden->type == 1){
            // Sacamos lo que tiene la orden en total con su precio para ver si podemos completarla toda o no
            
            if($out->entry->orden->basecurrencyid == $currencyid){
                $tempRate = ($pairquantity["qty"] - $pairquantity['totallyfilled']);
                $temptotal = 0;
                
                
                if($tempRate < $acum){
                    $acum = $acum - $tempRate;
                
                    $temptotal = (float)($pairquantity["qty"] - $pairquantity['totallyfilled']);
                    
                    $total += $temptotal; 
                    
                }else if($acum > 0){
                    $temptotal = $acum;
                
                    $total += $temptotal;
                    $acum -= $acum;
                }
            }else if($out->entry->orden->basecurrencyid != $currencyid && $action == 1 ){
                $out->qtys [] = $pairquantity["qty"];
                $tempRate = $pairquantity["price"] * ($pairquantity["qty"] - $pairquantity['totallyfilled']);
                
                if($tempRate < $acum){
                    $acum = $acum - $tempRate;
                    
                    $temptotal = $tempRate;
                    $out->totaltmp [] = $temptotal; 
                    
                    $total += $temptotal;
                    
                }else if($acum > 0){
                    
                    
                    $temptotal = $acum;
                    $out->totaltmp [] = $temptotal; 
                    
                    $total += $temptotal;
                    $acum -= $acum;
                }
            }else{
                $temptotal = 0;
                $tempRate = $pairquantity["qty"] - $pairquantity['totallyfilled'];
                        
                    if($tempRate < $acum){
                        $acum = $acum - $tempRate;
                        
                        $tmpPct = ($tempRate * $pairquantity['price']);
                        $out->temprate3[] = $tmpPct;
                        
                        $temptotal = $tmpPct;
                        $out->totaltmp [] = $temptotal; 
                            
                        $total += $temptotal;
                            
                    }else if($acum > 0){
                        
                        //$tempRate = $;
                        $tmpPct = $acum;
                        $out->temprate3[] = $acum;
                        
                        $temptotal = $tmpPct * $pairquantity["price"];
                        $out->totaltmp [] = $temptotal." 2"; 
                    
                        $total += $temptotal;
                        $acum -= $acum;
                    }
            }
            
        }else{
            
            if($out->entry->orden->type == 2 && $action == 1){
                $tempRate = ($pairquantity["qty"] - $pairquantity['totallyfilled']);
                $temptotal = 0;
                
                //$out->aquies [] = "hola2";
                
                if($tempRate < $acum){
                    $acum = $acum - $tempRate;
                
                    $temptotal = (float)($pairquantity["qty"] - $pairquantity['totallyfilled']);
                    
                    $total += $temptotal; 
                    
                }else if($acum > 0){
                    $temptotal = $acum;
                
                    $total += $temptotal;
                    $acum -= $acum;
                }
            }else{
                $tempRate = ($pairquantity["qty"] - $pairquantity['totallyfilled']) * ($refPrice);
                $temptotal = 0;
                
                //$out->aquies [] = "hola";
                
                if($tempRate < $acum){
                    $acum = $acum - $tempRate;
                
                    $temptotal = (float)($pairquantity["qty"] - $pairquantity['totallyfilled']);
                    
                    $total += $temptotal; 
                    
                }else if($acum > 0){
                    $temptotal = $acum / $refPrice;
                
                    $total += $temptotal;
                    $acum -= $acum;
                }
            }
            
            
            
        }
    }
    
    $out->entry->max = new stdClass();
    $out->entry->max->test = $total;
    $totalTrun = bcdiv(number_format($total,13,'.', ''), '1', ($out->entry->orden->type == 2 ? $out->entry->currency->decimals : $out->entry->refcurrency->decimals));
    $out->entry->max->number = (float)number_format($totalTrun,($out->entry->orden->type == 2 ? $out->entry->currency->decimals : $out->entry->refcurrency->decimals),".","");;
    $out->entry->max->formatted = number_format($out->entry->max->number,($out->entry->orden->type == 2 ? $out->entry->currency->decimals : $out->entry->refcurrency->decimals),",",".");
    
    //Consultamos los datos del usuario para encontrar su fee
    $sql = "SELECT id, usr, type, level ".
    "       FROM users WHERE id = ".$userid;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $userdata = $res->fetch_assoc();
    
    //Inicializamos el nivel en 1
    $level = 1;
    
    //Si el usuario es nivel 0, le colocamos comision de nivel 1
    if($userdata["level"] == 0){
        $level = 1;
    }else{
        $level = $userdata["level"];
    }
    
    // Consultamos las comisiones del par
    $sql = "SELECT * FROM cmspreffees ".
    "       WHERE levelid = ".$level.
    "       AND pairid = ".$out->entry->id.
    "       AND usertype = ".$userdata["type"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $feedata = $res->fetch_assoc();
    
    $out->entry->fees = new stdClass();
    
    // Fee de la blockchain
    if(intval($out->entry->refcurrency->interface) == 4){
        // Obtenemos el fee estimado
        $out->entry->fees->blockchainfee = new stdClass();
        
        $out->entry->fees->blockchainfee->number = determinateFee(intval($out->entry->refcurrency->interface), $BTC_URL, 100);
        $out->entry->fees->blockchainfee->formatted = numberFormatt($out->entry->blockchainfee->number, $out->entry->refcurrency->decimals);
    }else if(intval($out->entry->refcurrency->interface) == 5){
        //AJUSTAR AL VALOR REAL DE PTR
        $out->entry->fees->blockchainfee = new stdClass();
        
        $out->entry->fees->blockchainfee->number = 0;
        $out->entry->fees->blockchainfee->formatted = 0;
    }
    
    //Comisiones para market
    $out->entry->fees->market = new stdClass();
    
    //Si el porcentaje es 0, guardamos el nominal y retornamos el pct en null, y si no, lo hacemos al reves
    if($feedata["pctmktfee"] == 0){
        $out->entry->fees->market->pctfee = null;
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userxchgprefs ".
        "       WHERE pairid = ".$out->entry->id.
        "       AND userid = ".$userdata['id'].
        "       AND preffeesfield = 'nmlmktfee'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->fees->market->nmalfee = new stdClass();
        $out->entry->fees->market->nmalfee->number = (float)$feedata["nmlmktfee"] - ($feedata["nmlmktfee"]/100 * $userExg['exonerated']);
        $out->entry->fees->market->nmalfee->formatted = number_format($out->entry->fees->market->nmalfee->number,($out->entry->orden->type == 2 ? $out->entry->currency->decimals : $out->entry->refcurrency->decimals),",",".");
        
    }else{
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userxchgprefs ".
        "       WHERE pairid = ".$out->entry->id.
        "       AND userid = ".$userdata['id'].
        "       AND preffeesfield = 'pctmktfee'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->fees->market->pctfee = new stdClass();
        $out->entry->fees->market->pctfee->number = (float)$feedata["pctmktfee"] - ($feedata["pctmktfee"]/100 * $userExg['exonerated']);
        $out->entry->fees->market->pctfee->formatted = number_format($out->entry->fees->market->pctfee->number,2,",",".");
        
        $out->entry->fees->market->nmalfee = null;
    }
        
    //Comisiones para limit
    $out->entry->fees->limit = new stdClass();
    
    //Si el porcentaje es 0, guardamos el nominal y retornamos el pct en null, y si no, lo hacemos al reves
    if($feedata["pctlimitfee"] == 0){
        $out->entry->fees->limit->pctfee = null;
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userxchgprefs ".
        "       WHERE pairid = ".$out->entry->id.
        "       AND userid = ".$userdata['id'].
        "       AND preffeesfield = 'nmllimitfee'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->fees->limit->nmalfee = new stdClass();
        $out->entry->fees->limit->nmalfee->number = (float)$feedata["nmllimitfee"] - ($feedata["nmllimitfee"]/100 * $userExg['exonerated']);
        $out->entry->fees->limit->nmalfee->formatted = number_format($out->entry->fees->limit->nmalfee->number,($out->entry->orden->type == 2 ? $out->entry->currency->decimals : $out->entry->currency->decimals),",",".");
        
    }else{
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userxchgprefs ".
        "       WHERE pairid = ".$out->entry->id.
        "       AND userid = ".$userdata['id'].
        "       AND preffeesfield = 'pctlimitfee'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->fees->limit->pctfee = new stdClass();
        $out->entry->fees->limit->pctfee->number = (float)$feedata["pctlimitfee"] - ($feedata["pctlimitfee"]/100 * $userExg['exonerated']);;
        $out->entry->fees->limit->pctfee->formatted = number_format($out->entry->fees->limit->pctfee->number,2,",",".");
        
        $out->entry->fees->limit->nmalfee = null;
    }
    
    
    // Consultamos el minimo en la moneda base
    $sql = "SELECT minexchange ".
    "       FROM cmspreffees ".
    "       WHERE currencyid = ".$out->entry->refcurrency->id.
    "       AND usertype = ".$userdata["type"].
    "       LIMIT 1";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $min = $res->fetch_assoc();
    
    // Retornamos el valor
    $out->entry->min = new stdClass();
    $out->entry->min->number = (float)$min['minexchange'];
    $out->entry->min->formatted = numberFormatt($out->entry->min->number, $out->entry->refcurrency->decimals);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>