<?php
// app/api/accounts/entry

    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id");
    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"];
    $id = $_GET["id"];
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Consultamos los datos del usuario por su ssid
    $sql = "SELECT id, usr FROM users WHERE sessionid = '".$sessionid."'";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $rs->fetch_assoc();
    //Guardamos el id del usuario
    $userid = $row["id"];
    
    //Consultamos los datos requeridos
    $sql = "SELECT * FROM accounts WHERE entityusrid = -1 ".
    "       AND userid = ".$userid.
    "       AND id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    //Ordenamos el resultado
    $row = $rs->fetch_assoc();
    
    //En caso de que no existan registros retornamos 404
    if($row["id"] == null){
        badEnd("404", array("msg"=>determinateMsgFail(array(
            "esp"=>"No se encuentra el registro",
            "eng"=>"Cannot find the record"), $lang, "No se encuentra el registro")));
    }
    
    $out->entry = new stdClass();
    //Guardamos el id de la cuenta
    $out->entry->id = (int)$row["id"];
        
    //Metodo de pago
    $out->entry->paymentmethod = new stdClass();
    $out->entry->paymentmethod->id = (int)$row["paymentmethodid"];
    
    //Consultamos el nombre del metodo de pago
    $sql = "SELECT * ".
    "       FROM paymentmethods".
    "       WHERE id = ".$row["paymentmethodid"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $payment = $res->fetch_assoc();
    //Guardamos el nombre del metodo de pago
    $out->entry->paymentmethod->dsc = $payment["dsc"];
    //Guardamos el nombre del metodo de pago
    //$out->entry->paymentmethod->dsc = $payment["paymentdsc"];
    $cant = 0;
    if($payment["details1"] != null)$cant = $cant + 1;
    if($payment["details2"] != null)$cant = $cant + 1;
    if($payment["details3"] != null)$cant = $cant + 1;
    if($payment["details4"] != null)$cant = $cant + 1;
        
    //Moneda de la cuenta
    $out->entry->currency = new stdClass();
    $out->entry->currency->id = (int)$row["currencyid"];
        
    //Consultamos los datos de la moneda
    $sql = "SELECT * FROM currencies WHERE id = ".$row["currencyid"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currency = $res->fetch_assoc();
    //Guardamos los detalles de la moneda
    $out->entry->currency->dsc = $currency["name"];
    $out->entry->currency->symbol = $currency["symbol"];
    $out->entry->currency->interface = $currency["interface"];
    
    //Cuenta valida
    $out->entry->valid = new stdClass();
    
     $out->entry->valid = new stdClass();
        
        if($row["rejected"] != null){
             $out->entry->valid->id = -1;
        }else if($row["approved"] != null && $row["rejected"] == null && $cant==count(explode(",", $row["approved"]))){
             $out->entry->valid->id = 1;
        }else{
             $out->entry->valid->id = 0;
        }
        
         $out->entry->valid->dsc = validateAccount( $out->entry->valid->id);
    
    //Balance de la cuenta
    $sql = "SELECT SUM(amount) - ABS(IF(( ".
    "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
    "           FROM orders ".
    "           WHERE orders.accountid = ".$out->entry->id.
	"           AND orders.canceled IS NULL ".
	"           AND orders.type != 1) IS NOT NULL,  ".
	"               ( ".
    "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
    "           FROM orders ".
    "           WHERE orders.accountid = ".$out->entry->id.
	"           AND orders.canceled IS NULL ".
	"           AND orders.type != 1), 0)".
    "       + IF(( ".
    "           SELECT SUM(transactions.amount) AS amount ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND transactions.accountid = ".$out->entry->id.
    "           AND orders.accountid = ".$out->entry->id.
	"           AND orders.canceled IS NULL ".
	"           AND transactions.amount < 0 ".
	"           AND orders.type != 1) IS NOT NULL, ( ".
    "           SELECT SUM(transactions.amount) AS amount ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND transactions.accountid = ".$out->entry->id.
    "           AND orders.accountid = ".$out->entry->id.
	"           AND orders.canceled IS NULL ".
	"           AND transactions.amount < 0 ".
	"           AND orders.type != 1),0) ".
	"      + IF ((SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
	"           FROM transactions  ".
	"           WHERE transactions.paypending = 1".
	"           AND transactions.accountid = ".$out->entry->id.
	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)) IS NOT NULL, ".
	"           (SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
	"           FROM transactions  ".
	"           WHERE transactions.paypending = 1".
	"           AND transactions.accountid = ".$out->entry->id.
	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)), 0)".
	"      ) as qty FROM transactions WHERE accountid = ".$out->entry->id.
    "       AND paypending = 0";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $balancetx = $res->fetch_assoc();
        
    //Balance a partir de las transacciones
    $out->entry->balance = new stdClass();
    $out->entry->balance->number = (float)bcdiv(number_format($balancetx["qty"],13,'.',''), '1', $currency["decimals"]);
    $out->entry->balance->number = $out->entry->balance->number < 0 ? 0 : $out->entry->balance->number;
    $out->entry->balance->formatted = numberFormatt($out->entry->balance->number,$currency["decimals"]);
    
    //Wallet = null si no existe, si existe retornamos sus valores
    //$sql = "SELECT * FROM wallets WHERE accountid = ".$out->entry->id;

    //Se retorna la información de la billetera activa (la más nueva)
    //En front no había problema con los depositos (USDT) que se ignoran las vencidas, debído a que Magi usó el details1 y este parece mantenerse actualizado
    //Sin embargo se mostraba la fecha enviada en el wallet->expiry por lo que parecía estar vencída a pesar de mostrar la wallet nueva
    //Este cambio se realizó en front al mismo tiempo que se ajusta este query. Valor obtenido proviene del wallet->dsc
    $sql =  "SELECT     wallets.* ".
            "FROM       wallets " .
            "INNER JOIN ( " .
            "               SELECT w.wallet,w.accountid, MAX(w.expirationDate) AS expirationDate, MAX(id) AS id ".
            "               FROM wallets w WHERE w.accountid = ".$out->entry->id. " GROUP BY w.accountid " .
            "           ) lasts ".
            "ON         wallets.id = lasts.id " . 
            "WHERE      wallets.accountid = ".$out->entry->id. " " .
            "AND        wallets.expirationDate > DATE_SUB(NOW(), INTERVAL 1 DAY)";
    if (!$result=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $wallet = $result->fetch_assoc();
    
    if($wallet["id"] != null){
        $out->entry->wallet = new stdClass();
        $out->entry->wallet->id = (int)$wallet["id"];
        
        $out->entry->wallet->expiry = new stdClass();
        $out->entry->wallet->expiry->date = $wallet["expirationDate"];
        $out->entry->wallet->expiry->formatted = date("d/m/Y", strtotime($wallet["expirationDate"]));
        
        $out->entry->wallet->dsc = $wallet["wallet"];
    }else{
        $out->entry->wallet = new stdClass();
        $out->entry->wallet->id = (int)-1;
        
        $out->entry->wallet->expiry = new stdClass();
        $out->entry->wallet->expiry->date = "";
        $out->entry->wallet->expiry->formatted = "";
        
        $out->entry->wallet->dsc = "";
    }
        
    //Datos de la cuenta
    $out->entry->status = (int)$row["status"];
    $out->entry->deleteable = $out->entry->status == 0 ? true : false;
    //Detalles de la cuenta
    //$out->entry->status = (int)$row["accountstatus"];
    //$out->entry->deleteable = $out->entry->status == 0 ? true : false;
    $rejecteddetails = explode(",", $row["rejected"]);
    $approveddetails = explode(",", $row["approved"]);
    $out->entry->details1 = new stdClass();
    $out->entry->details1->valid = validateField("details1", $rejecteddetails, $approveddetails);
    $out->entry->details1->value = $row["details1"];
        
    $out->entry->details2 = new stdClass();
    $out->entry->details2->valid = validateField("details2", $rejecteddetails, $approveddetails);;
    $out->entry->details2->value = $row["details2"];
        
    $out->entry->details3 = new stdClass();
    $out->entry->details3->valid = validateField("details3", $rejecteddetails, $approveddetails);;
    $out->entry->details3->value = $row["details3"];
        
    $out->entry->details4 = new stdClass();
    $out->entry->details4->valid = validateField("details4", $rejecteddetails, $approveddetails);;
    $out->entry->details4->value = $row["details4"];
    
    
     /*  Funcion que valida el campo si fue rechazado, aceptado o sigue en espera
    *   $field = Campo que se esta validando
    *   $rejecteds = arreglo con campos rechazados
    *   $approveds = arreglo con campos aceptados
    */
    function validateField($field, $rejecteds, $approveds){
        
        foreach($rejecteds as $rejected){
            if($rejected == $field){
                return -1;
            }
        }
        
        foreach($approveds as $approved){
            if($approved == $field){
                return 1;
            }
        }
        
        return 0;
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
    
    /*  Funcion para validar estado de la cuenta
    *   0 = Pendiente por verificar
    *   1 = Aprobada
    *   -1 = Rechazada
    */
    function validateAccount($valid){
        $strres = "";
        
        switch($valid){
            case 0:
                $strres = "Pendiente";
                break;
            case 1:
                $strres = "Activa";
                break;
            case -1:
                $strres = "Rechazada";
                break;
        }
        
        return $strres;
    }
?>
