<?php
// cms/api/operations/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)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $out->entry = new stdClass();
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    
    //Validamos que la session del usuario sea valida para continuar
    isSessionValidCMS($db, $sessionid);
    
    //Validamos que el usuario tenga privilegios
    if(!tienePrivilegio($db, $sessionid, 33))
        badEnd("403", array("msg"=>"No tiene Privilegios"));
        
    //Consultamos los datos iniciales para saber si era un deposito o retiro
    $sql = "SELECT transactions.id AS transactionid, ".
    "       deposits.transactionid AS depositid, ".
    "       withdrawals.transactionid AS withdrawalid ".
    "       FROM transactions ".
    "       LEFT JOIN deposits ON transactions.id = deposits.transactionid".
    "       LEFT JOIN withdrawals ON transactions.id = withdrawals.transactionid".
    "       WHERE transactions.id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    $row = $rs->fetch_assoc();
    $out->entry->type = new stdClass();
    
    // 1 = DEPOSITO; 2 = RETIRO WN
    //Si el campo depositid es distinto a null significa que es un deposito
    if($row["depositid"] != null){
        
        $out->entry->type->id = 1;
        $out->entry->type->dsc = "Deposito";
        
        $sql = "SELECT transactions.id AS transactionid, ".
        "       transactions.datecreated AS txdatecreated, ".
        "       deposits.valid AS valid, ".
        "       deposits.rejected AS rejected, ".
        "       transactions.dsc AS txdsc, ".
        "       transactions.txid AS txid, ".
        "       transactions.accountid AS txaccountid, ".
        "       transactions.accountdestination AS txaccdestination, ".
        "       deposits.amount AS amount, ".
        "       deposits.fee AS fee, ".
        "       deposits.paymentdate AS paymentdate, ".
        "       deposits.paymentref AS paymentref, ".
        "       deposits.filetype AS filetype ".
        "       FROM transactions, deposits ".
        "       WHERE transactions.id = ".$id.
        "       AND deposits.transactionid = transactions.id";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $txdata = $rs->fetch_assoc();
        
    }else if($row["withdrawalid"] != null){
        
        $out->entry->type->id = 2;
        $out->entry->type->dsc = "Retiro";
        
        $sql = "SELECT transactions.id AS transactionid, ".
        "       transactions.datecreated AS txdatecreated, ".
        "       transactions.dsc AS txdsc, ".
        "       transactions.txid AS txid, ".
        "       transactions.accountid AS txaccountid, ".
        "       transactions.accountdestination AS txaccdestination, ".
        "       withdrawals.valid AS valid, ".
        "       withdrawals.rejected AS rejected, ".
        "       withdrawals.amount AS amount, ".
        "       withdrawals.fee AS fee, ".
        "       withdrawals.createddate AS paymentdate, ".
        "       withdrawals.paymentref AS paymentref, ".
        "       withdrawals.filetype AS filetype ".
        "       FROM transactions, withdrawals ".
        "       WHERE transactions.id = ".$id.
        "       AND withdrawals.transactionid = transactions.id";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $txdata = $rs->fetch_assoc();
        
    }else{
        
        $out->entry->type->id = 3;
        $out->entry->type->dsc = "Transferencia";
        
        $sql = "SELECT transactions.id AS transactionid, ".
        "       transactions.datecreated AS txdatecreated, ".
        "       transactions.datecreated AS valid, ".
        "       transactions.datecreated AS rejected, ".
        "       transactions.dsc AS txdsc, ".
        "       transactions.txid AS txid, ".
        "       transactions.accountid AS txaccountid, ".
        "       transactions.accountorigin AS txaccountorigin, ".
        "       transactions.accountdestination AS txaccdestination, ".
        "       transactions.amount AS amount, ".
        "       transactions.amountghost AS fee, ".
        "       transactions.datecreated AS paymentdate, ".
        "       CASE ".
	    "           WHEN transactions.txid = transactions.id THEN 0 ".
	    "           WHEN transactions.amountghost = 0 AND transactions.txid != transactions.id THEN 1 ".
	    "           WHEN transactions.amountghost != 0 AND transactions.txid = transactions.id THEN 2 ".
	    "           ELSE 0 ".
	    "       END AS status ".
        "       FROM transactions, deposits ".
        "       WHERE transactions.id = ".$id;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $txdata = $rs->fetch_assoc();
    }
    
    //Ordenamos los valores
    $out->entry->id = (int)$txdata["transactionid"];
    
    $out->entry->datecreated = new stdClass();
    $out->entry->datecreated->date = date("Y-m-d H:i", strtotime($txdata["txdatecreated"]));
    $out->entry->datecreated->formatted = date("d/m/Y h:i a", strtotime($txdata["txdatecreated"]));
    
    $out->entry->txid = $txdata["txid"];

    //Validamos el status
    if($txdata["valid"] == null && $txdata["rejected"] == null){
        $out->entry->status = 0;
        $out->entry->rejected = null;
        $out->entry->valid = null;
    }else if($txdata["valid"] == null && $txdata["rejected"] != null){
        $out->entry->status = 2;
        $out->entry->rejected = new stdClass();
        $out->entry->rejected->date = date("Y-m-d H:i", strtotime($txdata["rejected"]));
        $out->entry->rejected->formatted = date("d/m/Y h:i a", strtotime($txdata["rejected"]));
        $out->entry->valid = null;
    }else{
        $out->entry->status = 1;
        $out->entry->valid = new stdClass();
        $out->entry->valid->date = date("Y-m-d H:i", strtotime($txdata["valid"]));
        $out->entry->valid->formatted = date("d/m/Y h:i a", strtotime($txdata["valid"]));
        $out->entry->rejected = null;
    }
    
    if($out->entry->type->id == 3){
        $out->entry->status = $txdata["status"];
    }
    
    $out->entry->dsc = $txdata["txdsc"];
    
    //Datos de la cuenta asociada 
    $sql = "SELECT ".
    "       users.id AS userid, ".
    "       users.usr AS usr, ".
    "       accounts.id AS accountid, ".
    "       accounts.details1 AS accountdetails1, ".
    "       accounts.rejected AS accountrejected, ".
    "       accounts.approved AS accountapproved, ".
    "       accounts.status AS accountstatus, ".
    "       accounts.currencyid AS accountcurrencyid, ".
    "       paymentmethods.id AS paymentmethodid, ".
    "       paymentmethods.dsc AS paymetmenthoddsc ".
    "       FROM accounts, users, paymentmethods ".
    "       WHERE accounts.id = ".( $out->entry->type->id == 3 ? $txdata["txaccountorigin"] : $txdata['txaccountid']).
    "       AND accounts.userid = users.id ".
    "       AND accounts.paymentmethodid = paymentmethods.id";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $accountdata = $res->fetch_assoc();
    
    $out->entry->account = new stdClass();
    $out->entry->account->id = (int)$accountdata["accountid"];
    
    //Consultamos para obtener los nombres del usuario
    $sql = "SELECT userpersons.fname AS personname, ".
    "       userpersons.flastname AS personlastname, ".
    "       usercompanies.name AS companyname, ".
    "       usercompanies.comercialname AS companycomercialname ".
    "       FROM users".
    "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
    "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
    "       WHERE id = ".$accountdata["userid"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $username = $res->fetch_assoc();
        
    //Ordenamos los datos del usuario
    $out->entry->account->user = new stdClass();
    $out->entry->account->user->id = (int)$accountdata["userid"];
    $out->entry->account->user->usr = $accountdata["usr"];
    
    if($username["personname"] == null){
        $out->entry->account->user->fullname = $username["companyname"].( $username["companycomercialname"] == "" ? "" : " / ".$username["companycomercialname"] );
    }else{
        $out->entry->account->user->fullname = $username["personname"].( $username["personlastname"] == "" ? "" : " ".$username["personlastname"] );
    }
    
    $out->entry->account->paymentmethod = new stdClass();
    $out->entry->account->paymentmethod->id = (int)$accountdata["paymentmethodid"];
    $out->entry->account->paymentmethod->dsc = $accountdata["paymetmenthoddsc"];
    
    //Consultamos la wallet(si existejjeje)
    $sql = "SELECT * FROM wallets".
    "       WHERE accountid = ".$out->entry->account->id;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $wallet = $res->fetch_assoc();
    
    $out->entry->account->wallet = $wallet["wallet"];
    
    $sql = "SELECT * FROM currencies WHERE id = ".$accountdata["accountcurrencyid"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $currencydata = $res->fetch_assoc();
        
    $out->entry->account->currency = new stdClass();
    $out->entry->account->currency->id = (int)$currencydata["id"];
    $out->entry->account->currency->name = $currencydata["name"];
    $out->entry->account->currency->symbol = $currencydata["symbol"];
    $out->entry->account->currency->decimals = (int)$currencydata["decimals"];
    $out->entry->account->currency->interface = (int)$currencydata['interface'];
    
    $out->entry->account->status = new stdClass();
    $out->entry->account->status->id = (int)$accountdata["accountstatus"];
    $out->entry->account->status->dsc = $out->entry->account->status->id == 1 ? "Activa" : "Inactiva";
        
    //$out->entry->account->valid = (int)$accountdata["accountvalid"];
    
    if($accountdata["accountrejected"] != null){
        $out->entry->account->valid = -1;
    }else if($accountdata["accountapproved"] != null && $accountdata["accountrejected"] == null){
        $out->entry->account->valid = 1;
    }else{
        $out->entry->account->valid = 0;
    }
        
    //datos del pago
    $out->entry->payment = new stdClass();
    
    $out->entry->payment->date = new stdClass();
    $out->entry->payment->date->canonical = date("Y-m-d", strtotime($txdata["paymentdate"]));
    $out->entry->payment->date->formatted = date("d/m/Y", strtotime($txdata["paymentdate"]));
    
    $out->entry->payment->ref = $txdata["paymentref"];
    $out->entry->payment->filetype = $txdata["filetype"];
    
    //Buscamos el archivo para obtener su nombre y extension
    $filestest = glob("../../../app/api/uploads/payments/".$out->entry->id.".{jpg,png,jpeg}", GLOB_BRACE);
    //El primer resultado
    $info = pathinfo($filestest[0]);
    //Url dentro de la carpeta api
    $out->entry->payment->url = $txdata["filetype"] == null ? null : "../app/api/uploads/payments/".$info["basename"];
    
    // 1 = DEPOSITO; 2 = RETIRO WN
    //Datos de la cuenta de AFX DEPOSITOS
    //Si no existe acc destination es por que es un retiro
    if($out->entry->type->id == 2){
        $sql = "SELECT * FROM withdrawals WHERE transactionid = ".$out->entry->id;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $accountdata = $res->fetch_assoc();
        
        if($accountdata["paymentwallet"] != null){
            $out->entry->userpaymentmethod = new stdClass();
            $out->entry->userpaymentmethod->wallet = $accountdata["paymentwallet"];
        }else{
            $out->entry->userpaymentmethod = new stdClass();
        
            $sql = "SELECT ".
            "       users.id AS userid, ".
            "       users.usr AS usr, ".
            "       accounts.id AS accountid, ".
            "       accounts.details1 AS accountdetails1, ".
            "       accounts.details2 AS accountdetails2, ".
            "       accounts.details3 AS accountdetails3, ".
            "       accounts.details4 AS accountdetails4, ".
            "       accounts.currencyid AS accountcurrencyid, ".
            "       paymentmethods.id AS paymentmethodid, ".
            "       paymentmethods.dsc AS paymetmenthoddsc, ".
            "       paymentmethods.details1 AS paymentmethoddetails1, ".
            "       paymentmethods.details2 AS paymentmethoddetails2, ".
            "       paymentmethods.details3 AS paymentmethoddetails3, ".
            "       paymentmethods.details4 AS paymentmethoddetails4 ".
            "       FROM accounts, users, paymentmethods ".
            "       WHERE accounts.id = ".$accountdata["paymentaccountid"].
            "       AND accounts.userid = users.id ".
            "       AND accounts.paymentmethodid = paymentmethods.id";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
            
            $paymentaccountdata = $res->fetch_assoc();

            $out->entry->userpaymentmethod->id = (int)$paymentaccountdata["accountid"];
            
            //Ordenamos los datos del usuario
            $out->entry->userpaymentmethod->user = new stdClass();
            $out->entry->userpaymentmethod->user->id = (int)$paymentaccountdata["userid"];
            $out->entry->userpaymentmethod->user->fullname = $paymentaccountdata["usr"];
            
            $out->entry->userpaymentmethod->paymentmethod = new stdClass();
            $out->entry->userpaymentmethod->paymentmethod->id = (int)$paymentaccountdata["paymentmethodid"];
            $out->entry->userpaymentmethod->paymentmethod->dsc = $paymentaccountdata["paymetmenthoddsc"];
            $out->entry->userpaymentmethod->paymentmethod->details1 = $paymentaccountdata["paymentmethoddetails1"];
            $out->entry->userpaymentmethod->paymentmethod->details2 = $paymentaccountdata["paymentmethoddetails2"];
            $out->entry->userpaymentmethod->paymentmethod->details3 = $paymentaccountdata["paymentmethoddetails3"];
            $out->entry->userpaymentmethod->paymentmethod->details4 = $paymentaccountdata["paymentmethoddetails4"];
            
            //Consultamos la wallet(si existejjeje)
            $sql = "SELECT * FROM wallets".
            "       WHERE accountid = ".$out->entry->userpaymentmethod->id;
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>$db->error));
                
            $wallet = $res->fetch_assoc();
            
            $out->entry->userpaymentmethod->wallet = $wallet["wallet"];
            
            $sql = "SELECT * FROM currencies WHERE id = ".$paymentaccountdata["accountcurrencyid"];
            if (!$res=$db->query($sql))
                 badEnd("500", array("msg"=>$db->error));
                
            $currencydata = $res->fetch_assoc();
            
            $out->entry->userpaymentmethod->currency = new stdClass();
            $out->entry->userpaymentmethod->currency->id = (int)$currencydata["id"];
            $out->entry->userpaymentmethod->currency->name = $currencydata["name"];
            $out->entry->userpaymentmethod->currency->symbol = $currencydata["symbol"];
            
            $out->entry->userpaymentmethod->details1 = $paymentaccountdata["accountdetails1"];
            $out->entry->userpaymentmethod->details2 = $paymentaccountdata["accountdetails2"];
            $out->entry->userpaymentmethod->details3 = $paymentaccountdata["accountdetails3"];
            $out->entry->userpaymentmethod->details4 = $paymentaccountdata["accountdetails4"];
        }
    }else if($txdata["txaccdestination"] == null){
        $out->entry->userpaymentmethod = null;
    }else {
        $out->entry->userpaymentmethod = new stdClass();
        
        $sql = "SELECT ".
        "       users.id AS userid, ".
        "       users.usr AS usr, ".
        "       accounts.id AS accountid, ".
        "       accounts.details1 AS accountdetails1, ".
        "       accounts.details2 AS accountdetails2, ".
        "       accounts.details3 AS accountdetails3, ".
        "       accounts.details4 AS accountdetails4, ".
        "       accounts.currencyid AS accountcurrencyid, ".
        "       paymentmethods.id AS paymentmethodid, ".
        "       paymentmethods.dsc AS paymetmenthoddsc, ".
        "       paymentmethods.details1 AS paymentmethoddetails1, ".
        "       paymentmethods.details2 AS paymentmethoddetails2, ".
        "       paymentmethods.details3 AS paymentmethoddetails3, ".
        "       paymentmethods.details4 AS paymentmethoddetails4 ".
        "       FROM accounts, users, paymentmethods ".
        "       WHERE accounts.id = ".$txdata["txaccdestination"].
        "       AND accounts.userid = users.id ".
        "       AND accounts.paymentmethodid = paymentmethods.id";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $accountdata = $res->fetch_assoc();

        $out->entry->userpaymentmethod->id = (int)$accountdata["accountid"];
            
        //Ordenamos los datos del usuario
        $out->entry->userpaymentmethod->user = new stdClass();
        $out->entry->userpaymentmethod->user->id = (int)$accountdata["userid"];
        $out->entry->userpaymentmethod->user->fullname = $accountdata["usr"];
        
        $out->entry->userpaymentmethod->paymentmethod = new stdClass();
        $out->entry->userpaymentmethod->paymentmethod->id = (int)$accountdata["paymentmethodid"];
        $out->entry->userpaymentmethod->paymentmethod->dsc = $accountdata["paymetmenthoddsc"];
        $out->entry->userpaymentmethod->paymentmethod->details1 = $accountdata["paymentmethoddetails1"];
        $out->entry->userpaymentmethod->paymentmethod->details2 = $accountdata["paymentmethoddetails2"];
        $out->entry->userpaymentmethod->paymentmethod->details3 = $accountdata["paymentmethoddetails3"];
        $out->entry->userpaymentmethod->paymentmethod->details4 = $accountdata["paymentmethoddetails4"];
        
        //Consultamos la wallet(si existejjeje)
        $sql = "SELECT * FROM wallets".
        "       WHERE accountid = ".$out->entry->userpaymentmethod->id;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $wallet = $res->fetch_assoc();
        
        $out->entry->userpaymentmethod->wallet = $wallet["wallet"];
        
        $sql = "SELECT * FROM currencies WHERE id = ".$accountdata["accountcurrencyid"];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $currencydata = $res->fetch_assoc();
            
        $out->entry->userpaymentmethod->currency = new stdClass();
        $out->entry->userpaymentmethod->currency->id = (int)$currencydata["id"];
        $out->entry->userpaymentmethod->currency->name = $currencydata["name"];
        $out->entry->userpaymentmethod->currency->symbol = $currencydata["symbol"];
        
        $out->entry->userpaymentmethod->details1 = $accountdata["accountdetails1"];
        $out->entry->userpaymentmethod->details2 = $accountdata["accountdetails2"];
        $out->entry->userpaymentmethod->details3 = $accountdata["accountdetails3"];
        $out->entry->userpaymentmethod->details4 = $accountdata["accountdetails4"];
    }
    
    //Si es una transferencia necesitamos consultar el movimiento con su amountghost
    if($out->entry->type->id == 3){
        //Consultamos el movimiento de comision de la cuenta
        $sql = "SELECT * FROM transactions".
        "       WHERE id != ".$out->entry->id.
        "       AND txid = ".$out->entry->id.
        "       AND accountid = ".$out->entry->account->id;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $res->fetch_assoc();
        
        //Monto del movimiento
        $out->entry->amount = new stdClass();
        $out->entry->amount->number = ($txdata["amount"] + $txdata["amountghost"]) + ($row["amount"] + $row["amountghost"]);
        $out->entry->amount->formatted = numberFormatt($out->entry->amount->number,$currencydata["decimals"]);
    }else{
        //Monto del movimiento
        $out->entry->amount = new stdClass();
        $out->entry->amount->number = (float)$txdata["amount"];
        $out->entry->amount->formatted = numberFormatt($out->entry->amount->number,$currencydata["decimals"]);
    }
    
    //Si es una transferencia necesitamos consultar el movimiento con su comision
    if($out->entry->type->id == 3){
        //Consultamos el movimiento de comision de la cuenta
        $sql = "SELECT * FROM transactions".
        "       WHERE id != ".$out->entry->id.
        "       AND txid = ".$out->entry->id.
        "       AND accountid = ".$out->entry->account->id;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $row = $res->fetch_assoc();
        //Comision del movimiento
        $out->entry->fee = new stdClass();
        $out->entry->fee->number = abs((float)$row["amount"] + $row["amountghost"]);
        $out->entry->fee->formatted = numberFormatt($out->entry->fee->number,$currencydata["decimals"]);
    }else{
        //Comision del movimiento
        $out->entry->fee = new stdClass();
        $out->entry->fee->number = (float)$txdata["fee"];
        $out->entry->fee->formatted = numberFormatt($out->entry->fee->number,$currencydata["decimals"]);
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
