<?php
// app/api/transactions/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)));
    }
    
    //Declaracion de variables
    $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 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.paymentref 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"=>determinateDBError($db),"sql"=>$sql));
        
    $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.entityusrid = -1 ".
    "       AND accounts.currencyid = currencies.id";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db),"sql"=>$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"=>determinateDBError($db),"sql"=>$sql));
        
        $amountdata = $res->fetch_assoc();
        
        //Monto del movimiento
        $out->entry->amount = new stdClass();
        $out->entry->amount->number = $amountdata["amount"] == 0 ? (float)number_format($amountdata["amountghost"], $currency["currencydecimals"], '.', '') : (float)number_format($amountdata["amount"], $currency["currencydecimals"], '.', '');
        $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)number_format($row["transactionamountghost"], $currency["currencydecimals"], '.', '') : (float)number_format($row["transactionamount"], $currency["currencydecimals"], '.', '');
        $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)number_format($row["transactionamountghost"], $currency["currencydecimals"], '.', '') : (float)number_format($row["transactionamount"], $currency["currencydecimals"], '.', '');
        $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"=>determinateDBError($db),"sql"=>$sql));
            
        $feedata = $res->fetch_assoc();
        
        $out->entry->fee = new stdClass();
        $out->entry->fee->number = $feedata["amount"] == 0 ? (float)number_format($feedata["amountghost"], $currency["currencydecimals"], '.', '') : (float)number_format($feedata["amount"], $currency["currencydecimals"], '.', '');
        $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.paymentref AS depositref, ".
        "       withdrawals.valid AS withdrawalsvalid, ".
        "       withdrawals.rejected AS withdrawalsrejected, ".
        "       withdrawals.createddate AS withdrawalscreateddate, ".
        "       withdrawals.filetype AS withdrawalsfiletype, ".
        "       withdrawals.paymentref 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"=>determinateDBError($db),"sql"=>$sql));
        
        $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,pdf,JPG,PNG,JPEG,PDF}", GLOB_BRACE);
        //El primer resultado
        $info = pathinfo($filestest[0]);
        
        if($info['basename'] != ""){
            //Url dentro de la carpeta api
            //$out->entry->payment->url = $uploadsURL."payments/".$info["basename"];
            $out->entry->payment->url = $uploadsURLapp."?payid=".$out->entry->id."&sessionid=".$sessionid;
        }
    }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"];
        
        if($out->entry->payment->filetype !== null){
            //Buscamos el archivo para obtener su nombre y extension
            $filestest = glob("../../../uploads/payments/".$row["txid"].".{jpg,png,jpeg,pdf,JPG,PNG,JPEG,PDF}", GLOB_BRACE);
            //El primer resultado
            $info = pathinfo($filestest[0]);
            
            if($info['basename'] != ""){
                //Url dentro de la carpeta api
                //$out->entry->payment->url = $uploadsURL."payments/".$info["basename"];
                $out->entry->payment->url = $uploadsURLapp."?payid=".$out->entry->id."&sessionid=".$sessionid;
            }
        }
    }
    
    $out->entry->total = new stdClass();
    $out->entry->total->number = number_format($out->entry->amount->number - abs($out->entry->fee->number), $currency["currencydecimals"], '.', '');
    $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.entityusrid = -1 ".
        "       AND accounts.paymentmethodid = paymentmethods.id";
        
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db),"sql"=>$sql));
        
        $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"=>determinateDBError($db),"sql"=>$sql));
        
        $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"=>determinateDBError($db),"sql"=>$sql));
        
        $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"];
    }
    
    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.entityusrid = -1 ".
        "       AND accounts.paymentmethodid = paymentmethods.id";
        
        //badEnd("500", array("msg"=>determinateDBError($db),"sql"=>$sql));
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db),"sql"=>$sql));
        
        $accountdata = $res->fetch_assoc();
        if($accountdata["accountid"]!=null){
            //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"=>determinateDBError($db),"sql"=>$sql));
            
            $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"=>determinateDBError($db),"sql"=>$sql));
        
        $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.entityusrid = -1 ".
        "       AND accounts.paymentmethodid = paymentmethods.id";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db),"sql"=>$sql));
        
        $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"=>determinateDBError($db),"sql"=>$sql));
        
        $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();
?>