<?php
// app/api/deposits/depositWallet
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    
    $out = new stdClass();
    
    // Consultamos los depositos que tengan un ref y paymentref
    $sql = "SELECT deposits.ref AS ref, ".
    "       deposits.transactionid AS txid, ".
    "       currencies.id AS currencyid ,".
    "       currencies.interface AS interface, ".
    "       accounts.id AS accountid ".
    "       FROM deposits ".
    "       JOIN accounts ON accounts.id = deposits.paymentaccountid".
    "       JOIN currencies ON accounts.currencyid = currencies.id".
    "       WHERE deposits.paymentref = deposits.ref";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    // Recorremos los movimientos
    while($row = $rs->fetch_assoc()){
        
        switch(intval($row['interface'])){
            case 7:
                //Interface = 7 | DASH
                $parms = array('txid'=>$row['ref']);
                $request = array('method'=>'gettransaction','parms' => $parms);
                $rest = json_decode(queryServicesDash($DASH_URL, $request),true);
                
                // Validamos que el error no sea nulo para mandar el mensaje
                if($rest['error'] != null){
                    continue 2;
                    //badEnd('500',array("msg"=>$rest['error']['message']));
                }
                
                // Cambiamos la columna de este movimiento
                $sql = "UPDATE deposits SET".
                "       ref = '".$rest['result']['details'][0]['address']."'".
                "       WHERE transactionid = ".$row['txid'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                break;
            case 6:
                // USDT
                
                // Buscamos las wallets de esta cuenta
                /*
                $sql = "SELECT * FROM deposits 
                        INNER JOIN accounts a ON a.id = deposits.paymentaccountid
                        INNER JOIN wallets ON a.id = wallets.accid AND wallets.validdepositsold = 0 
                        WHERE deposits.ref = deposits.paymentref";*/
                 $sql =  "SELECT * FROM wallets WHERE   wallets.accountid = ".$row['accountid'] .
                        "                       AND     wallets.validdepositsold = 0 ";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                $rowW = $res->fetch_assoc();

                //  Obtenemos las transacciones confirmadas (confirmed)
                $request = array('method'=>'trc20byaddress',"address" => $rowW['wallet'], 'confirmed' => true);
                $restConfirmed = json_decode(queryServicesUSDT($USDT_URL, $request), true);
                
                // Validamos que el error no sea nulo para mandar el mensaje
                if($restConfirmed['error'] != null){
                    continue 2;
                }

                $confData = ($restConfirmed['data']!=null && $restConfirmed['data']!='undefined') ? $restConfirmed['data'] : [];
                if(sizeof($confData) > 0){
                    foreach($restConfirmed['data'] as $deposit){
                        // Validamos que este movimiento ya se haya aprobado
                        //Obtenemos los datos de el deposito para efectos de ajustar montos en transactions
                        $sql = "SELECT * ".
                        "       FROM deposits ".
                        "       WHERE paymentref = '".$deposit['transaction_id']."'";
                        if (!$res=$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                        
                        $rowDe = mysqli_num_rows($res);
                        if($rowDe>0){ // Insertamos la wallet
                            $sql = "UPDATE deposits SET".
                            "       ref = '".$rowW['wallet']."'".
                            "       WHERE transactionid = ".$row['txid'];
                            if (!$res=$db->query($sql))
                                badEnd("500", array("msg"=>determinateDBError($db)));
                        }
                    }
                }
                
                $sql = "UPDATE wallets SET".
                "       validdepositsold = 1".
                "       WHERE wallet = '".$rowW['wallet']."'";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));

                break;
            case 5:
                //Interface = 5 | PTR
                    
                //Llamamos a la api por cada retiro para verificar su estado y actualizar sus datos
                $rsp = queryPrivate('deposit', $TCV_JWT, $TCV_URL, $VERSION_API, true, ['txid' => $row['ref']]);
                
                if($rsp['httpres'] != 200){
                    continue 2;
                    //badEnd("402", array("msg"=>'Error al insertar retiro '.$rsp['httpres']." - ".$rsp['error']->message));
                }
                
                $sql = "UPDATE deposits SET".
                "       ref = '".$rest['result']['address']."'".
                "       WHERE transactionid = ".$row['txid'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                break;
            case 4:
                //Interface = 4 | BTC
                $parms = array('txid'=>$row['ref']);
                $request = array('method'=>'gettransaction','parms' => $parms);
                $rest = json_decode(queryServicesBTC($BTC_URL, $request), true);
                
                // Validamos que el error no sea nulo para mandar el mensaje
                if($rest['error'] != null){
                    continue 2;
                    //badEnd('500',array("msg"=>$rest['error']['message']));
                }
                
                // Cambiamos la columna de este movimiento
                $sql = "UPDATE deposits SET".
                "       ref = '".$rest['result']['details'][0]['address']."'".
                "       WHERE transactionid = ".$row['txid'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                break;
        }
        
        break;
    }
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>