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

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../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);
    
    //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"=>$db->error));
        
    $row = $rs->fetch_assoc();
    //Guardamos el id del usuario
    $userid = $row["id"];
    
    //Consultamos los datos requeridos
    $sql = "SELECT * FROM accounts WHERE userid = ".$userid.
    "       AND id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    //Ordenamos el resultado
    $row = $rs->fetch_assoc();
    
    //En caso de que no existan registros retornamos 404
    if($row["id"] == null){
        badEnd("404", array("msg"=>"No encontrado"));
    }
    
    $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 dsc".
    "       FROM paymentmethods".
    "       WHERE id = ".$row["paymentmethodid"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $payment = $res->fetch_assoc();
    //Guardamos el nombre del metodo de pago
    $out->entry->paymentmethod->dsc = $payment["dsc"];
        
    //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"=>$db->error));
        
    $currency = $res->fetch_assoc();
    //Guardamos los detalles de la moneda
    $out->entry->currency->dsc = $currency["name"];
    $out->entry->currency->symbol = $currency["symbol"];
    
    //Cuenta valida
    $out->entry->valid = new stdClass();
    
    if($row["rejected"] != null){
        $out->entry->valid->id = -1;
    }else if($row["approved"] != null && $row["rejected"] == null){
        $out->entry->valid->id = 1;
    }else{
        $out->entry->valid->id = 0;
    }
        
    //$out->entry->valid->id = (int)$row["valid"];
    $out->entry->valid->dsc = validateAccount($out->entry->valid->id);
    
    //Balance de la cuenta
    $sql = "SELECT SUM(amount) as qty FROM transactions WHERE accountid = ".$out->entry->id;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    $balancetx = $res->fetch_assoc();
        
    $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 = ".$out->entry->id.
	"           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 = ".$out->entry->id.
    "           AND orders.accountid = ".$out->entry->id.
	"           AND orders.canceled IS NULL ".
	"           AND transactions.amount < 0 ".
	"           AND orders.type != 1 ".
    "       ) amount";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    $balanceorder = $res->fetch_assoc();
        
    //Balance a partir de las transacciones
    $out->entry->balance = new stdClass();
    $out->entry->balance->number = (float)($balancetx["qty"] - $balanceorder["qty"]);
    $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;
    if (!$result=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $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 = null;
    }
        
    //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;
    }
?>
