<?php
// app/api/fees/entry

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","currencyid");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out = new stdClass();
    $sessionid = $_GET["sessionid"];
    $currencyid = $_GET["currencyid"];
    $getFeeFailed = false;
    $currenciesFailed = [];
    
    //Ordenamos los datos
    $out->entry = new stdClass();
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    //Consultamos los datos del usuario para encontrar su fee
    $sql = "SELECT id, usr, type, level ".
    "       FROM users WHERE sessionid = '".$sessionid."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $userdata = $rs->fetch_assoc();
    
    $level = 1;
    
    if($userdata["level"] == 0){
        $level = 1;
    }else{
        $level = $userdata["level"];
    }
    
    // Consultamos los datos de la moneda
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currencydata = $rs->fetch_assoc();
    
    // Fee de la blockchain
    if(intval($currencydata['interface']) == 4){
        // Obtenemos el fee estimado
        $fee = determinateFee(intval($currencydata['interface']), $BTC_URL, 10);
        if (is_null($fee)) {
            $getFeeFailed = true;
            array_push($currenciesFailed, $currencydata['symbol']);
        }
        
        $out->entry->blockchainfee = new stdClass();
        
        $out->entry->blockchainfee->number = (float)number_format($getFeeFailed ? 0 : $fee,$currencydata['decimals'],'.','');
        $out->entry->blockchainfee->formatted = numberFormatt($out->entry->blockchainfee->number, $currencydata['decimals']);
    }else if(intval($currencydata['interface']) == 5){
        $out->entry->blockchainfee = new stdClass();
        // Obtenemos el fee estimado
        $fee = determinateFee(intval($currencydata['interface']), $TCV_URL, 10, $VERSION_API, $TCV_JWT);
        if (is_null($fee)) {
            $getFeeFailed = true;
            array_push($currenciesFailed, $currencydata['symbol']);
        }
        
        $out->entry->blockchainfee->number = (float)number_format($getFeeFailed ? 0 : $fee,$currencydata['decimals'],'.','');
        $out->entry->blockchainfee->formatted = numberFormatt($out->entry->blockchainfee->number, $currencydata['decimals']);
    }else if(intval($currencydata['interface']) == 6){
        // Obtenemos el fee estimado
        $out->entry->blockchainfee = new stdClass();
        
        $out->entry->blockchainfee->number = (float)number_format(0,$currencydata['decimals'],'.','');
        $out->entry->blockchainfee->formatted = numberFormatt($out->entry->blockchainfee->number, $currencydata['decimals']);
    }else if(intval($currencydata['interface']) == 7){
        // Obtenemos el fee estimado
        $fee = determinateFee(intval($currencydata['interface']), $DASH_URL, 10);
        
        $out->entry->blockchainfee = new stdClass();
        
        if (is_null($fee)) {
            $getFeeFailed = true;
            array_push($currenciesFailed, $currencydata['symbol']);
        }
        
        $out->entry->blockchainfee->number = (float)number_format($getFeeFailed ? 0 : $fee,$currencydata['decimals'],'.','');
        $out->entry->blockchainfee->formatted = numberFormatt($out->entry->blockchainfee->number, $currencydata['decimals']);
    }
    
    //Consultamos las comisiones con los datos del usuario
    $sql = "SELECT * FROM cmspreffees ".
    "       WHERE levelid = ".$level.
    "       AND currencyid = ".$currencyid.
    "       AND usertype = ".$userdata["type"];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
            
    $feedata = $rs->fetch_assoc();
    
    //Comisiones para depositos
    $out->entry->deposits = new stdClass();
    
    if($feedata["pctfeedeposits"] == 0){
        $out->entry->deposits->pctfee = null;
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
        "       WHERE currencyid = ".$currencyid.
        "       AND userid = ".$userid.
        "       AND preffeesfield = 'nmlfeedeposits'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->deposits->nmalfee = new stdClass();
        $out->entry->deposits->nmalfee->number = (float)number_format($feedata["nmlfeedeposits"] - ($feedata["nmlfeedeposits"]/100 * $userExg['exonerated']),$currencydata['decimals'],'.','');
        $out->entry->deposits->nmalfee->formatted = numberFormatt($out->entry->deposits->nmalfee->number,$currencydata['decimals']);
        
    }else{
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
        "       WHERE currencyid = ".$currencyid.
        "       AND userid = ".$userid.
        "       AND preffeesfield = 'pctfeedeposits'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->deposits->pctfee = new stdClass();
        $out->entry->deposits->pctfee->number = (float)number_format($feedata["pctfeedeposits"] - ($feedata["pctfeedeposits"]/100 * $userExg['exonerated']), 3,'.','');
        $out->entry->deposits->pctfee->formatted = number_format($out->entry->deposits->pctfee->number,3,",",".");
        
        $out->entry->deposits->nmalfee = null;
    }
    
    $out->entry->deposits->min = new stdClass();
    $out->entry->deposits->min->number = (float)number_format($feedata['mindeposit'], $currencydata['decimals'],'.','');
    $out->entry->deposits->min->formatted = numberFormatt($out->entry->deposits->min->number, $currencydata['decimals']);
    
    if(floatval($feedata["maxamountmonthlyopdeposits"]) == 0){
        $out->entry->deposits->max = null;
    }else{
        $out->entry->deposits->max = new stdClass();
        $out->entry->deposits->max->number = (float)number_format($feedata['maxamountmonthlyopdeposits'], $currencydata['decimals'],'.','');
        $out->entry->deposits->max->formatted = numberFormatt($out->entry->deposits->max->number, $currencydata['decimals']);
    }
    
    //Comisiones para retiros
    $out->entry->withdrawals = new stdClass();
    
    if($feedata["pctfeewithdrawals"] == 0){
        $out->entry->withdrawals->pctfee = null;
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
        "       WHERE currencyid = ".$currencyid.
        "       AND userid = ".$userid.
        "       AND preffeesfield = 'nmlfeewithdrawals'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->withdrawals->nmalfee = new stdClass();
        $out->entry->withdrawals->nmalfee->number = (float)number_format($feedata["nmlfeewithdrawals"] - ($feedata["nmlfeewithdrawals"]/100 * $userExg['exonerated']), $currencydata['decimals'],'.','');
        $out->entry->withdrawals->nmalfee->formatted = numberFormatt($out->entry->withdrawals->nmalfee->number,$currencydata['decimals']);
    
    }else{
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
        "       WHERE currencyid = ".$currencyid.
        "       AND userid = ".$userid.
        "       AND preffeesfield = 'pctfeewithdrawals'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->withdrawals->pctfee = new stdClass();
        $out->entry->withdrawals->pctfee->number = (float)number_format($feedata["pctfeewithdrawals"] - ($feedata["pctfeewithdrawals"]/100 * $userExg['exonerated']), 3,'.','');
        $out->entry->withdrawals->pctfee->formatted = number_format($out->entry->withdrawals->pctfee->number,3,",",".");
        
        $out->entry->withdrawals->nmalfee = null;
    }
    
    $out->entry->withdrawals->min = new stdClass();
    $out->entry->withdrawals->min->number = (float)number_format($feedata['minwithdraw'], $currencydata['decimals'],'.','');
    $out->entry->withdrawals->min->formatted = numberFormatt($out->entry->withdrawals->min->number, $currencydata['decimals']);
    
    if(floatval($feedata['maxamountmonthlyopwithdrawals']) == 0){
        $out->entry->withdrawals->max = null;
    }else{
        $out->entry->withdrawals->max = new stdClass();
        $out->entry->withdrawals->max->number = (float) number_format($feedata['maxamountmonthlyopwithdrawals'], $currencydata['decimals'],'.','');
        $out->entry->withdrawals->max->formatted = numberFormatt($out->entry->withdrawals->max->number, $currencydata['decimals']);
    }
    
    
    //Comisiones para retiros
    $out->entry->xfer = new stdClass();
    
    if($feedata["pctfeexfer"] == 0){
        $out->entry->xfer->pctfee = null;
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
        "       WHERE currencyid = ".$currencyid.
        "       AND userid = ".$userid.
        "       AND preffeesfield = 'nmlfeesxfer'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->xfer->nmalfee = new stdClass();
        $out->entry->xfer->nmalfee->number = (float) number_format($feedata["nmlfeesxfer"] - ($feedata["nmlfeesxfer"]/100 * $userExg['exonerated']), $currencydata['decimals'],'.','');
        $out->entry->xfer->nmalfee->formatted = numberFormatt($out->entry->xfer->nmalfee->number,$currencydata['decimals']);
    
    }else{
        
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
        "       WHERE currencyid = ".$currencyid.
        "       AND userid = ".$userid.
        "       AND preffeesfield = 'pctfeexfer'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $out->entry->xfer->pctfee = new stdClass();
        $out->entry->xfer->pctfee->number = (float)number_format($feedata["pctfeexfer"] - ($feedata["pctfeexfer"]/100 * $userExg['exonerated']), 3,'.','');
        $out->entry->xfer->pctfee->formatted = number_format($out->entry->xfer->pctfee->number,3,",",".");
        
        $out->entry->xfer->nmalfee = null;
    }
    
    $out->entry->xfer->min = new stdClass();
    $out->entry->xfer->min->number = (float) number_format($feedata['minxfer'], $currencydata['decimals'],'.','');
    $out->entry->xfer->min->formatted = numberFormatt($out->entry->xfer->min->number, $currencydata['decimals']);
    if(floatval($feedata['maxamountmonthlyopxfer']) == 0){
        $out->entry->xfer->max = null;
    }else{
        $out->entry->xfer->max = new stdClass();
        $out->entry->xfer->max->number = (float) number_format($feedata['maxamountmonthlyopxfer'], $currencydata['decimals'],'.','');
        $out->entry->xfer->max->formatted = numberFormatt($out->entry->xfer->max->number, $currencydata['decimals']);
    }
    
    if ($getFeeFailed) {
        header("HTTP/1.1 502");
        echo (json_encode(array("msg"=>'Cuenta'.(count($currenciesFailed) > 0 ? 's' : '')." no creada".(count($currenciesFailed) > 0 ? 's' : '')." por falla de conexión")));
        die();
    } else {
        header("HTTP/1.1 200");
        echo (json_encode($out));
        die();
    }
?>