<?php
// app/api/transactions/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)));
    }
    
    //Declaracion de variables
    $out = new stdClass;
    $sessionid = $_GET["sessionid"];
    $id = $_GET["id"];
    
    //Validamos la session
    
    //Consultamos la transaccion requerida
    $sql = "SELECT transactions.id AS transactionid, ".
    "       transactions.datecreated AS transactiondatecreated, ".
    "       transactions.dsc AS transactiondsc, ".
    "       transactions.amount AS transactionamount, ".
    "       transactions.amountghost AS transactionamountghost, ".
    "       transactions.accountorigin AS transactionaccountor, ".
    "       transactions.accountdestination AS transactionaccountdestination, ".
    "       transactions.accountid AS txaccountid, ".
    "       transactions.txid AS txid, ".
    "       deposits.valid AS depositvalid, ".
    "       deposits.rejected AS depositrejected, ".
    "       deposits.createddate AS depositcreateddate, ".
    "       deposits.filetype AS depositfiletype, ".
    "       deposits.paymentref AS depositref, ".
    "       withdrawals.valid AS withdrawalsvalid, ".
    "       withdrawals.rejected AS withdrawalsrejected, ".
    "       withdrawals.createddate AS withdrawalscreateddate, ".
    "       withdrawals.filetype AS withdrawalsfiletype, ".
    "       withdrawals.ref AS withdrawalsref ".
    "       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();
    //Ordenamos los datos
    $out->entry = new stdClass;
    $out->entry->id = (int)$row["transactionid"];
    $out->entry->dsc = $row["transactiondsc"];
    
    //Si es 0 no es comision, 1 es una comision
    $isFee = 0;
    
    //Si tiene la palabra comision retorna 1
    if(stripos($row["transactiondsc"], "comisión") !== false){
        $isFee = 1;
    }
    
    $sql = "SELECT ".
    "       accounts.id AS accountid, ".
    "       accounts.currencyid AS accountcurrencyid, ".
    "       currencies.decimals AS currencydecimals ".
    "       FROM accounts, currencies".
    "       WHERE accounts.id = ".$row["txaccountid"].
    "       AND accounts.currencyid = currencies.id";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
        
    $currency = $res->fetch_assoc();
    
    if($isFee == 1){
        $sql = "SELECT * FROM transactions WHERE id = ".$row["txid"];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $amountdata = $res->fetch_assoc();
        
        //Monto del movimiento
        $out->entry->amount = new stdClass();
        $out->entry->amount->number = $amountdata["amount"] == 0 ? (float)$amountdata["amountghost"] : (float)$amountdata["amount"];
        $out->entry->amount->formatted = numberFormatt($out->entry->amount->number,$currency["currencydecimals"]);
    }else{
        //Monto del movimiento
        $out->entry->amount = new stdClass();
        $out->entry->amount->number = $row["transactionamount"] == 0 ? (float)$row["transactionamountghost"] : (float)$row["transactionamount"];
        $out->entry->amount->formatted = numberFormatt($out->entry->amount->number,$currency["currencydecimals"]);
    }
    
    if($isFee == 1){
        $out->entry->fee = new stdClass();
        $out->entry->fee->number = $row["transactionamount"] == 0 ? (float)$row["transactionamountghost"] : (float)$row["transactionamount"];
        $out->entry->fee->formatted = numberFormatt($out->entry->fee->number,$currency["currencydecimals"]);
    }else{
        //Fee del movimiento
        $sql = "SELECT * FROM transactions ".
        "       WHERE txid = ".$out->entry->id.
        "       AND dsc LIKE '%Comision%'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $feedata = $res->fetch_assoc();
        
        $out->entry->fee = new stdClass();
        $out->entry->fee->number = $feedata["amount"] == 0 ? (float)$feedata["amountghost"] : (float)$feedata["amount"];
        $out->entry->fee->formatted = numberFormatt($out->entry->fee->number,$currency["currencydecimals"]);
    }
    
    //Fecha de creacion
    $out->entry->datecreated = new stdClass();
    $out->entry->datecreated->date = date("Y-m-d H:i", strtotime($row["transactiondatecreated"]));
    $out->entry->datecreated->formatted = date("d/m/Y h:i a", strtotime($row["transactiondatecreated"]));
    
    //Datos del pago
    $out->entry->payment = new stdClass();
    
    if($isFee == 1){
        $sql = "SELECT transactions.id AS transactionid, ".
        "       transactions.txid AS txid, ".
        "       deposits.valid AS depositvalid, ".
        "       deposits.rejected AS depositrejected, ".
        "       deposits.createddate AS depositcreateddate, ".
        "       deposits.filetype AS depositfiletype, ".
        "       deposits.ref AS depositref, ".
        "       withdrawals.valid AS withdrawalsvalid, ".
        "       withdrawals.rejected AS withdrawalsrejected, ".
        "       withdrawals.createddate AS withdrawalscreateddate, ".
        "       withdrawals.filetype AS withdrawalsfiletype, ".
        "       withdrawals.ref AS withdrawalsref ".
        "       FROM transactions ".
        "       LEFT JOIN deposits ON transactions.id = deposits.transactionid".
        "       LEFT JOIN withdrawals ON transactions.id = withdrawals.transactionid".
        "       WHERE transactions.id = ".$row["txid"];
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $rowpayment = $res->fetch_assoc();
        
        //Fecha de validacion
        if($rowpayment["depositvalid"] == null && $rowpayment["withdrawalsvalid"] == null){
            $out->entry->rejected = new stdClass();
            $out->entry->rejected->date = date("Y-m-d H:i", strtotime($rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositrejected"] : $rowpayment["withdrawalsrejected"]));
            $out->entry->rejected->formatted = date("d/m/Y h:i a", strtotime($rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositrejected"] : $rowpayment["withdrawalsrejected"]));
            $out->entry->valid = null;
        }else{
            $out->entry->valid = new stdClass();
            $out->entry->valid->date = date("Y-m-d H:i", strtotime($rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositvalid"] : $rowpayment["withdrawalsvalid"]));
            $out->entry->valid->formatted = date("d/m/Y h:i a", strtotime($rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositvalid"] : $rowpayment["withdrawalsvalid"]));
            $out->entry->rejected = null;
        }
    
        $out->entry->payment->date = new stdClass();
        $out->entry->payment->date->canonical = date("Y-m-d H:i", strtotime($rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositcreateddate"] : $rowpayment["withdrawalscreateddate"]));
        $out->entry->payment->date->formatted = date("d/m/Y h:i a", strtotime($rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositcreateddate"] : $rowpayment["withdrawalscreateddate"]));
    
        $out->entry->payment->ref = $rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositref"] : $rowpayment["withdrawalsref"];
        $out->entry->payment->filetype = $rowpayment["withdrawalscreateddate"] == null ? $rowpayment["depositfiletype"] : $rowpayment["withdrawalsfiletype"];
    
        //Buscamos el archivo para obtener su nombre y extension
        $filestest = glob("../uploads/payments/".$row["txid"].".{jpg,png,jpeg}", GLOB_BRACE);
        //El primer resultado
        $info = pathinfo($filestest[0]);
        //Url dentro de la carpeta api
        $out->entry->payment->url = "./api/uploads/payments/".$info["basename"];
    }else{
        //Fecha de validacion
        if($row["depositvalid"] == null && $row["withdrawalsvalid"] == null){
            $out->entry->rejected = new stdClass();
            $out->entry->rejected->date = date("Y-m-d H:i", strtotime($row["withdrawalscreateddate"] == null ? $row["depositrejected"] : $row["withdrawalsrejected"]));
            $out->entry->rejected->formatted = date("d/m/Y h:i a", strtotime($row["withdrawalscreateddate"] == null ? $row["depositrejected"] : $row["withdrawalsrejected"]));
            $out->entry->valid = null;
        }else{
            $out->entry->valid = new stdClass();
            $out->entry->valid->date = date("Y-m-d H:i", strtotime($row["withdrawalscreateddate"] == null ? $row["depositvalid"] : $row["withdrawalsvalid"]));
            $out->entry->valid->formatted = date("d/m/Y h:i a", strtotime($row["withdrawalscreateddate"] == null ? $row["depositvalid"] : $row["withdrawalsvalid"]));
            $out->entry->rejected = null;
        }
    
        $out->entry->payment->date = new stdClass();
        $out->entry->payment->date->canonical = date("Y-m-d H:i", strtotime($row["withdrawalscreateddate"] == null ? $row["depositcreateddate"] : $row["withdrawalscreateddate"]));
        $out->entry->payment->date->formatted = date("d/m/Y h:i a", strtotime($row["withdrawalscreateddate"] == null ? $row["depositcreateddate"] : $row["withdrawalscreateddate"]));
    
        $out->entry->payment->ref = $row["withdrawalscreateddate"] == null ? $row["depositref"] : $row["withdrawalsref"];
        $out->entry->payment->filetype = $row["withdrawalscreateddate"] == null ? $row["depositfiletype"] : $row["withdrawalsfiletype"];
    
        //Buscamos el archivo para obtener su nombre y extension
        $filestest = glob("../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 = "./api/uploads/payments/".$info["basename"];
    }
    
    $out->entry->total = new stdClass();
    $out->entry->total->number = $out->entry->amount->number - abs($out->entry->fee->number);
    $out->entry->total->formatted = numberFormatt($out->entry->total->number,$currency["currencydecimals"]);
    
    //Datos de las cuentas de transaccion
    
    if($row["transactionaccountor"] != null ){
        //Consultamos los datos generales de la cuenta
        $sql = "SELECT ".
        "       users.id AS userid, ".
        "       accounts.id AS accountid, ".
        "       accounts.details1 AS accountdetails1, ".
        "       accounts.currencyid AS accountcurrencyid, ".
        "       paymentmethods.id AS paymentmethodid, ".
        "       paymentmethods.dsc AS paymetmenthoddsc ".
        "       FROM accounts, users, paymentmethods ".
        "       WHERE accounts.id = ".$row["transactionaccountor"].
        "       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();
        
        //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();
        $out->entry->origin = new stdClass();
        
        //Ordenamos los datos del usuario
        $out->entry->origin->user = new stdClass();
        $out->entry->origin->user->id = (int)$accountdata["userid"];
        
        
        if($username["fname"] == null){
            $out->entry->origin->user->name = $username["companyname"].( $username["companycomercialname"] == "" ? "" : " ".$username["companycomercialname"] );
        }else{
            $out->entry->origin->user->name = $username["personname"].( $username["personlastname"] == "" ? "" : " ".$username["personlastname"] );
        }
        
        //Ordenamos los datos de la cuenta
        $out->entry->origin->account = new stdClass();
        $out->entry->origin->account->id = (int)$accountdata["accountid"];
        $out->entry->origin->account->details1 = $accountdata["accountdetails1"];
        
        $out->entry->origin->account->paymentmethod = new stdClass();
        $out->entry->origin->account->paymentmethod->id = (int)$accountdata["paymentmethodid"];
        $out->entry->origin->account->paymentmethod->dsc = $accountdata["paymetmenthoddsc"];
        
        $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->origin->account->currency = new stdClass();
        $out->entry->origin->account->currency->id = (int)$currencydata["id"];
        $out->entry->origin->account->currency->name = $currencydata["name"];
        $out->entry->origin->account->currency->symbol = $currencydata["symbol"];
    }
    
    $out->prueba = $isFee;
    
    if($row["transactionaccountdestination"] != null && $isFee == 0){
        //Consultamos los datos generales de la cuenta
        $sql = "SELECT ".
        "       users.id AS userid, ".
        "       accounts.id AS accountid, ".
        "       accounts.details1 AS accountdetails1, ".
        "       accounts.currencyid AS accountcurrencyid, ".
        "       paymentmethods.id AS paymentmethodid, ".
        "       paymentmethods.dsc AS paymetmenthoddsc ".
        "       FROM accounts, users, paymentmethods ".
        "       WHERE accounts.id = ".$row["transactionaccountdestination"].
        "       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();
        
        //Ordenamos los datos de la cuenta
        $out->entry->destination = new stdClass();
        $out->entry->destination->account = new stdClass();
        $out->entry->destination->account->id = (int)$accountdata["accountid"];
        $out->entry->destination->account->details1 = $accountdata["accountdetails1"];
        
        $out->entry->destination->account->paymentmethod = new stdClass();
        $out->entry->destination->account->paymentmethod->id = (int)$accountdata["paymentmethodid"];
        $out->entry->destination->account->paymentmethod->dsc = $accountdata["paymetmenthoddsc"];
        
        $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->destination->account->currency = new stdClass();
        $out->entry->destination->account->currency->id = (int)$currencydata["id"];
        $out->entry->destination->account->currency->name = $currencydata["name"];
        $out->entry->destination->account->currency->symbol = $currencydata["symbol"];
    }else if($isFee == 1){
        //Al ser fee, consultamos los datos de la cuenta de destino del movimiento padre
        $sql = "SELECT * FROM transactions WHERE id = ".$row["txid"];
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $txdata = $rs->fetch_assoc();
        
        //Consultamos los datos generales de la cuenta
        $sql = "SELECT ".
        "       users.id AS userid, ".
        "       accounts.id AS accountid, ".
        "       accounts.details1 AS accountdetails1, ".
        "       accounts.currencyid AS accountcurrencyid, ".
        "       paymentmethods.id AS paymentmethodid, ".
        "       paymentmethods.dsc AS paymetmenthoddsc ".
        "       FROM accounts, users, paymentmethods ".
        "       WHERE accounts.id = ".$txdata["accountdestination"].
        "       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();
        
        //Ordenamos los datos de la cuenta
        $out->entry->destination = new stdClass();
        $out->entry->destination->account = new stdClass();
        $out->entry->destination->account->id = (int)$accountdata["accountid"];
        $out->entry->destination->account->details1 = $accountdata["accountdetails1"];
        
        $out->entry->destination->account->paymentmethod = new stdClass();
        $out->entry->destination->account->paymentmethod->id = (int)$accountdata["paymentmethodid"];
        $out->entry->destination->account->paymentmethod->dsc = $accountdata["paymetmenthoddsc"];
        
        $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->destination->account->currency = new stdClass();
        $out->entry->destination->account->currency->id = (int)$currencydata["id"];
        $out->entry->destination->account->currency->name = $currencydata["name"];
        $out->entry->destination->account->currency->symbol = $currencydata["symbol"];
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>