<?php
// cms/api/operations/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)));
    
    //Declaramos e inicializamos nuestras variables
    $out = new stdClass();
    $out->entry = new stdClass();
    $sessionid = mysqli_real_escape_string($db, $_GET["sessionid"]);
    $id = mysqli_real_escape_string($db, $_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, ".
    "       transactions.dsc AS dsc, ".
    "       deposits.transactionid AS depositid, ".
    "       withdrawals.transactionid AS withdrawalid, ".
    "       pmd.transactionid AS pagomovildetailid ".
    "       FROM transactions ".
    "       LEFT JOIN deposits ON transactions.id = deposits.transactionid".
    "       LEFT JOIN withdrawals ON transactions.id = withdrawals.transactionid".
    "       LEFT JOIN pagomovildetails pmd ON transactions.id = pmd.transactionid " .
    "       WHERE transactions.id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $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.paypending AS paypending, ".
        "       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.ref AS ref, ".
        "       deposits.pagomovilbankid AS pagomovilbankid, ".
        "       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"=>determinateDBError($db)));
        
        $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.paypending AS paypending, ".
        "       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.ref AS ref, ".
        "       withdrawals.createddate AS paymentdate, ".
        "       withdrawals.paymentref AS paymentref, ".
        "       withdrawals.paymentwallet AS paymentwallet, ".
        "       withdrawals.pagomovilbankid AS pagomovilbankid, ".
        "       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"=>determinateDBError($db)));
        
        $txdata = $rs->fetch_assoc();
        
    }else if($row['pagomovildetailid'] != null){

        $out->entry->type->id = 5;
        
        $out->entry->type->dsc = "Cripto Pago";

        //Movimientos de comisiones
        $sqlPMAll =     "       SELECT          t.id AS transactionid, ".
                        "                       t.txid AS txid, " .
                        "                       t.datecreated AS txdatecreated, ".
                        "                       t.datecreated AS valid, ".
                        "                       t.datecreated AS rejected, ".
                        "                       t.dsc AS txdsc, ".
                        "                       t.paypending AS paypending, ".
                        "                       t.accountid AS txaccountid, ".
                        "                       t.accountorigin AS txaccountorigin, ".
                        "                       t.accountdestination AS txaccdestination, ".
                        "                       t.amount AS amount, ".
                        "                       0 AS fee, ".
                        "                       t.datecreated AS paymentdate, ".
    			        "                       IF(adest.paymentmethodid <> -7, 'Comisi&oacuten', 'Cripto Pago') AS typedsc, ".
    			        "                       IF(adest.paymentmethodid <> -7, 'FEE', 'PMPAY') AS type, " .                                      
                        "                       IF(t.paypending = 0, 1, 0) AS status, " .                                             
                        "                       IF(t.paypending = 0, 'Aprobado', 'Pendiente') AS statusorder, " .
                        "                       a.currencyid AS currencyaccid, " .
                        "                       adest.paymentmethodid " . //De acá sabermos si es un fee o el otro
    			        "       FROM            transactions t " .
        		        "       INNER JOIN      accounts a ON t.accountid = a.id ".                        
        		        "                       ".$time.
                        "                       AND a.paymentmethodid = -1 " .
                        "                       AND a.entityusrid = -1 ".
        		        "       INNER JOIN      pagomovildetails pd ON pd.transactionid = t.txid ".
    			        "       LEFT JOIN       accounts adest ON adest.id = t.accountdestination" .
                        "       INNER JOIN      ( " . //Nos traemos los movimientos que coincidan con el id encontrado
                        "           SELECT txid FROM transactions WHERE transactions.id = ".$id." " .
                        "       ) transacts ON transacts.txid = t.txid " .
                        "       WHERE           t.paypending = 0 AND t.validator IS NULL ". //Filtro los que si se confirmaron con código    
    			        "       ORDER BY        t.id ";

        $sql =  "SELECT     A.*, ".
                "           pd.phone AS phone, " .
                "           pd.docid AS doc, ".
                "           pd.bankname AS bankname, ".
                "           pd.amounttx AS amountves, ".
                "           pd.notes AS notes, ".
                "           pd.pagomovilbankid AS pagomovilbankid, ".
                "           currfiat.decimals AS currfiatdecimals, " .
                "           currfiat.symbol AS currfiatsymbol, " .
                "           feeCrip.amount AS feecripto, " .
                "           feeWith.amount AS feewithd, " .
                "           curr.decimals AS currdecimals, " .
                "           curr.symbol AS currsymbol, " .
                "           pd.ref AS ref " .
                "FROM       (  ".$sqlPMAll." ) A " .                
        	    "INNER JOIN pagomovildetails pd ON pd.transactionid = A.transactionid ".
                "LEFT JOIN  (  ".$sqlPMAll." ) feeCrip " .
                "ON         feeCrip.txid = A.txid AND feeCrip.paymentmethodid = -6 " .
                "LEFT JOIN  (  ".$sqlPMAll." ) feeWith " .
                "ON         feeWith.txid = A.txid AND feeWith.paymentmethodid = -2 " .
                "LEFT JOIN  currencies currfiat ON pd.currencytx = currfiat.id " .
                "LEFT JOIN  currencies curr ON A.currencyaccid = curr.id "; 

        if (!$rs=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $txdata = $rs->fetch_assoc();
    }else{
        
        // Validamos si es pay o normal
        if(strpos($row['dsc'], 'PAY') !== false){
            $out->entry->type->id = 4;
            $out->entry->type->dsc = "Transferencia PAY";
            
            $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.paypending AS paypending, ".
            "       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.amountghost = 0 AND transactions.paypending = 0 THEN 1 ".
    	    "           ELSE 0 ".
    	    "       END AS status, ".
    	    "       CASE ".
    	    "           WHEN transactions.amountghost = 0 AND transactions.paypending = 0 THEN 'Aprobado' ".
    	    "           ELSE 'Pendiente' ".
    	    "       END AS statusorder ".
            "       FROM transactions ".
            "       WHERE transactions.id = ".$id;
        } 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.paypending AS paypending, ".
            "       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 ".
            "       WHERE transactions.id = ".$id;
        }
        
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $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"];
    
    // Vamos a validar el estado si es un pago movil
    if(strpos($out->entry->dsc, 'con pago') !== false){
        // COnsultamos el retiro para obtener su codigo de retiro
        $sql = "SELECT * ".
        "       FROM withdrawals ".
        "       WHERE transactionid = ".$txdata["txid"];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $mobileData = $res->fetch_assoc();
        
        $out->entry->txid = $mobileData['paymentref'];
        
        // consultamos si existe un ajuste de este retiro
        $sql = "SELECT COUNT(*) AS qty FROM transactions ".
        "       WHERE dsc LIKE '%pago móvil #".$txdata['txid']."%' ".
        "       AND amount = ".number_format(abs($txdata["amount"]) + abs($txdata["fee"]) ,$currencydata["decimals"], '.', '');
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $mobileqty = $res->fetch_assoc();
        
        if($mobileqty['qty'] > 0){
            $out->entry->status = 3;
        }

        if( ($mobileData['filetype'] == '9191' || $mobileData['paymentref'] == '0000') && $mobileqty['qty'] == 0){
            $out->entry->reversable = true;
        }else{
            $out->entry->reversable = false;
        }
    }
    
    //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 || $out->entry->type->id == 4 ? $txdata["txaccountorigin"] : $txdata['txaccountid']).
    "       AND accounts.userid = users.id ".
    "       AND accounts.paymentmethodid = paymentmethods.id";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $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, ".
    "       IF(userpersons.doc IS NULL, usercompanies.doc, userpersons.doc) AS doc, ".
    "       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"=>determinateDBError($db)));
        
    $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"];
    $out->entry->account->user->doc = $username['doc'];
    
    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"=>determinateDBError($db)));
        
    $wallet = $res->fetch_assoc();
    
    $out->entry->account->wallet = $wallet["wallet"];
    
    $out->entry->account->realwallet = '';
    if($out->entry->type->id == 2){
        $out->entry->account->realwallet = $txdata["paymentwallet"];
    } else if($out->entry->type->id == 1){
        $out->entry->account->realwallet = $txdata["ref"];
    }
    
    $sql = "SELECT * FROM currencies WHERE id = ".$accountdata["accountcurrencyid"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $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'];
    if($txdata['paypending'] != -1 && $currencydata['interface'] == 1 && ($out->entry->reversable === null) ){
        $out->entry->reversable = true;
    }else{
        $out->entry->reversable = false;
    }
    
    $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"]));
    
    if(isCripto($out->entry->account->currency->interface) && !($out->entry->type->id == 5)){
        $out->entry->payment->ref = $txdata["paymentref"];
        $out->entry->payment->filetype = $txdata["filetype"];
    }else{
        $out->entry->payment->ref = $txdata["paymentref"];
        if(strpos($out->entry->dsc, 'con pago') !== false || $out->entry->type->id == 5)
            $out->entry->payment->ref = $txdata["paymentref"];
        $out->entry->payment->filetype = $txdata["filetype"];
    }
    
    //Buscamos el archivo para obtener su nombre y extension
    $filestest = glob("../../../uploads/payments/".$out->entry->id.".{jpg,png,jpeg,pdf,PNG,JPG,JPEG,PDF}", GLOB_BRACE);
    //El primer resultado
    $info = pathinfo($filestest[0]);
    
    //Url dentro de la carpeta api
    //$out->entry->payment->url = $txdata["filetype"] == null ? null : $uploadsURL."payments/".$info["basename"];
    $out->entry->payment->url = $txdata["filetype"] == null ? null : $uploadsURLcms."?payid=".$out->entry->id."&sessionid=".$sessionid."&usrid=".$out->entry->account->user->id;
    
    // 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"=>determinateDBError($db)));
            
        $accountdata = $res->fetch_assoc();
        
        if($accountdata["paymentwallet"] != null){
            $out->entry->userpaymentmethod = new stdClass();
            
            // Si es pago movil debe tener otros datos
            if(strpos($out->entry->dsc, 'con pago') !== false){
                
                // Validamos si tiene registro en pagomovildetails (PAY)
                $sql = "SELECT COUNT(transactionid) AS qty ".
                "       FROM pagomovildetails ".
                "       WHERE transactionid = ".$out->entry->id;
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $pagomovildetail = $res->fetch_assoc();
                
                if ($pagomovildetail['qty'] > 0) {
                    // Obtenemos el detalle del pago movil
                    $sql = "SELECT phone ".
                    "       FROM pagomovildetails ".
                    "       WHERE transactionid = ".$out->entry->id;
                    if (!$res=$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    
                    $pagomovildetail = $res->fetch_assoc();
                    $out->entry->payment->ref = $pagomovildetail['phone'];
                } else {
                    // Si no, fue el telefono del usuario
                    $out->entry->payment->ref = $txdata["ref"];
                }
                
                $out->entry->userpaymentmethod->bankid = $accountdata["paymentwallet"];
                $out->entry->userpaymentmethod->dsc = '';
                
                
                switch($txdata['pagomovilbankid']){
                    case 1:
                        
                        // Consultamos el listado de bancos
                        $headers = array('Content-Type:application/json');
                        $request = array();
                        $rest = queryApiBP($BP_URL_QA, "pagos/p2p/bancos", $BP_VERSION_P2P, "GET", $headers, $request);
                        
                        if($rest['httpres'] != 200 && $rest['httpres'] != 201){/*
                            switch($rest['httpres']){
                                case 503:
                                    badEnd("500", array("msg"=>determinateMsgFail(array(
                                        "esp"=>'El servidor no puede atender temporalmente su petici��n',
                                        "eng"=>'The server is temporarily unable to service your petition BP'), $lang, "El servidor no puede atender temporalmente su petici��n")));
                                    break;
                                default:
                                    badEnd("500", array("msg"=>determinateMsgFail(array(
                                        "esp"=>'Error llamada a API BP',
                                        "eng"=>'Error Call to API'), $lang, "Error llamada a API BP")));
                            }*/
                        } else {
                            $banks = $rest['bancos'];
                        
                            // recorremos los bancos para sacar el code a partir del nombre para la API
                            foreach($banks as $bank){
                                if ($bank['codigo'] == $out->entry->userpaymentmethod->bankid) {
                                    $out->entry->userpaymentmethod->dsc = $bank['nombre'];
                                }
                            }
                        }
                        
                        break;
                    case 2:
                        
                        // Consultamos la api de banco activo
                        $headers = array('Content-Type:application/json','apikey: '.$BA_API_KEY);
                        $request = array("tipo_pagador"=>"P2P");
                        $rest = queryApiBA($BA_URL_QA."lista_banco_pago_movil/1.0.0/bancos", "POST", $headers, $request);
                        
                        if($rest['httpres'] != 200 && $rest['httpres'] != 201){
                            $msgs = validateErrorBancoActivo($rest['bodyres']->code, $rest['bodyres']->descripcion, $rest['bodyres']->descripcion);
                            $msg_esp = $msgs->msg_esp;
                            $msg_eng = $msgs->msg_eng;
                                            
                            $msg_esp = $msg_esp;
                            $msg_eng = $msg_eng;
                            
                            /*badEnd("500", array("msg"=>determinateMsgFail(array(
                                "esp"=>$msg_esp,
                                "eng"=>$msg_eng), $lang, $msg_esp)));*/
                        } else {
                            $bancos = $rest['bodyres']->bancos;
                            foreach($bancos as $bank){
                                if ($bank->codBanco == $out->entry->userpaymentmethod->bankid) {
                                    $out->entry->userpaymentmethod->dsc = $bank->nombreBanco;
                                }
                            }
                        }
                        break;
                }
                
                $out->entry->userpaymentmethod->doc = GetFormattedIdentification($db, $out->entry->account->user->id);
    
            }else{
                $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"=>determinateDBError($db)));
            
            $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"=>determinateDBError($db)));
                
            $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"=>determinateDBError($db)));
                
            $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 if($txdata['paypending'] == 0) {
        $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"=>determinateDBError($db)));
            
        $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"=>determinateDBError($db)));
            
        $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"=>determinateDBError($db)));
            
        $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"];
    } else if($txdata['paypending'] == 1) {
        // Si esta en 1  buscamo el nombre del usuario
        $out->entry->userpaymentmethod = new stdClass();
        $out->entry->userpaymentmethod->user = new stdClass();
        
        $sql = "SELECT users.usr AS usr ".
                "       FROM users ".
                "       LEFT JOIN accounts ON accounts.id = ".$txdata['txaccdestination']." AND accounts.userid = users.id".
                "       WHERE users.id = ".$txdata['txaccdestination']." OR accounts.id IS NOT NULL".
                "       ORDER BY users.id DESC";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db).$sql));
            
        $userdestData = $res->fetch_assoc();
        
        $out->entry->userpaymentmethod->user->fullname = $userdestData['usr'];
    } else {
        $out->entry->userpaymentmethod = new stdClass();
    }
    
    //Si es una transferencia necesitamos consultar el movimiento con su amountghost
    if($out->entry->type->id == 3 || $out->entry->type->id == 4){
        //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.
        "       AND dsc LIKE '%Comisión%'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $rowFeeAmount = $res->fetch_assoc();
        //Monto del movimiento
        $out->entry->amount = new stdClass();
        $out->entry->amount->number = ($txdata["amount"] + $txdata["amountghost"]); //+ ($rowFeeAmount["amount"] + $rowFeeAmount["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 || $out->entry->type->id == 4){
        //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.
        "       AND dsc like '%comision%'";
        if (!$res=$db->query($sql)){
            badEnd("500", array("msg"=>determinateDBError($db)));
        }
            
        $rowFee = $res->fetch_assoc();
        //Comision del movimiento
        $out->entry->fee = new stdClass();
        $out->entry->fee->number = ($out->entry->amount->number < 0 ? -1 : 1) * abs($rowFee["amount"] + $rowFee["amountghost"]);
        $out->entry->fee->formatted = numberFormatt($out->entry->fee->number,$currencydata["decimals"]);
    }else{
        //Comision del movimiento
        $out->entry->fee = new stdClass();
        if($out->entry->account->currency->interface == 2 || $out->entry->account->currency->interface == 1 || $out->entry->type->id == 1){
            $out->entry->fee->number = (float)-1*$txdata["fee"];
        }else{
            $out->entry->fee->number = (float)-1*$txdata["fee"];
        }
        
        $out->entry->fee->formatted = numberFormatt($out->entry->fee->number,$currencydata["decimals"]);
    }

    if($row['pagomovildetailid'] != null){

        //Se ajustan principalmente los campos utilizados al cargar el poup
        $out->entry->type->id = 5;

        $out->entry->payment->ref = $txdata["phone"];
        $out->entry->userpaymentmethod->doc = $txdata["doc"];
        $out->entry->userpaymentmethod->dsc = $txdata["bankname"];
        $out->entry->txid = $txdata["ref"];

        $out->entry->fee = new stdClass();
        $out->entry->fee->number = (float)$txdata["feecripto"];
        $out->entry->fee->formatted = numberFormatt($out->entry->fee->number,$txdata["currdecimals"]);

        $out->entry->feeW = new stdClass();
        $out->entry->feeW->number = (float)$txdata["feewithd"];
        $out->entry->feeW->formatted = numberFormatt($out->entry->feeW->number,$txdata["currdecimals"]);

        //Monto del movimiento
        $out->entry->pagomovil = new stdClass();
        $out->entry->pagomovil->amounttx = new stdClass();
        $out->entry->pagomovil->amounttx->number = (float)$txdata["amountves"];
        $out->entry->pagomovil->amounttx->formatted = numberFormatt($out->entry->pagomovil->amounttx->number,$txdata["currfiatdecimals"]);

        $out->entry->pagomovil->currencytx = $txdata["currfiatsymbol"];
    }


    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
