<?php
// app/api/withdrawals/insert

    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","accountid","amount");
    if (!parametrosValidos($_POST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables e inicializacion
    $out = new stdClass;
    $sessionid = $_POST["sessionid"];
    $amount = $_POST["amount"];
    $accountid = $_POST["accountid"];
    
    if($amount <= 0){
        badEnd("403", array("msg"=>"Monto no puede ser menor o igual a 0"));
    }
    
    //Debemos validar si es moneda fiat o cripto, no pueden ser ambas
    //Tipo de transaccion: -cripto -fiat
    $withdrawType = "";
    $withdrawId = "";
    if($_POST["paymentaccountid"] != "" && $_POST["paymentwallet"] == ""){
        $withdrawType = "fiat";
        $withdrawId = $_POST["paymentaccountid"];
    }else if($_POST["paymentaccountid"] == "" && $_POST["paymentwallet"] != ""){
        $withdrawType = "cripto";
        $withdrawId = $_POST["paymentwallet"];
    }else{
        badEnd("400", array("msg"=>"Solo puede ser enviado paymentaccountid O paymentwallet, no ambos o ninguno"));
    }
    
    //Validamos la session
    $idUserSession = isSessionValid($db, $sessionid);
    //Validamos el si el usuario puede crear cuentas
    isLevelValid($db, $idUserSession);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Obtenemos la moneda en la cual se hace el retiro
    $sql = "SELECT * from accounts WHERE id = ".$accountid.
    "       AND accounts.entityusrid = -1 ";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta
    $accountdata = $rs->fetch_assoc();
    
    //validamos que exista
    if($accountdata["id"] == null){
        badEnd("500", array("msg"=>determinateMsgFail(array(
            "esp"=>"Accountid invalido",
            "eng"=>"Invalid Accountid"), $lang, "Accountid invalido")));
    }
    
    //Obtenemos el nivel de usuario para determinar su fee
    $sql = "SELECT * FROM users WHERE sessionid = '".$sessionid."'";
    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 la moneda del retiro de ".$shortname."
    $sql = "SELECT * FROM accounts WHERE userid = -1".
    "       AND currencyid = ".$accountdata["currencyid"].
    "       AND paymentmethodid = -2";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    //Guardamos la data de la cuenta AFX
    $afxdata = $rs->fetch_assoc();
    
    //Obtenemos el fee de cada operacion por la moneda de la cuenta
    $sql = "SELECT * FROM cmspreffees WHERE currencyid = ".$accountdata["currencyid"].
    "       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();
    
    //Consultamos la moneda para verificar si es FIAT o INTERNACIONAL
    $sql = "SELECT * FROM currencies WHERE id = ".$accountdata["currencyid"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currency = $res->fetch_assoc();
    
    // Formateamos el monto
    $amount = (float)number_format($amount,$currency['decimals'], '.', '');
    
    /* Si es FIAT o INTERNACIONAL, Debemos restar la comision DE EL BALANCE
    *   Si no, quitamos la comision de el monto
    */
    if(intval($currency['interface']) == 1 || intval($currency['interface']) == 2){
        
        //Validamos que el monto sea mas que el minimo aceptado
        if(validateMin($accountdata["currencyid"],$userdata["type"], 3, $db, $amount)){
            badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Monto m&iacute;nimo autorizado: ".numberFormatt($fee['minwithdraw'], $currency['decimals']),
            "eng"=>"Minimum amount authorized: ".numberFormatt($fee['minwithdraw'], $currency['decimals'])), $lang, "Monto m&iacute;nimo autorizado: ".numberFormatt($fee['minwithdraw'], $currency['decimals']))));
        }
    
        //Calculamos el monto real quitandole la comision
        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 = ".$accountdata["currencyid"].
                "       AND userid = ".$userdata['id'].
                "       AND preffeesfield = 'nmlfeewithdrawals'";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                $userExg = $res->fetch_assoc();
            
                $realfee = number_format(($fee["nmlfeewithdrawals"] - ($fee["nmlfeewithdrawals"]/100 * $userExg['exonerated'])), $currency['decimals'], '.', '');
                $realamount = number_format($amount, $currency['decimals'],'.','');
            }else{
                
                // Obtenemos el exonerado para depositos si podee
                $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
                "       WHERE currencyid = ".$accountdata["currencyid"].
                "       AND userid = ".$userdata['id'].
                "       AND preffeesfield = 'pctfeewithdrawals'";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                $userExg = $res->fetch_assoc();
                
                $realfee = number_format((($fee["pctfeewithdrawals"] - ($fee["pctfeewithdrawals"]/100 * $userExg['exonerated']) )*$amount)/100, $currency['decimals'], '.', '');
                $realamount = number_format($amount, $currency['decimals'],'.','');
            }
        }else{
            $realfee = 0;
            $realamount = number_format($amount, $currency['decimals'],'.','');
        }
        
        $sql = "SELECT SUM(amount) - ABS(IF(( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1) IS NOT NULL,  ".
    	"               ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1), 0)".
        "       + IF(( ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$accountid.
        "           AND orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1) IS NOT NULL, ( ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$accountid.
        "           AND orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1),0) ".
    	"      + IF ((SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)) IS NOT NULL, ".
    	"           (SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)), 0)".
    	"      ) as qty FROM transactions WHERE accountid = ".$accountid.
        "       AND paypending = 0";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $balancetx = $res->fetch_assoc();
    
        if(number_format($balancetx["qty"], $currency['decimals'], '.', '') <= 0 || number_format($balancetx["qty"], $currency['decimals'], '.', '') < number_format(($realamount + $realfee), $currency['decimals'], '.', '')){
            badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Saldo insuficiente",
            "eng"=>"Insufficient balance"), $lang, "Saldo insuficiente")));
        }
    }else{
        $sql = "SELECT SUM(amount) - ABS(IF(( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1) IS NOT NULL,  ".
    	"               ( ".
        "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
        "           FROM orders ".
        "           WHERE orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND orders.type != 1), 0)".
        "       + IF(( ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$accountid.
        "           AND orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1) IS NOT NULL, ( ".
        "           SELECT SUM(transactions.amount) AS amount ".
        "           FROM transactions, orders ".
        "           WHERE orders.id = transactions.orderid ".
        "           AND transactions.accountid = ".$accountid.
        "           AND orders.accountid = ".$accountid.
    	"           AND orders.canceled IS NULL ".
    	"           AND transactions.amount < 0 ".
    	"           AND orders.type != 1),0) ".
    	"      + IF ((SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)) IS NOT NULL, ".
    	"           (SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
    	"           FROM transactions  ".
    	"           WHERE transactions.paypending = 1".
    	"           AND transactions.accountid = ".$accountid.
    	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)), 0)".
    	"      ) as qty FROM transactions WHERE accountid = ".$accountid.
        "       AND paypending = 0";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>determinateDBError($db)));
        
        $balancetx = $res->fetch_assoc();
        
        if(number_format($balancetx["qty"], $currency['decimals'], '.', '') <= 0 || number_format($balancetx["qty"], $currency['decimals'], '.', '') < $amount){
            badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Saldo insuficiente",
            "eng"=>"Insufficient balance"), $lang, "Saldo insuficiente")));
        }
        
        //Validamos que el monto sea mas que el minimo aceptado
        if(validateMin($accountdata["currencyid"],$userdata["type"], 3, $db, $amount)){
            badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Monto m&iacute;nimo autorizado: ".numberFormatt($fee['minwithdraw'], $currency['decimals']),
            "eng"=>"Minimum amount authorized: ".numberFormatt($fee['minwithdraw'], $currency['decimals'])), $lang, "Monto m&iacute;nimo autorizado: ".numberFormatt($fee['minwithdraw'], $currency['decimals']))));
        }
        
        if(intval($currency['interface']) == 4){
            $parms = array("conf_target"=>3);
            $request = array('method'=>'estimatesmartfee','parms' => $parms);
            $rspfee = json_decode(queryServicesBTC($BTC_URL, $request), true); 
            $out->testsmart = $rspfee;
            
            $parms = array("amount"=>$rspfee['result']['feerate']);//0.00001255);//
            $request = array('method'=>'settxfee','parms' => $parms);
            $rspsettingfee = json_decode(queryServicesBTC($BTC_URL, $request), true); 
            $out->resapi = $rspsettingfee;
            
            if($rspsettingfee['result'] == false){
                badEnd('500',array("msg"=>determinateMsgFail(array(
                    "esp"=>"Error API no se pudo calcular la comisión BTC ".$rsp['error']['message'],
                    "eng"=>"API error could not calculate the BTC commission ".$rsp['error']['message']), $lang, "Error API no se pudo calcular la comisión BTC ".$rsp['error']['message']),'out'=>$out));
            }
        }else if(intval($currency['interface']) == 5){
            /*$feetmp = determinateFee(intval($currency['interface']), $TCV_URL, 10, $VERSION_API, $TCV_JWT);
            
            $realfee += $feetmp;*/
        }else if(intval($currency['interface']) == 6){
            
        }else if(intval($currency['interface']) == 7){
            $parms = array("conf_target"=>5);
            $request = array('method'=>'estimatesmartfee','parms' => $parms);
            $rspfee = json_decode(queryServicesDash($DASH_URL, $request),true);
            $out->testsmart = $rspfee;
            
            $parms = array("amount"=>$rspfee['result']['feerate']);//0.00001255);//
            $request = array('method'=>'settxfee','parms' => $parms);
            $rspsettingfee = json_decode(queryServicesDash($DASH_URL, $request),true);
            $out->resapi = $rspsettingfee;
            
            if($rspsettingfee['result'] == false){
                badEnd('500',array("msg"=>determinateMsgFail(array(
                    "esp"=>"Error API no se pudo calcular la comisión DASH ".$rsp['error']['message'],
                    "eng"=>"API error could not calculate the DASH commission ".$rsp['error']['message']), $lang, "Error API no se pudo calcular la comisión DASH ".$rsp['error']['message']),'out'=>$out));
            }
        }
    
        //Calculamos el monto real quitandole la comision
        if($fee["pctfeewithdrawals"] != null || $fee["nmlfeewithdrawals"] != null ){
            if($fee["pctfeewithdrawals"] == null){
                $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
                "       WHERE currencyid = ".$accountdata["currencyid"].
                "       AND userid = ".$userdata['id'].
                "       AND preffeesfield = 'nmlfeewithdrawals'";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                $userExg = $res->fetch_assoc();
            
                $realfee = number_format($amount - ($amount - ($fee["nmlfeewithdrawals"] - ($fee["nmlfeewithdrawals"]/100 * $userExg['exonerated']) )), $currency['decimals'], '.', '');
                $realamount = number_format($amount - $realfee, $currency['decimals'], '.', '');
            }else{
                
                $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
                "       WHERE currencyid = ".$accountdata["currencyid"].
                "       AND userid = ".$userdata['id'].
                "       AND preffeesfield = 'pctfeewithdrawals'";
                if (!$res=$db->query($sql))
                    badEnd("500", array("msg"=>determinateDBError($db)));
                
                $userExg = $res->fetch_assoc();
                
                $realfee = number_format((($fee["pctfeewithdrawals"] - ($fee["pctfeewithdrawals"]/100 * $userExg['exonerated']) )*$amount)/100, $currency['decimals'], '.', '');
                $realamount = number_format($amount - $realfee, $currency['decimals'], '.', '');
            }
        }else{
            $realfee = number_format((2*$amount)/100, $currency['decimals'], '.', '');
            $realamount = number_format($amount - $realfee, $currency['decimals'], '.', '');
        }
    }
    
    validateOperations($db, $accountid, $userdata["id"], $amount, 2);
    
    if($realamount <= 0){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Total neto no puede ser menor o igual a 0",
            "eng"=>"Total cannot be less than or equal to 0"), $lang, "Total neto no puede ser menor o igual a 0")));
    }
    
    $validator = getValidator(8);
    
    $db->autocommit(FALSE);
        
    //insertamos la trasaccion del retiro
    $sql = "INSERT INTO transactions".
    "       (datecreated, dsc, ".
    "       amountghost, amount, ".
    "       validthru, ".
    "       accountid, validator, ".
    "       orderid, txid, ".
    "       accountorigin, accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), 'Retiro', ".
    "       -".abs($realamount).", 0, ".
    "       DATE_ADD(NOW(), INTERVAL 10 MINUTE), ".
    "       ".$accountid.", '".$validator."', ".
    "       NULL, NULL, ".
    "       ".$accountid.",".($withdrawType == "fiat" ? $withdrawId : "'".$withdrawId."'" ).
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //Guardamos el id de la transaccion de deposito
    $txid = (int)$db->insert_id;
    $out->id = (int)$txid;
    
    //Le colocamos a la primera transferencia el txid
    $sql = "UPDATE transactions SET".
    "       txid = ".$txid.
    "       WHERE id = ".$txid;
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //insertamos la comision del retiro
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amount, ".
    "       amountghost, ".
    "       validthru, ".
    "       accountid, validator, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Comisión de Retiro', ".
    "       0, ".
    "       -".abs($realfee).", ".
    "       DATE_ADD(NOW(), INTERVAL 10 MINUTE), ".
    "       ".$accountid.", '".$validator."', ".
    "       NULL, ".
    "       ".$txid.", ".
    "       ".$accountid.", ".
    "       ".$afxdata["id"].
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //insertamos la comision del retiro hacia la cuenta POTE
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amount, ".
    "       amountghost, ".
    "       validthru, ".
    "       accountid, ".
    "       validator, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Comisión de Retiro', ".
    "       0, ".
    "       ".$realfee.", ".
    "       DATE_ADD(NOW(), INTERVAL 10 MINUTE), ".
    "       ".$afxdata["id"].", '".$validator."', ".
    "       NULL, ".
    "       ".$txid.", ".
    "       ".$accountid.", ".
    "       ".$afxdata["id"].
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //insertamos el retiro
    $sql = "INSERT INTO withdrawals".
    "       (".
    "       ".($withdrawType == "fiat" ? "paymentaccountid" :"paymentwallet" ).", ".
    "       createddate, ".
    "       fee, ".
    "       transactionid, ".
    "       valid, ".
    "       amount ".
    "       )".
    "       VALUES(".
    "       ".($withdrawType == "fiat" ? $withdrawId : "'".$withdrawId."'" ).", ".
    "       NOW(), ".
    "       ".$realfee.", ".
    "       ".$txid.", ".
    "       NULL, ".
    "       -".abs($realamount).//CAMBIADO VALOR "$amount" A "$realamount" no se si afecta caso fiat revisar
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    if($withdrawType != "fiat"){
        $out->transacctionid = $txid;
    }
    
    // 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, "OPERACIONES", $sessionid, "APP", "Se registró un retiro por ".$amount." (".$out->id.") en ".$currency['name'].", del usuario ".$userdataaudit['name'], $ipaddress);
    
    $db->commit();
    $db->close();
    
    $email = $userdata["usr"];
    $subject = $userdata['lang'] == 'esp' ? "Código de retiro ".$shortname."" : 'Withdrawal code '.$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'>".($lang == "esp" ? "Hola" : "Hello")." ".strtolower($email)."</h1>".
            "       <p class='msg'>".
            "           ".($lang == "esp" ? "Para completar el retiro de fondos ingrese el c&oacute;digo a continuaci&oacute;n" : 
                                "To complete the withdrawal of funds enter the code below").
            "       </p>".
            "       <div class='validatorBox'>".
            "           <p class='code'>".$validator."</p>".
            "       </div>".
            "       <p class='note'>".
            "           ".($lang == "esp" ? "Este c&oacute;digo expirar&aacute; en 10 minutos" : "This code will expire in 10 minutes").
            "       .</p>".
            "   </div>".
            "   <p class='copy'>".$footerEmails."</p>".
            "</div>";
            
    $body = templateEmail($body, $styleTag);
            
    enviarCorreo2($fromeMail, strtolower($email), $subject, $body);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>