<?php
//  app/api/payments/pagomovil/update.php
    header("Content-Type:application/json");
    include("../../../../settings/dbconn.php");
    include("../../../../settings/utils.php");
    require '../../../hooks/PHPMailer5/PHPMailerAutoload.php';
    date_default_timezone_set('Etc/UTC');
    
    // parametros obligatorios
    $parmsob = array("sessionid", "paymentid", "recipient", "rif", "phone", "bankcode", "note", "sendat", "accountid", "VESamount");
    if (!parametrosValidos($_POST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables y almacenamiento de valores enviados por GET
    $out = new stdClass();
    $sessionid = $_POST["sessionid"];
    $paymentid = $_POST["paymentid"];
    $recipient = mysqli_real_escape_string($db, $_POST["recipient"]);
    $rif = mysqli_real_escape_string($db,$_POST["rif"]);
    $phone = mysqli_real_escape_string($db,$_POST["phone"]);
    $bankcode = mysqli_real_escape_string($db,$_POST["bankcode"]);
    $note = mysqli_real_escape_string($db,$_POST["note"]);
    $sendat = $_POST["sendat"];
    $accountid = $_POST["accountid"];
    $VESamount = $_POST["VESamount"];
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    isLevelValid($db, $userid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    // Validamos el permiso del usuario
    $sql = "SELECT * FROM users WHERE id = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $userPerm = $rs->fetch_assoc();
    
    // Preferencias de pago de terceros
    $paymentstothirdsparty = json_decode($userPerm['paymentstothirdsparty'], true);
    
    if(!$paymentstothirdsparty[0]['pagomovil']){
        badEnd("405", array("msg"=>determinateMsgFail(array(
            "esp"=>"No posee permisos",
            "eng"=>"does not have permissions"), $lang, "No posee permisos")));
    }
    
    if($VESamount <= 0){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Monto no puede ser menor o igual a 0",
            "eng"=>"Amount cannot be less than or equal to 0"), $lang, "Monto no puede ser menor o igual a 0")));
    }
    
    // Obtenemos los datos de la cuenta del usuario
    $sql = "SELECT * FROM accounts ".
    "       WHERE id = ".$accountid.
    "       AND userid = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $accountdata = $rs->fetch_assoc();
    
    if($accountdata['id'] == null){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Cuenta no encontrada",
            "eng"=>"Account not found"), $lang, "Cuenta no encontrada")));
    }
    
    $currencyid = $accountdata['currencyid'];
    
    // Obtenemos los datos de la cuenta del usuario FIAT
    $sql = "SELECT * FROM accounts ".
    "       WHERE currencyid = 1".
    "       AND userid = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $accountfiat = $rs->fetch_assoc();
    $accountfiatid = $accountfiat['id'];
    
    // Obtenemos los datos de la moneda
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currency = $rs->fetch_assoc();
    
    // Obtenemos los datos del BS
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = 1";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currencyfiat = $rs->fetch_assoc();
    
    // Obtenemos el rate de la moneda para VES para la descripcion
    $rate = determinateRate($db, $currencyfiat["id"], $currency['id'], $currencyfiat['decimals']); //se volteó las monedas y se cambiaron los decimals 
    $amountReal = number_format($VESamount*$rate->number, $currency['decimals'], '.', '');
    $showedAmountVes  = number_format($VESamount, $currencyfiat['decimals'], '.', '');
    
    // Obtenemos la cuenta AFX del usuario
    $sql = "SELECT id FROM accounts  ".
    "       WHERE currencyid = ".$currencyid.
    "       AND paymentmethodid = -1 " .
    "       AND accounts.entityusrid = -1 ".
    "       AND userid=".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db).$sql));
        
    $account = $rs->fetch_assoc();
    
    // Consultamos de la vista ya creada con el balance
    $sql = "SELECT * FROM accountbalances WHERE accountid = ".$accountid;
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $balancetx = $res->fetch_assoc();
    
    if(
        number_format($balancetx["balance"], $currency['decimals'], '.', '') <= 0 ||
        number_format($balancetx["balance"], $currency['decimals'], '.', '') < $amountReal
    ){
        badEnd("402", array("msg"=>determinateMsgFail(array(
            "esp"=>"Saldo Insuficiente",
            "eng"=>"Insufficient balance"), $lang, "Saldo Insuficiente")));
    }
    
    //Obtenemos el nivel de usuario para determinar su fee
    $sql = "SELECT * FROM users WHERE id = ".$userid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta
    $userdata = $rs->fetch_assoc();
    
    $level = 1;
    if($userdata["level"] == 0){
        $level = 1;
    }else{
        $level = $userdata["level"];
    }
    
    //Consultamos la cuenta que tiene los saldos de los pago moviles
    $sql = "SELECT * FROM accounts ".
    "       WHERE userid = -1".
    "       AND currencyid = ".$currency["id"].
    "       AND paymentmethodid = -7";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta AFX
    $afxdatabalances = $rs->fetch_assoc();
    
    //Consultamos la cuenta que tiene la moneda del retiro de AFX
    $sql = "SELECT * FROM accounts ".
    "       WHERE userid = -1".
    "       AND currencyid = ".$currency["id"].
    "       AND paymentmethodid = -6";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta AFX
    $afxdata = $rs->fetch_assoc();
    
    // Buscamos la cuenta de comision de AFX para retiros
    $sql = "SELECT * FROM accounts ".
    "       WHERE userid = -1".
    "       AND currencyid = ".$currency["id"].
    "       AND paymentmethodid = -2";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta AFX
    $afxdatawithdrawal = $rs->fetch_assoc();
    
    //Obtenemos el fee de cada operacion por la moneda de la cuenta
    $sql = "SELECT * FROM cmspreffees WHERE currencyid = ".$currencyfiat["id"].
    "       AND levelid = ".$level.
    "       AND usertype = ".$userdata["type"];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    //Guardamos la data de la cuenta
    $fee = $rs->fetch_assoc();
    
    //Validamos que el monto sea mas que el minimo aceptado para transferencia
    if(validateMin(1,$userdata["type"], 3, $db, $showedAmountVes)){
        badEnd("403", array("msg"=> "Monto m&iacute;nimo autorizado: ".numberFormatt($fee['minwithdraw'], $currencyfiat['decimals'])." ".$currencyfiat['symbol']));
    }
    
    // SACAMOS LA COMISION PARA PAGO MOVIL PRIMERO
    $feepagomovil = 0;
    if($fee["pagomovilpct"] != null){
        // Obtenemos el exonerado para depositos si posee
        $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
        "       WHERE currencyid = ".$currencyfiat["id"].
        "       AND userid = ".$userdata['id'].
        "       AND preffeesfield = 'pagomovilpct'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $userExg = $res->fetch_assoc();
        
        $feepagomovil = number_format((($fee["pagomovilpct"] - ($fee["pagomovilpct"]/100 * $userExg['exonerated']) )*$amountReal)/100, $currency['decimals'], '.', '');
    }
    
    // SACAMOS LA COMISION PARA RETIRO PORCENTAJE FIAT
    $sql = "SELECT * FROM cmspreffees WHERE currencyid = ".$currencyfiat["id"].
    "       AND levelid = ".$level.
    "       AND usertype = ".$userdata["type"];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    //Guardamos la data de la cuenta
    $fee = $rs->fetch_assoc();
        
    $feewithdrawal = 0;
    if($fee["pctfeewithdrawals"] != null || $fee["nmlfeewithdrawals"] != null ){
        if($fee["pctfeewithdrawals"] == null){
            
            // Obtenemos el exonerado para depositos si podee
            $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
            "       WHERE currencyid = ".$currencyfiat["id"].
            "       AND userid = ".$userdata['id'].
            "       AND preffeesfield = 'nmlfeewithdrawals'";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $userExg = $res->fetch_assoc();
            
            // Cambiamos a la moneda que es
            $userExgRated = number_format($userExg['exonerated']*$rate->number, $currency['decimals'], '.', '');
            $feeRated = number_format($fee["nmlfeewithdrawals"]*$rate->number, $currency['decimals'], '.', '');
           /* $out->test = $feeRated;
            $out->test2 = $userExgRated;
            $out->res = $userExg['exonerated'];
            $out->res2 = $fee["nmlfeewithdrawals"];
            $out->rate = $rate1;
            echo(json_encode($out));
    die();*/
            
            $feewithdrawal = number_format($amountReal - ($amountReal - ($feeRated - ($feeRated/100 * $userExgRated) )), $currency['decimals'], '.', '');
        }else{
            
            // Obtenemos el exonerado para depositos si podee
            $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
            "       WHERE currencyid = ".$currencyfiat["id"].
            "       AND userid = ".$userdata['id'].
            "       AND preffeesfield = 'pctfeewithdrawals'";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db)));
            
            $userExg = $res->fetch_assoc();
            
            $feewithdrawal = number_format((($fee["pctfeewithdrawals"] - ($fee["pctfeewithdrawals"]/100 * $userExg['exonerated']) )*$amountReal)/100, $currency['decimals'], '.', '');
        }
    }
        
    // AHORA VEMOS SI TIENE SUFICIENTE SALDO CON LAS COMISIONES
    if(
        number_format($balancetx["balance"], $currency['decimals'], '.', '') < number_format($amountReal + $feewithdrawal + $feepagomovil, $currency['decimals'], '.', '')
    ){
        badEnd("403", array("msg"=>"Saldo insuficiente"));
    }
    
    $validator = getValidator(8);
    $validatorMd5 = md5($validator);
    
    validateOperations($db, $accountfiatid, $userid, $showedAmountVes, 2);
    validateOperations($db, $accountfiatid, $userid, $showedAmountVes, 4);
    
    $bankinterface = getActiveBank($db, 2, 1);
    
    // Buscamos los bancos
    $bankname = '';
    switch($bankinterface){
        case 0:
            badEnd("204", array("msg"=>determinateMsgFail(array(
                "esp"=>'Servicio inactivo, intente más tarde',
                "eng"=>'Service down, please try again later'), $lang, "Servicio inactivo, intente más tarde")));
            break;
        case 1:
            // Consultamos el listado de bancos
            $headers = array('Content-Type:application/json');
            $request = array();
            $rest = queryApiBP($BP_URL_QA, "pagos/p2p/bancos", $BP_VERSION_P2P, "GET", $headers, $request);
            
            if($rest['httpres'] != 200 && $rest['httpres'] != 201){
                switch($rest['httpres']){
                    case 503:
                        badEnd("500", array("msg"=>determinateMsgFail(array(
                            "esp"=>'El servidor no puede atender temporalmente su petición',
                            "eng"=>'The server is temporarily unable to service your petition BP'), $lang, "El servidor no puede atender temporalmente su petición")));
                        break;
                    default:
                        badEnd("500", array("msg"=>determinateMsgFail(array(
                            "esp"=>'Error llamada a API BP',
                            "eng"=>'Error Call to API'), $lang, "Error llamada a API BP")));
                }
            }
        
            $banks = $rest['bancos'];
            // recorremos los bancos para sacar el code a partir del nombre para la API
            foreach($banks as $bank){
                if ($bank['codigo'] == $bankcode) {
                    $bankname = $bank['nombre'];
                }
            }
        
            break;
        case 2:
            
            // Consultamos la api de banco activo
            $headers = array('Content-Type:application/json','apikey: '.$BA_API_KEY);
            $request = array("tipo_pagador"=>"P2P");
            $rest = queryApiBA($BA_URL_QA."lista_banco_pago_movil/1.0.0/bancos", "POST", $headers, $request);
            
            if($rest['httpres'] != 200 && $rest['httpres'] != 201){
                $msgs = validateErrorBancoActivo($rest['bodyres']->code, $rest['bodyres']->descripcion, $rest['bodyres']->descripcion);
                $msg_esp = $msgs->msg_esp;
                $msg_eng = $msgs->msg_eng;
                                
                $msg_esp = $msg_esp;
                $msg_eng = $msg_eng;
                
                badEnd("500", array("msg"=>determinateMsgFail(array(
                    "esp"=>$msg_esp,
                    "eng"=>$msg_eng), $lang, $msg_esp)));
            }
            
            $bancos = $rest['bodyres']->bancos;
            foreach($bancos as $bank){
                if ($bank->codBanco == $bankcode) {
                    $bankname = $bank->nombreBanco;
                }
            }
        break;
    }
    
    // Si es 0 creamos 1 nuevo registro
    if($paymentid == 0) {
    
        // Creamos el registro
        $sql = "INSERT INTO payments_pagomovil (".
        "       status,".
        "       datecreated,".
        "       recipient,".
        "       recipientrif,".
        "       recipientphone,".
        "       bankcode,".
        "       bankname,".
        "       note,".
        "       sendat,".
        "       sentat, ".
        "       ref, ".
        "       accountid, ".
        "       validationcode, ".
        "       amount, ".
        "       txid ".
        "       )".
        "       VALUES (".
        "       1, ".
        "       NOW(), ".
        "       '".$recipient."', ".
        "       '".$rif."', ".
        "       '".$phone."', ".
        "       '".$bankcode."', ".
        "       '".$bankname."', ".
        "       '".$note."', ".
        "       TIMESTAMP('".$sendat."'),".
        "       NULL, ".
        "       NULL, ".
        "       ".$accountid.", ".
        "       '".$validatorMd5."', ".
        "       ".$VESamount.", ".
        "       NULL ".
        "       )";
        if (!$db->query($sql)){
            $error = $db->error;
            $db->rollback();
            $db->close();
            badEnd("500", array("msg"=>$error));
        }
        
        $txid = (int)$db->insert_id;
        $paymentid = $txid;
        
        $email = $userdata["usr"];
        $subject = "Código para Cripto Pago ".$shortname;
        $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
        $styleTag = 
            "<style rel='stylesheet' type='text/css'>".
            "           .emailBox {".
            "               background-color: #F8F8FA;".
            "               padding: 20px;".
            "           }".
            "           .copy {".
            "               font-family: 'Roboto', sans-serif;".
            "               font-weight: 400;".
            "               font-size: 12px;".
            "               margin-top:40px;".
            "               color: #767E93;".
            "               text-align:center;".
            "           }".
            "           .mainBox {".
            "               margin: auto;".
            "               display: block;".
            "               background-color: #FFF;".
            "               border-radius: 22px;".
            "               width: 60%;".
            "               padding:30px;".
            "           }".
            "           .msg { ".
            "               font-size: 18px;".
            "               color: #474C58;".
            "               text-align:center;".
            "               margin-bottom:30px;".
            "               margin-left:20px;".
            "               margin-right:20px;".
            "           }".
            "           .titleEmail {".
            "               color:#474C58;".
            "               text-align:center;".
            "               font-size: 20px;".
            "               font-weight: bold;".
            "               margin-left:20px;".
            "               margin-right:20px;".
            "           }".
            "           .note {".
            "               text-align:center;".
            "               font-size:12px;".
            "               color: #474C58;".
            "           }".
            "           .code {".
            "               margin: auto;".
            "               display: block;".
            "               color: #FFF;".
            "               font-size: 18px;".
            "               text-align:center;".
            "               line-height: 58px;".
            "               font-weight:bold;".
            "               letter-spacing: 10px;".
            "           }".
            "           .validatorBox {".
            "               margin: auto;".
            "               display: block;".
            "               background-color: #4287CE;".
            "               border-radius: 8px;".
            "               width: 200px;".
            "               height: 57px;".
            "               text-align:center;".
            "           }".
            "           @media (max-width: 450px) {".
            "               .mainBox {".
            "                   width: 95% !important;".
            "                   padding: 25px 0px;".
            "               }".
            "               .emailBox {".
            "                   padding: 0px;".
            "               }".
            "               .titleEmail {".
            "                   font-size: 18px;".
            "               }".
            "               .msg, .code {".
            "                   font-size: 14px;".
            "               }".
            "           }".
            "</style>";
            $body = 
                "<div class='emailBox'>".
                "   <img style='margin: auto; display: block;margin-bottom:10px;' width='110' height='110' src='".$homeurl."./settings/img/logo-email.png'/>".
                "   <div class='mainBox'>".
                "       <img style='margin: auto; display: block;margin-bottom:20px;' width='160' height='130' src='".$homeurl."/img/img_transfer.png'/>".
                "       <h1 class='titleEmail'>Hola ".strtolower($email)."</h1>".
                "       <p class='msg'>".
                "           Para completar el Cripto Pago, ingrese el c&oacute;digo a continuaci&oacute;n".
                "       </p>".
                "       <div class='validatorBox'>".
                "           <p class='code'>".$validator."</p>".
                "       </div>".
                "   </div>".
                "   <p class='copy'>".$footerEmails."</p>".
                "</div>";
                
        $body = templateEmail($body, $styleTag);
                
        enviarCorreo2($fromeMail, strtolower($email), $subject, $body);
        
        $msg = 'Para completar el Cripto Pago, ingrese el código a continuación: '.$validator;
        enviarSMS($userdata['paymobilephone'], $msg); //Cambiado "phone" que no se obtiene del users por paymobilephone
        
        // Audit
        // Obtenemos el nombre del usuario
        $sql = "SELECT IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name ".
        "       FROM users ".
        "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
        "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
        "       WHERE sessionid = '".$sessionid."'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $userdataaudit = $res->fetch_assoc();
        
        $ipaddress = getRealIP();
        //auditoria
        setAudit($db, "CRIPTO PAGOS", $sessionid, "APP", "Se registró un pago móvil por ".$VESamount." ".$currencyfiat['symbol'].", del usuario ".$userdataaudit['name']." a la persona ".$recipient, $ipaddress);
        
    } else {
        //Validamos que existe
        $sql = "SELECT COUNT(payments_pagomovil.id) AS qty ".
        "       FROM payments_pagomovil ".
        "       JOIN accounts ON accounts.userid = ".$userid.
        "           AND accounts.id = payments_pagomovil.accountid".
        "       WHERE payments_pagomovil.id = ".$paymentid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        
        if($row['qty'] == 0){
            badEnd("402", array("msg"=>determinateMsgFail(array(
                "esp"=>"Pago no registrado",
                "eng"=>"Payment not registered"), $lang, "Pago no registrado")));
        }
        
        // Si existe, vemos que status posee
        $sql = "SELECT payments_pagomovil.* ".
        "       FROM payments_pagomovil ".
        "       JOIN accounts ON accounts.userid = ".$userid.
        "           AND accounts.id = payments_pagomovil.accountid".
        "       WHERE payments_pagomovil.id = ".$paymentid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $row = $rs->fetch_assoc();
        
        // Si es 1 o 2 podemos continuar
        if($row['status'] != 1 && $row['status'] != 2){
            badEnd("403", array("msg"=>determinateMsgFail(array(
                "esp"=>"No se puede editar",
                "eng"=>"Cannot edit"), $lang, "No se puede editar")));
        }
        
        // Actualizamos el registro
        $sql = "UPDATE payments_pagomovil SET".
        "       recipient = '".$recipient."', ".
        "       recipientrif = '".$rif."', ".
        "       recipientphone = '".$phone."', ".
        "       bankcode = '".$bankcode."', ".
        "       bankname = '".$bankname."', ".
        "       note = '".$note."', ".
        "       sendat = DATE('".$sendat."'), ".
        "       accountid = ".$accountid.", ".
        "       ".($row['status'] == 2 ? "validationcode = '".$validatorMd5."', status = 1," : "").
        "       amount = ".$VESamount." ".
        "       WHERE id = ".$paymentid;
        if (!$rs=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        // Si es status 2, mandamos el code
        if($row['status'] == 2) {
            $email = $userdata["usr"];
            $subject = "Código para Cripto Pago ".$shortname;
            $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
            $styleTag = 
                "<style rel='stylesheet' type='text/css'>".
                "           .emailBox {".
                "               background-color: #F8F8FA;".
                "               padding: 20px;".
                "           }".
                "           .copy {".
                "               font-family: 'Roboto', sans-serif;".
                "               font-weight: 400;".
                "               font-size: 12px;".
                "               margin-top:40px;".
                "               color: #767E93;".
                "               text-align:center;".
                "           }".
                "           .mainBox {".
                "               margin: auto;".
                "               display: block;".
                "               background-color: #FFF;".
                "               border-radius: 22px;".
                "               width: 60%;".
                "               padding:30px;".
                "           }".
                "           .msg { ".
                "               font-size: 18px;".
                "               color: #474C58;".
                "               text-align:center;".
                "               margin-bottom:30px;".
                "               margin-left:20px;".
                "               margin-right:20px;".
                "           }".
                "           .titleEmail {".
                "               color:#474C58;".
                "               text-align:center;".
                "               font-size: 20px;".
                "               font-weight: bold;".
                "               margin-left:20px;".
                "               margin-right:20px;".
                "           }".
                "           .note {".
                "               text-align:center;".
                "               font-size:12px;".
                "               color: #474C58;".
                "           }".
                "           .code {".
                "               margin: auto;".
                "               display: block;".
                "               color: #FFF;".
                "               font-size: 18px;".
                "               text-align:center;".
                "               line-height: 58px;".
                "               font-weight:bold;".
                "               letter-spacing: 10px;".
                "           }".
                "           .validatorBox {".
                "               margin: auto;".
                "               display: block;".
                "               background-color: #4287CE;".
                "               border-radius: 8px;".
                "               width: 200px;".
                "               height: 57px;".
                "               text-align:center;".
                "           }".
                "           @media (max-width: 450px) {".
                "               .mainBox {".
                "                   width: 95% !important;".
                "                   padding: 25px 0px;".
                "               }".
                "               .emailBox {".
                "                   padding: 0px;".
                "               }".
                "               .titleEmail {".
                "                   font-size: 18px;".
                "               }".
                "               .msg, .code {".
                "                   font-size: 14px;".
                "               }".
                "           }".
                "</style>";
                $body = 
                    "<div class='emailBox'>".
                    "   <img style='margin: auto; display: block;margin-bottom:10px;' width='110' height='110' src='".$homeurl."./settings/img/logo-email.png'/>".
                    "   <div class='mainBox'>".
                    "       <img style='margin: auto; display: block;margin-bottom:20px;' width='160' height='130' src='".$homeurl."/img/img_transfer.png'/>".
                    "       <h1 class='titleEmail'>Hola ".strtolower($email)."</h1>".
                    "       <p class='msg'>".
                    "           Para completar el Cripto Pago, ingrese el c&oacute;digo a continuaci&oacute;n".
                    "       </p>".
                    "       <div class='validatorBox'>".
                    "           <p class='code'>".$validator."</p>".
                    "       </div>".
                    "   </div>".
                    "   <p class='copy'>".$footerEmails."</p>".
                    "</div>";
                    
            $body = templateEmail($body, $styleTag);
                    
            enviarCorreo2($fromeMail, strtolower($email), $subject, $body);
            
            $msg = 'Para completar el Cripto Pago, ingrese el código a continuación: '.$validator;
            enviarSMS($userdata['paymobilephone'], $msg); //Cambiado "phone" que no se obtiene del users por paymobilephone
        }
        
        // Audit
        // Obtenemos el nombre del usuario
        $sql = "SELECT IF(userpersons.fname IS NULL, usercompanies.name, CONCAT(userpersons.fname,' ',userpersons.flastname)) AS name ".
        "       FROM users ".
        "       LEFT JOIN userpersons ON userpersons.usrid = users.id ".
        "       LEFT JOIN usercompanies ON usercompanies.usrid = users.id ".
        "       WHERE sessionid = '".$sessionid."'";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
            
        $userdataaudit = $res->fetch_assoc();
        
        $ipaddress = getRealIP();
        //auditoria
        setAudit($db, "CRIPTO PAGOS", $sessionid, "APP", "Se actualizó un pago móvil por ".$VESamount." ".$currencyfiat['symbol'].", del usuario ".$userdataaudit['name']." a la persona ".$recipient, $ipaddress);
    }
    
    // Return
    $out->transaction = new stdClass();
    
    $out->transaction->id = (int)$paymentid;
    
     // Main ??
    $out->transaction->main = new stdClass();
    $out->transaction->main->currency = new stdClass();
    $out->transaction->main->currency->id = $currencyfiat['id'];
    $out->transaction->main->currency->symbol = $currencyfiat['symbol'];
    $out->transaction->main->currency->name = $currencyfiat['name'];
    $out->transaction->main->currency->decimals = (int)$currencyfiat['decimals'];
    
    $out->transaction->main->amount = new stdClass();
    $out->transaction->main->amount->number = $showedAmountVes;
    $out->transaction->main->amount->formatted = numberFormatt($out->transaction->main->amount->number,$currencyfiat["decimals"]);;
    
    // Cuenta de origen
    $out->transaction->wallet = new stdClass();
    $out->transaction->wallet->currency = new stdClass();
    $out->transaction->wallet->currency->id = $currency['id'];
    $out->transaction->wallet->currency->symbol = $currency['symbol'];
    $out->transaction->wallet->currency->name = $currency['name'];
    $out->transaction->wallet->currency->decimals = (int)$currency['decimals'];
    
    $out->transaction->wallet->amount = new stdClass();
    $out->transaction->wallet->amount->number = $amountReal;
    $out->transaction->wallet->amount->formatted = numberFormatt($out->transaction->wallet->amount->number, $currency['decimals']);
    
    $out->transaction->wallet->fee = new stdClass();
    $out->transaction->wallet->fee->number = number_format($feewithdrawal + $feepagomovil, $currency['decimals'], '.', '');
    $out->transaction->wallet->fee->formatted = numberFormatt($out->transaction->wallet->fee->number, $currency['decimals']);
    
    $out->transaction->wallet->total = new stdClass();
    $out->transaction->wallet->total->number = number_format($amountReal + $feewithdrawal + $feepagomovil, $currency['decimals'], '.', '');
    $out->transaction->wallet->total->formatted = numberFormatt($out->transaction->wallet->total->number, $currency['decimals']);
    
    // Tasa
    $out->transaction->rate = $rate;
    
    // Destino
    $out->transaction->destination = new stdClass();
    $out->transaction->destination->bank = new stdClass();
    $out->transaction->destination->bank->code = $bankcode;
    $out->transaction->destination->bank->name = $bankname;
    $out->transaction->destination->recipient = new stdClass();
    $out->transaction->destination->recipient->phone = $phone;
    $out->transaction->destination->recipient->rif = $rif;
    $out->transaction->destination->recipient->name = $recipient;
    
    
    header("HTTP/1.1 200");
    echo(json_encode($out));
    die();
    
?>