<?php
    // app/api/deposits/searchfunds
    //Servicio exclusivo de USDT

    //$mt = microtime(true);
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    $out = new stdClass();
    
    //Obtenemos los datos de las monedas
    $usdtcurrid = 231;

    //Si Ya no tenemos wallets por validar repetimos el ciclo
    $cntceros = "       SELECT COUNT(wallets.id) AS cntid, accounts.currencyid AS currencyid ".
                "       FROM wallets, accounts ".
                "       WHERE wallets.accountid = accounts.id ".
                "       AND accounts.currencyid = ".$usdtcurrid.
                "       AND accounts.entityusrid = -1 ".
                "       AND (wallets.txid IS NULL OR wallets.txid = '') ".
                "       AND wallets.validatedTRX = 0";
    if (!$res=$db->query($cntceros))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $row = $res->fetch_assoc();
    if($row['cntid']<=0){
        $sql =  "UPDATE     wallets ".
                "INNER JOIN accounts ".
                "ON         accounts.id = wallets.accountid ".
                "AND        accounts.currencyid = ".$usdtcurrid. " ".
                "SET        validatedTRX = 0 ";
            if (!$db->query($sql)){
                $error = determinateDBError($db);
                $db->rollback();
                $db->close();
                badEnd("500", array("msg"=>$error));
            }
    }

    //Consultamos las wallets que ya fueron confirmadas o que acaban de ser aprobadas y esperan para retornar los fondos
    $sql = "SELECT  wallets.* ".
    "       FROM    wallets, accounts ".
    "       WHERE   wallets.accountid = accounts.id ".
    "       AND     accounts.currencyid = ".$usdtcurrid.
    "       AND     accounts.entityusrid = -1 ".
    "       AND     (wallets.txid IS NULL OR wallets.txid = '') ".
    "       AND     wallets.validatedTRX = 0" .    
    "       ORDER BY wallets.txidApprove DESC, wallets.id DESC";
    if (!$resW=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
       
    
    $i = 0;
    while($rowW = $resW->fetch_assoc()){
        if($i>=1)break;
        //Este servicio valida las aprobaciones y reenvia fondos de TRX si existen
        
        // Verificamos si esta en approve o no
        if($rowW['txidApprove'] !== null && $rowW['txidApprove'] !== ''){
            //  Consultamos por ese txid
            $request = array('method'=>'getTransactionByTxid','txid'=>$rowW['txidApprove']); //ESTO VALIDA EL STATUS DEL APPROVE
            $rest = json_decode(queryServicesUSDT($USDT_URL, $request), true);
            $out->entry [] = $rest;
            
            if($rest != null){
                if($rest['ret'][0]['contractRet'] == 'SUCCESS'){
                    //  Devolvemos los tron a la wallet central
                    $request = array('method'=>'resendTrx', 'from'=>$rowW['wallet'], 'fromKey' => $rowW['secretKey']);
                    $rest = json_decode(queryServicesUSDT($USDT_URL, $request), true);

                    // Si es distinto a null y esta fina, lanzamos el resend y actualizamos el registro
                    $sql = "UPDATE wallets SET ".
                    "       txidApprove = NULL, ".
                    "       txid = NULL ".
                    "       WHERE id = ".$rowW['id'];
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));

                }else if(($rest['ret'][0]['contractRet'] == 'OUT_OF_ENERGY' || $rest['ret'][0]['contractRet'] == 'REVERT')){
                    //Si ENTRA ACÁ ES PORQUE LOS TRX QUE ENVIÓ LA WALLET POTE NO ALCANZARON
                    $sqlPref =  "SELECT * FROM cmspreferences WHERE id = 1";
                    if (!$rsPref=$db->query($sqlPref))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                    $rowPref = $rsPref->fetch_assoc();

                    $sqlUp =  "UPDATE cmspreferences SET newwalletfeeUsdt=".(($rowPref["newwalletfeeUsdt"]*1)+4)." WHERE id = 1";
                    if (!$rsPrefUp=$db->query($sqlUp))
                        badEnd("500", array("msg"=>determinateDBError($db)));

                    // Si expiramos la wallet blanqueamos el details 1 de la cuenta a la que pertenece
                    $sql = "UPDATE accounts SET ".
                    "       details1 = NULL ".
                    "       WHERE id = ".$rowW['accountid'];
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));

                    // Expiramos la wallet
                    $sql = "UPDATE wallets SET".
                    "       expirationDate = DATE_SUB(NOW(), INTERVAL 7 DAY), ".
                    "       txid = NULL, ".
                    "       txidApprove = NULL " .
                    "       WHERE id = ".$rowW['id'];
                    if (!$db->query($sql))
                        badEnd("500", array("msg"=>determinateDBError($db)));
                }
            }
        }else{                 
            $request = array('method'=>'getBalances', "address" => $rowW['wallet']);
            $restBal = json_decode(queryServicesUSDT($USDT_URL, $request), true);
            //Si enontramos saldo en una billetera nos lo enviamos a la wallet pote
            if($restBal != null && $restBal != "" && $restBal != 'undefined'){
                if(formattedTrxAmount($restBal['TRX']) >= 0.05){
                    $request = array('method'=>'resendTrx', 'from'=>$rowW['wallet'], 'fromKey' => $rowW['secretKey']);
                    $rest = json_decode(queryServicesUSDT($USDT_URL, $request), true);        
                }
            }
        }
        
        $sql =  "UPDATE wallets SET".
                "       validatedTRX = 1 " .
                "WHERE  id = ".$rowW['id'];

                if (!$db->query($sql)){
                    $error = determinateDBError($db);
                    $db->rollback();
                    $db->close();
                    badEnd("500", array("msg"=>$error));
                }
        $i++;
    }
        
    function formattedTrxAmount($value){
        return ((($value*1) > 0)?(($value*1)/1000000):0);
    }
    
    
    $db->close();
    //$out->tiempo = microtime(true) - $mt;
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
        
?>