<?php
// app/api/withdrawals/withdrawvalid
    
    $mt = microtime(true);
    header("Content-Type:application/json");
    include("../../../settings/dbconn.php");
    include("../../../settings/utils.php");
    //Agregado
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    
    $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"=>determinateDBError($db)));
        
    while($currencydata = $rs->fetch_assoc()){
        //Aqui colocaremos un switch con los interface de las apis
        switch(intval($currencydata['interface'])){
            case 7:
                //Interface = 7 | DASH
                //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, ".
                "       accounts.userid AS userid " .
                "       FROM accounts, withdrawals, transactions ".
                "       WHERE withdrawals.valid IS NULL ".
                "       AND transactions.validator IS NULL ".
                "       AND withdrawals.rejected IS NULL ".
                "       AND accounts.entityusrid = -1 ".
                "       AND transactions.id = withdrawals.transactionid ".
                "       AND transactions.accountid = accounts.id ".
                "       AND accounts.currencyid = ".$currencydata['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                //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(queryServicesDash($DASH_URL, $request),true);
                    
                    // Validamos que el error no sea nulo para mandar el mensaje
                    if($rest['error'] != null){
                        continue;
                        //badEnd('500',array("msg"=>$rest['error']['message']));
                    }
                
                    // validamos las confirmaciones
                    // SI es mayor o igual a 5 la validamos
                    if(intval($rest['result']['confirmations']) >= 5){
                        
                        //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"=>determinateDBError($db)));
                            
                        // Consultamos los datos del mensaje
                        $sql = "SELECT * FROM cmsmessages WHERE id = 8";
                        if (!$rs=$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                            
                        $data = $rs->fetch_assoc();
                        
                        // Validamos que el usuario tenga las notificaciones activas
                        $sql = "SELECT * FROM usermessages ".
                        "       WHERE categoryid = ".$data['category'].
                        "       AND usrid = ".$row['userid'];
                        if (!$rs=$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                            
                        $userPref = $rs->fetch_assoc();
                        
                        $userdata = getUserdata($db, $row['userid'],"Error al obtener data del usuario");
                        //UNA VEZ VALIDADO SE ENVÏA LA NOTIFICACION CORRESPONDIENTE ADD JR
                        if($userPref['email'] == null || $userPref['email'] == 1){
                            $subject = $userdata['lang'] == 'esp' ? $data['name_esp'] : $data['name_eng'];
                            $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
                            $body = "<div class='emailBox'>".
                            "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
                            "           <div class='mainBox'>".
                            "               <h1 class='titleEmail'>".
                            "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
                            "               </h1>".
                            "               <p class='msgEmail'>".
                            "                   ".($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_eng']))).
                            "               </p>".
                            "           </div>".
                            "           <p class='copy'>".$footerEmails."</p>".
                            "       </div>";
                            
                            $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
                                    
                            enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
                        }
                        
                        // Se valida la preferenca del mensaje y se envía según el idioma
                        if($userPref['sms'] == null || $userPref['sms'] == 1){
                            $msg = ($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['sms_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['sms_eng'])));
                            enviarSMS($userdata['phone'], $msg);
                        }
                        
                        if($userPref['system'] == null || $userPref['system'] == 1){
                            
                            $email = '';
                            $sms = '';
                            
                            // Si se envia por correo obtenemos el correo del usuario
                            if($userPref['email'] == null || $userPref['email'] == 1){
                                $sql = "SELECT usr ".
                                "       FROM users ".
                                "       WHERE id = ".$row['userid'];
                                if (!$resPref=$db->query($sql))
                                    badEnd("500", array("msg"=>determinateDBError($db)));
                                    
                                $rowPrefCom = $resPref->fetch_assoc();
                                
                                $email = $rowPrefCom['usr'];
                            }
                            
                            // SI se envia por sms, obtenemos el numero del usuario
                            if($userPref['sms'] == null || $userPref['sms'] == 1){
                                $sql = "SELECT IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone ".
                                "       FROM users ".
                                "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
                                "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
                                "       WHERE users.id = ".$row['userid'];
                                if (!$resPref=$db->query($sql))
                                    badEnd("500", array("msg"=>determinateDBError($db)));
                                    
                                $rowPrefCom = $resPref->fetch_assoc();
                                
                                $sms = $rowPrefCom['phone'];
                                
                            }
                            
                            // Enviamos el mensaje por la mensajeria interna
                            $msg = ( $userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_eng'])));
                            saveInternalMsg($db, $msg, $row['userid']);
                        }
                        
                        
                    }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"=>determinateDBError($db)));
                            
                        //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"=>determinateDBError($db)));
                    }
                }
                break;
            case 6:
                // USDT
                //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 transactions.validator IS NULL ".
                "       AND withdrawals.rejected IS NULL ".
                "       AND transactions.id = withdrawals.transactionid ".
                "       AND transactions.accountid = accounts.id ".
                "       AND accounts.entityusrid = -1 ".
                "       AND accounts.currencyid = ".$currencydata['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                //Luego de que tenemos los retiros pendientes consultamos cada retiro por individual para verificar su estado
                while($row = $res->fetch_assoc()){
                    $out->record [] = $row;
                    //  Consultamos por ese txid
                    $request = array('method'=>'getTransactionByTxid','txid'=>$row['ref']);
                    $rest = json_decode(queryServicesUSDT($USDT_URL, $request), true);
                    
                    if($rest != null && $rest['ret'][0]['contractRet'] == 'SUCCESS'){
                        //Actualizamos el retiro en la BD
                        $sql = "UPDATE withdrawals SET ".
                        "       paymentref = '".$rest['txID']."', ".
                        "       valid = NOW() ".
                        "       WHERE ref = '".$row['ref']."'";
                        if (!$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                        
                        // Consultamos los datos del mensaje
                        $sql = "SELECT * FROM cmsmessages WHERE id = 8";
                        if (!$rs=$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                        
                        $data = $rs->fetch_assoc();
                        
                        // Validamos que el usuario tenga las notificaciones activas
                        $sql = "SELECT * FROM usermessages ".
                        "       WHERE categoryid = ".$data['category'].
                        "       AND usrid = ".$row['userid'];
                        if (!$rs=$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                            
                        $userPref = $rs->fetch_assoc();
                        
                        $userdata = getUserdata($db, $row['userid'],"Error al obtener data del usuario");
                            
                        //UNA VEZ VALIDADO SE ENVÏA LA NOTIFICACION CORRESPONDIENTE ADD JR
                        if($userPref['email'] == null || $userPref['email'] == 1){
                            $subject = $userdata['lang'] == 'esp' ? $data['name_esp'] : $data['name_eng'];
                            $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
                            $body = "<div class='emailBox'>".
                            "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
                            "           <div class='mainBox'>".
                            "               <h1 class='titleEmail'>".
                            "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
                            "               </h1>".
                            "               <p class='msgEmail'>".
                            "                   ".($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_eng']))).
                            "               </p>".
                            "           </div>".
                            "           <p class='copy'>".$footerEmails."</p>".
                            "       </div>";
                            
                            $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
                                    
                            enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
                        }
                        
                        // Se valida la preferenca del mensaje y se envía según el idioma
                        if($userPref['sms'] == null || $userPref['sms'] == 1){
                            $msg = ($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['sms_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['sms_eng'])));
                            enviarSMS($userdata['phone'], $msg);
                        }   
                        
                        if($userPref['system'] == null || $userPref['system'] == 1){
                            
                            $email = '';
                            $sms = '';
                            
                            // Si se envia por correo obtenemos el correo del usuario
                            if($userPref['email'] == null || $userPref['email'] == 1){
                                $sql = "SELECT usr ".
                                "       FROM users ".
                                "       WHERE id = ".$row['userid'];
                                if (!$resPref=$db->query($sql))
                                    badEnd("500", array("msg"=>determinateDBError($db)));
                                        
                                $rowPrefCom = $resPref->fetch_assoc();
                                
                                $email = $rowPrefCom['usr'];
                            }
                                
                            // SI se envia por sms, obtenemos el numero del usuario
                            if($userPref['sms'] == null || $userPref['sms'] == 1){
                                $sql = "SELECT IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone ".
                                "       FROM users ".
                                "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
                                "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
                                "       WHERE users.id = ".$row['userid'];
                                if (!$resPref=$db->query($sql))
                                    badEnd("500", array("msg"=>determinateDBError($db)));
                                    
                                $rowPrefCom = $resPref->fetch_assoc();
                                
                                $sms = $rowPrefCom['phone'];
                                
                            }
                                            
                            // Enviamos el mensaje por la mensajeria interna
                            $msg = ($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['sms_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['sms_eng'])));
                            saveInternalMsg($db, $msg, $row['userid'], $email, $sms);
                        }
                    }else if($rest != null && $rest['ret'][0]['contractRet'] != 'SUCCESS' && ($rest['ret'][0]['contractRet'] == 'OUT_OF_ENERGY' || $rest['ret'][0]['contractRet'] == 'REVERT')){
                        //Actualizamos el retiro en la BD
                        $sql = "UPDATE withdrawals SET ".
                        "       rejected = NOW() ".
                        "       WHERE ref = '".$row['ref']."'";
                        if (!$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                            
                        //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"=>determinateDBError($db)));
                    }
                }
                break;
            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 transactions.validator IS NULL ".
                "       AND withdrawals.rejected IS NULL ".
                "       AND transactions.id = withdrawals.transactionid ".
                "       AND transactions.accountid = accounts.id ".
                "       AND accounts.entityusrid = -1 ".
                "       AND accounts.currencyid = ".$currencydata['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                //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){
                        continue;
                        //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"=>determinateDBError($db)));
                                
                            // Consultamos los datos del mensaje
                            $sql = "SELECT * FROM cmsmessages WHERE id = 8";
                            if (!$rs=$db->query($sql))
                                badEnd("500", array("msg"=>determinateDBError($db)));
                                
                            $data = $rs->fetch_assoc();
                            
                            // Validamos que el usuario tenga las notificaciones activas
                            $sql = "SELECT * FROM usermessages ".
                            "       WHERE categoryid = ".$data['category'].
                            "       AND usrid = ".$row['userid'];
                            if (!$rs=$db->query($sql))
                                badEnd("500", array("msg"=>determinateDBError($db)));
                                
                            $userPref = $rs->fetch_assoc();
                            
                            $userdata = getUserdata($db, $row['userid'],"Error al obtener data del usuario");
                                
                            //UNA VEZ VALIDADO SE ENVÏA LA NOTIFICACION CORRESPONDIENTE ADD JR
                            if($userPref['email'] == null || $userPref['email'] == 1){
                                $subject = $userdata['lang'] == 'esp' ? $data['name_esp'] : $data['name_eng'];
                                $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
                                $body = "<div class='emailBox'>".
                                "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
                                "           <div class='mainBox'>".
                                "               <h1 class='titleEmail'>".
                                "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
                                "               </h1>".
                                "               <p class='msgEmail'>".
                                "                   ".($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_eng']))).
                                "               </p>".
                                "           </div>".
                                "           <p class='copy'>".$footerEmails."</p>".
                                "       </div>";
                                
                                $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
                                        
                                enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
                            }
                            
                            // Se valida la preferenca del mensaje y se envía según el idioma
                            if($userPref['sms'] == null || $userPref['sms'] == 1){
                                $msg = ($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['sms_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['sms_eng'])));
                                enviarSMS($userdata['phone'], $msg);
                            }   
                            
                            if($userPref['system'] == null || $userPref['system'] == 1){
                                
                                $email = '';
                                $sms = '';
                                
                                // Si se envia por correo obtenemos el correo del usuario
                                if($userPref['email'] == null || $userPref['email'] == 1){
                                    $sql = "SELECT usr ".
                                    "       FROM users ".
                                    "       WHERE id = ".$row['userid'];
                                    if (!$resPref=$db->query($sql))
                                        badEnd("500", array("msg"=>determinateDBError($db)));
                                            
                                    $rowPrefCom = $resPref->fetch_assoc();
                                    
                                    $email = $rowPrefCom['usr'];
                                }
                                
                                // SI se envia por sms, obtenemos el numero del usuario
                                if($userPref['sms'] == null || $userPref['sms'] == 1){
                                    $sql = "SELECT IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone ".
                                    "       FROM users ".
                                    "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
                                    "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
                                    "       WHERE users.id = ".$row['userid'];
                                    if (!$resPref=$db->query($sql))
                                        badEnd("500", array("msg"=>determinateDBError($db)));
                                        
                                    $rowPrefCom = $resPref->fetch_assoc();
                                    
                                    $sms = $rowPrefCom['phone'];
                                    
                                }
                                                
                                // Enviamos el mensaje por la mensajeria interna
                                $msg = ($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['sms_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['sms_eng'])));
                                saveInternalMsg($db, $msg, $row['userid'], $email, $sms);
                            }
                                
                        }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"=>determinateDBError($db)));
                                
                            //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"=>determinateDBError($db)));
                        }
                    }
                }
                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, ".
                "       accounts.userid AS userid " .
                "       FROM accounts, withdrawals, transactions ".
                "       WHERE withdrawals.valid IS NULL ".
                "       AND transactions.validator IS NULL ".
                "       AND withdrawals.rejected IS NULL ".
                "       AND transactions.id = withdrawals.transactionid ".
                "       AND transactions.accountid = accounts.id ".
                "       AND accounts.entityusrid = -1 ".
                "       AND accounts.currencyid = ".$currencydata['id'];
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                    
                //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);
                    
                    // Validamos que el error no sea nulo para mandar el mensaje
                    if($rest['error'] != null){
                        continue;
                        //badEnd('500',array("msg"=>$rest['error']['message']));
                    }
                    
                    // 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"=>determinateDBError($db)));
                            
                        // Consultamos los datos del mensaje
                        $sql = "SELECT * FROM cmsmessages WHERE id = 8";
                        if (!$rs=$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                            
                        $data = $rs->fetch_assoc();
                        
                        // Validamos que el usuario tenga las notificaciones activas
                        $sql = "SELECT * FROM usermessages ".
                        "       WHERE categoryid = ".$data['category'].
                        "       AND usrid = ".$row['userid'];
                        if (!$rs=$db->query($sql))
                            badEnd("500", array("msg"=>determinateDBError($db)));
                            
                        $userPref = $rs->fetch_assoc();
                        
                        $userdata = getUserdata($db, $row['userid'],"Error al obtener data del usuario");
                        //UNA VEZ VALIDADO SE ENVÏA LA NOTIFICACION CORRESPONDIENTE ADD JR
                        if($userPref['email'] == null || $userPref['email'] == 1){
                            $subject = $userdata['lang'] == 'esp' ? $data['name_esp'] : $data['name_eng'];
                            $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
                            $body = "<div class='emailBox'>".
                            "           <img class='afxLogo' src='".$homeurl."./settings/img/logo-email.png'/>".
                            "           <div class='mainBox'>".
                            "               <h1 class='titleEmail'>".
                            "                   ".($userdata['lang'] == "esp" ? "Hola" : "Hello")." ".$userdata['name'].
                            "               </h1>".
                            "               <p class='msgEmail'>".
                            "                   ".($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_eng']))).
                            "               </p>".
                            "           </div>".
                            "           <p class='copy'>".$footerEmails."</p>".
                            "       </div>";
                            
                            $body = templateEmail($body, $STANDAR_STYLE_EMAIL);
                                    
                            enviarCorreo2($fromeMail, strtolower($userdata['email']), $subject, $body);
                        }
                        
                        // Se valida la preferenca del mensaje y se envía según el idioma
                        if($userPref['sms'] == null || $userPref['sms'] == 1){
                            $msg = ($userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['sms_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['sms_eng'])));
                            enviarSMS($userdata['phone'], $msg);
                        }
                        
                        if($userPref['system'] == null || $userPref['system'] == 1){
                            
                            $email = '';
                            $sms = '';
                            
                            // Si se envia por correo obtenemos el correo del usuario
                            if($userPref['email'] == null || $userPref['email'] == 1){
                                $sql = "SELECT usr ".
                                "       FROM users ".
                                "       WHERE id = ".$row['userid'];
                                if (!$resPref=$db->query($sql))
                                    badEnd("500", array("msg"=>determinateDBError($db)));
                                    
                                $rowPrefCom = $resPref->fetch_assoc();
                                
                                $email = $rowPrefCom['usr'];
                            }
                            
                            // SI se envia por sms, obtenemos el numero del usuario
                            if($userPref['sms'] == null || $userPref['sms'] == 1){
                                $sql = "SELECT IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone ".
                                "       FROM users ".
                                "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
                                "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
                                "       WHERE users.id = ".$row['userid'];
                                if (!$resPref=$db->query($sql))
                                    badEnd("500", array("msg"=>determinateDBError($db)));
                                    
                                $rowPrefCom = $resPref->fetch_assoc();
                                
                                $sms = $rowPrefCom['phone'];
                                
                            }
                            
                            // Enviamos el mensaje por la mensajeria interna
                            $msg = ( $userdata['lang'] == 'esp' ? (str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_esp'])):(str_replace('<currency_name>', $currencydata['symbol'],$data['dsc_eng'])));
                            saveInternalMsg($db, $msg, $row['userid']);
                        }
                        
                        
                    }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"=>determinateDBError($db)));
                            
                        //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"=>determinateDBError($db)));
                    }
                }
                break;
        }
    }
    
    function getUserdata($db, $userid, $msg = ''){
        $sql = "SELECT users.*, users.usr AS email, IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name,  ".
        "       IF(users.type = 1, userpersons.phone, usercompanies.phone) AS phone " .
        "       FROM users ".
        "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
        "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
        "       WHERE id = ".$userid;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
                    
        return $res->fetch_assoc();
    }
    
    
    $out->tiempo = microtime(true) - $mt;
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>