<?php
// app/api/transactions/accept

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // parametros obligatorios
    $parmsob = array("sessionid","id","validator");
    if (!parametrosValidos($_GET, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
    }
    
    //Declaracion de variables
    $out = new stdClass;
    $sessionid = $_GET["sessionid"];
    $validator = $_GET["validator"];
    $id = $_GET["id"];
    
    //Validamos la session
    isSessionValid($db, $sessionid);
    
    //Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Consultamos los datos de la transaccion
    $sql = "SELECT * FROM transactions WHERE id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    $txdata = $rs->fetch_assoc();
    
    if($txdata["validator"] != $validator){
        badEnd("402", array("msg"=>determinateMsgFail(array(
            "esp"=>"Código invalido",
            "eng"=>"Invalid code"), $lang, "Código invalido")));
    }
    
    // Validamos que el codigo no este vencido
    $sql = "SELECT COUNT(id) AS qty FROM transactions ".
    "       WHERE id = ".$id.
    "       AND validthru > NOW()";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    $txdata = $rs->fetch_assoc();
    
    if($txdata["qty"] == 0){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Código expirado",
            "eng"=>"Code expired"), $lang, "Código expirado")));
    }
    
    //Consultamos para saber si es un retiro o no
    $sql = "SELECT ( ".
    "           SELECT COUNT(withdrawals.transactionid) FROM withdrawals ".
    "           WHERE withdrawals.transactionid = tx.id ".
    "       ) AS isWithdraw, ".
    "       ( ".
    "           SELECT COUNT(deposits.transactionid) FROM deposits ".
    "           WHERE deposits.transactionid = tx.id ".
    "       ) AS isDeposit ".
    "       FROM transactions tx ".
    "       WHERE tx.id = ".$id;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    //Si es un retiro, debemos consulta a las API de la moneda
    if(intval($row['isWithdraw']) == 1 && intval($row['isDeposit']) == 0){
    
        //Consultamos la moneda para hacer llamado a API
        $sql = "SELECT currencies.symbol AS symbol, ".
        "       currencies.interface AS interface, ".
        "       ABS(transactions.amountghost) AS amount, ".
        "       withdrawals.paymentwallet AS wallet ".
        "       FROM currencies, accounts, transactions, withdrawals ".
        "       WHERE transactions.id = ".$id.
        "       AND transactions.accountid = accounts.id ".
        "       AND accounts.currencyid = currencies.id ".
        "       AND withdrawals.transactionid = transactions.id";
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
            
        $currencydata = $rs->fetch_assoc();
        
        switch(intval($currencydata['interface'])){
            case 5:
                //Si es 5, llamamos a la api del TCV para hacer un retiro
                $rsp = queryPrivate('withdraws/new', $TCV_JWT, $TCV_URL, $VERSION_API, false, [
                    'rid' => $currencydata['wallet'], 
                    'currency' => $currencydata['symbol'],
                    'amount' => $currencydata['amount']
                ]);
                
                $out->test = $rsp;
                
                //Si el id es nulo, tenemos un error ya que es nuestra guia
                if($rsp['id'] == null || $rsp['httpres'] != 201){
                    badEnd('402',array('msg'=>determinateMsgFail(array(
                        "esp"=>'Error API ingreso de retiro '.$rsp['httpres'],
                        "eng"=>'Withdrawal income API error '.$rsp['httpres']), $lang, 'Error API ingreso de retiro '.$rsp['httpres']),
                    'error'=>$rsp));
                    
                    //Abrimos la transaccion
                    $db->autocommit(FALSE);

                    //eliminar el retiro(si existe)
                    $sql = "DELETE FROM withdrawals WHERE transactionid = ".$id;
                    if (!$db->query($sql)){
                        $error = $db->error;
                        $db->rollback();
                        $db->close();
                        badEnd("500", array("msg"=>$error));
                    }
    
                    //eliminar la transaccion
                    $sql = "DELETE FROM transactions ".
                    "       WHERE id = ".$id.
                    "       OR txid = ".$id;
                    if (!$db->query($sql)){
                        $error = $db->error;
                        $db->rollback();
                        $db->close();
                        badEnd("500", array("msg"=>$error));
                    }
    
                    //Retornamos 304 si no se elimino ningun registro
                    if ($db->affected_rows == 0){
                        $db->rollback();
                        $db->close();
                        badEnd("403", array("msg"=>determinateMsgFail(array(
                        "esp"=>"No se pudo modificar",
                        "eng"=>"Cannot modify"), $lang, "No se pudo modificar")));
                    }
    
                    $db->commit();
                    $db->close();
                    
                }
                
                //Obtenemos el id del retiro en la tcv y lo guardamos en ref
                $sql = "UPDATE withdrawals SET ".
                "       ref = ".$rsp['id'].
                "       WHERE transactionid = ".$id;
                if (!$db->query($sql)){
                    badEnd("500", array("msg"=>$db->error));
                }
                break;
            case 4:
                $parms = array('address'=>$currencydata['wallet'],'amount'=>$currencydata['amount']);
                $request = array('method'=>'sendtoaddress','parms' => $parms);
                $rsp = json_decode(queryServicesBTC($BTC_URL, $request), true);
                
                $out->test = $rsp;
                
                // SI error no es nulo, significa que hubo un error
                if($rsp['error'] != null){
                    // Acomodamos el retiro para borrarlo
                    
                    //Abrimos la transaccion
                    $db->autocommit(FALSE);

                    //eliminar el retiro(si existe)
                    $sql = "DELETE FROM withdrawals WHERE transactionid = ".$id;
                    if (!$db->query($sql)){
                        $error = $db->error;
                        $db->rollback();
                        $db->close();
                        badEnd("500", array("msg"=>$error));
                    }
    
                    //eliminar la transaccion
                    $sql = "DELETE FROM transactions ".
                    "       WHERE id = ".$id.
                    "       OR txid = ".$id;
                    if (!$db->query($sql)){
                        $error = $db->error;
                        $db->rollback();
                        $db->close();
                        badEnd("500", array("msg"=>$error));
                    }
    
                    //Retornamos 304 si no se elimino ningun registro
                    if ($db->affected_rows == 0){
                        $db->rollback();
                        $db->close();
                        badEnd("403", array("msg"=>determinateMsgFail(array(
                        "esp"=>"No se pudo modificar",
                        "eng"=>"Cannot modify"), $lang, "No se pudo modificar")));
                    }
    
                    $db->commit();
                    $db->close();
                    
                    badEnd('500',array("msg"=>determinateMsgFail(array(
                        "esp"=>"Error API ingreso de retiro ".$rsp['error']['message'],
                        "eng"=>"Withdrawal income API error ".$rsp['error']['message']), $lang, "Error API ingreso de retiro ".$rsp['error']['message'])));
                }
                
                //Obtenemos el tx del retiro de BTC y lo guardamos en ref
                $sql = "UPDATE withdrawals SET ".
                "       ref = '".$rsp['result']."'".
                "       WHERE transactionid = ".$id;
                if (!$db->query($sql)){
                    badEnd("500", array("msg"=>$db->error));
                }
                
                break;
        }   
    }
    
    //Actualizamos la transaccion
    $sql = "UPDATE transactions SET".
    "       amount = amount + amountghost, ".
    "       validthru = NULL, ".
    "       amountghost = 0, ".
    "       validator = NULL ".
    "       WHERE txid = ".$id.
    "       AND validthru > NOW()".
    "       AND validator = ".$validator;
    if (!$db->query($sql)){
        $error = $db->error;
        badEnd("500", array("msg"=>$error));
    }
    
    $out->id = (int)$id;
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>