<?php
// app/api/withdrawals/withdrawvalid
    
    $mt = microtime(true);
    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    $out = new stdClass();
    
    //Con este servicio consultaremos los retiros que estan pendientes para asi buscarlos en la API(DINAMICO)
    
    //Obtenemos los datos de las monedas
    $sql = "SELECT * FROM currencies";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    while($currencydata = $rs->fetch_assoc()){
        //Aqui colocaremos un switch con los interface de las apis
        switch(intval($currencydata['interface'])){
            case 5:
                //Interface = 5 | PTR
                //Primero debemos consultar en la DB los retiros pendientes para PTR
                $sql = "SELECT withdrawals.ref AS ref, ".
                "       withdrawals.transactionid AS transactionid ".
                "       FROM accounts, withdrawals, transactions ".
                "       WHERE withdrawals.valid IS NULL ".
                "       AND withdrawals.rejected IS NULL ".
                "       AND transactions.id = withdrawals.transactionid ".
                "       AND transactions.accountid = accounts.id ".
                "       AND accounts.currencyid = ".$currencydata['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>$db->error));
                    
                //Luego de que tenemos los retiros pendientes consultamos cada retiro por individual para verificar su estado
                while($row = $res->fetch_assoc()){
                    $out->record [] = $row;
                    
                    //Llamamos a la api por cada retiro para verificar su estado y actualizar sus datos
                    $rsp = queryPrivate('withdraws/'.$row['ref'], $TCV_JWT, $TCV_URL, $VERSION_API, true);
                    
                    if($rsp['httpres'] != 200){
                        badEnd("402", array("msg"=>'Error al insertar retiro '.$rsp['httpres']." - ".$rsp['error']->message));
                    }
                    
                    //Validamos que haya sido completado y que no este en proceso
                    if($rsp['completed_at'] != null && $rsp['state'] != 'submitted'){
                        
                        //Si el state es igual a succeed, el retiro fue confirmado y validado
                        //Igual validamos que el txid exista si se confirmo
                        if($rsp['state'] == 'succeed' && $rsp['blockchain_txid'] != NULL){
                            
                            //Actualizamos el retiro en la BD
                            $sql = "UPDATE withdrawals SET ".
                            "       paymentref = '".$rsp['blockchain_txid']."', ".
                            "       valid = NOW() ".
                            "       WHERE ref = ".$row['ref'];
                            if (!$db->query($sql))
                                badEnd("500", array("msg"=>$db->error));
                                
                        }else if($rsp['state'] == 'rejected'){
                            //Si el state es rejected, significa que se rechazo el retiro
                            
                            //Actualizamos el retiro en la BD
                            $sql = "UPDATE withdrawals SET ".
                            "       rejected = NOW() ".
                            "       WHERE ref = ".$row['ref'];
                            if (!$db->query($sql))
                                badEnd("500", array("msg"=>$db->error));
                                
                            //Tambien ajustamos el movimiento en transactions
                            $sql = "UPDATE transactions SET".
                            "       amountghost = amount + amountghost, ".
                            "       amount = 0 ".
                            "       WHERE txid = ".$row['transactionid'];
                            if (!$db->query($sql))
                                badEnd("500", array("msg"=>$db->error));
                        }
                    }
                }
                break;
            case 4:
                //Interface = 4 | BTC
                //Primero debemos consultar en la DB los retiros pendientes para BTC
                $sql = "SELECT withdrawals.ref AS ref, ".
                "       withdrawals.paymentwallet AS paymentwallet, ".
                "       withdrawals.transactionid AS transactionid ".
                "       FROM accounts, withdrawals, transactions ".
                "       WHERE withdrawals.valid IS NULL ".
                "       AND withdrawals.rejected IS NULL ".
                "       AND transactions.id = withdrawals.transactionid ".
                "       AND transactions.accountid = accounts.id ".
                "       AND accounts.currencyid = ".$currencydata['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>$db->error));
                    
                //Luego de que tenemos los retiros pendientes consultamos cada retiro por individual para verificar su estado
                while($row = $res->fetch_assoc()){
                    $parms = array('txid'=>$row['ref']);
                    $request = array('method'=>'gettransaction','parms' => $parms);
                    $rest = json_decode(queryServicesBTC($BTC_URL, $request), true);
                    $out->testing [] = $rest;
                    /*
                    // Generamos un bloque
                    if($rest['result']['confirmations'] <= 5){
                        $parms = array('nblocks'=>1,'address'=>$row['paymentwallet']);
                        $request = array('method'=>'generatetoaddress','parms' => $parms);
                        $rest = json_decode(queryServicesBTC($BTC_URL, $request), true);
                    }
                      */      
                    // validamos las confirmaciones
                    // SI es mayor o igual a 3 la validamos
                    if(intval($rest['result']['confirmations']) >= 3){
                        
                        //Actualizamos el retiro en la BD
                        $sql = "UPDATE withdrawals SET ".
                        "       paymentref = '".$rest['result']['txid']."', ".
                        "       valid = NOW() ".
                        "       WHERE ref = '".$row['ref']."'";
                        if (!$db->query($sql))
                            badEnd("500", array("msg"=>$db->error));
                        
                    }else if(intval($rest['result']['confirmations']) < 0){
                        // SI es menor a 0 la cancelamos
                        $sql = "UPDATE withdrawals SET ".
                        "       rejected = NOW() ".
                        "       WHERE ref = '".$row['ref']."'";
                        if (!$db->query($sql))
                            badEnd("500", array("msg"=>$db->error));
                            
                        //Tambien ajustamos el movimiento en transactions
                        $sql = "UPDATE transactions SET".
                        "       amountghost = amount + amountghost, ".
                        "       amount = 0 ".
                        "       WHERE txid = ".$row['transactionid'];
                        if (!$db->query($sql))
                            badEnd("500", array("msg"=>$db->error));
                    }
                }
                break;
        }
    }
    $out->tiempo = microtime(true) - $mt;
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>