<?php
// app/api/p2p/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","bankid",'phone','currencyid',"amount");
    if (!parametrosValidos($_POST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    //Definicion de variables e inicializacion
    $out = new stdClass;
    $sessionid = $_POST["sessionid"];
    $bankid = $_POST['bankid'];
    $phone = $_POST['phone'];
    $amount = $_POST['amount'];
    $currencyid = $_POST['currencyid'];
    
    if($amount <= 0){
        badEnd("403", array("msg"=>"Monto no puede ser menor o igual a 0"));
    }
    
    // formateamos el telefono para quitarle el zero
    $phone = preg_replace('/^0?/', '', $phone);
    
    //Validamos la session
    $userid = isSessionValid($db, $sessionid);
    
    //Validamos el si el usuario puede crear cuentas
    isLevelValid($db, $userid);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    // Obtenemos la cuenta AFX del usuario
    $sql = "SELECT * 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)));
        
    $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 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 la moneda del retiro de AFX
    $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();
    
    // Validamos que el interface de la moneda sea Bs
    $sql = "SELECT * ".
    "       FROM currencies ".
    "       WHERE id = ".$currencyid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $currency = $rs->fetch_assoc();
    
    // Si la interface es distinta a 1, no podemos hacer el pago
    if($currency['interface'] != 1){
        badEnd("500", array("msg"=>"La moneda debe ser Bs/VES"));
    }
    
    $amount = (float)number_format($amount, $currency['decimals'], '.', '');
        
    //Validamos que el monto sea mas que el minimo aceptado
    if(validateMin($currency['id'], $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 = ".$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 = ".$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) as qty FROM `transactions` WHERE accountid = ".$accountdata["id"];
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
    
    $balance = $res->fetch_assoc();
    
    $sql = "SELECT SUM(amount) AS qty ".
    "       FROM ( ".
    "           SELECT SUM(CASE WHEN orders.side = 1 THEN orders.quantity ELSE orders.total END) AS amount ".
    "           FROM orders ".
    "           WHERE orders.accountid = ".$accountdata["id"].
	"           AND orders.canceled IS NULL ".
	"           AND orders.type != 1 ".
    "       UNION ALL ".
    "           SELECT SUM(transactions.amount) AS amount ".
    "           FROM transactions, orders ".
    "           WHERE orders.id = transactions.orderid ".
    "           AND transactions.accountid = ".$accountdata["id"].
    "           AND orders.accountid = ".$accountdata["id"].
	"           AND orders.canceled IS NULL ".
	"           AND transactions.amount < 0 ".
	"           AND orders.type != 1 ".
	"       UNION ALL ".
	"           SELECT SUM(transactions.amount + transactions.amountghost) AS amount ".
	"           FROM transactions  ".
	"           WHERE transactions.paypending = 1".
	"           AND transactions.accountid = ".$accountdata["id"].
	"           AND NOT EXISTS(SELECT withdrawals.transactionid FROM withdrawals WHERE withdrawals.transactionid = transactions.id)".
	"      UNION ALL ".
	"           SELECT SUM(ABS(withdrawals.amount) + ABS(withdrawals.fee)) AS amount ".
	"           FROM transactions, withdrawals ".
	"           WHERE transactions.id = withdrawals.transactionid ".
	"           AND transactions.accountid = ".$accountdata["id"].
	"           AND withdrawals.valid IS NUll ".
	"           AND withdrawals.rejected IS NULL ".
    "       ) amount";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db)));
        
    $balanceorder = $res->fetch_assoc();
    
    if(number_format( ($balance["qty"] - $balanceorder['qty']), $currency['decimals'], '.', '') <= 0 || number_format(($balance["qty"] - $balanceorder['qty']), $currency['decimals'], '.', '') < number_format(($realamount + $realfee), $currency['decimals'], '.', '')){
        badEnd("403", array("msg"=>determinateMsgFail(array(
        "esp"=>"Saldo insuficiente",
        "eng"=>"Insufficient balance"), $lang, "Saldo insuficiente")));
    }
    
    validateOperations($db, $accountdata['id'], $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 con pago móvil', ".
    "       -".abs($realamount).", 0, ".
    "       DATE_ADD(NOW(), INTERVAL 10 MINUTE), ".
    "       ".$accountdata["id"].", '".$validator."', ".
    "       NULL, NULL, ".
    "       ".$accountdata["id"].", ".$bankid.
    "       )";
    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 con pago móvil', ".
    "       0, ".
    "       -".abs($realfee).", ".
    "       DATE_ADD(NOW(), INTERVAL 10 MINUTE), ".
    "       ".$accountdata["id"].", '".$validator."', ".
    "       NULL, ".
    "       ".$txid.", ".
    "       ".$accountdata["id"].", ".
    "       ".$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 con pago móvil', ".
    "       0, ".
    "       ".$realfee.", ".
    "       DATE_ADD(NOW(), INTERVAL 10 MINUTE), ".
    "       ".$afxdata["id"].", '".$validator."', ".
    "       NULL, ".
    "       ".$txid.", ".
    "       ".$accountdata["id"].", ".
    "       ".$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".
    "       (".
    "       paymentwallet, ".
    "       ref, ".
    "       createddate, ".
    "       fee, ".
    "       transactionid, ".
    "       valid, ".
    "       amount ".
    "       )".
    "       VALUES(".
    "       '".$bankid."', ".
    "       '".$phone."', ".
    "       NOW(), ".
    "       ".$realfee.", ".
    "       ".$txid.", ".
    "       NULL, ".
    "       -".abs($amount).
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db);
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    $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>";
    $msg_esp = "Para completar el retiro de fondos ingrese el c&oacute;digo a continuaci&oacute;n";
    $msg_eng = "To complete the withdrawal of funds enter the code below";
    $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" ? $msg_esp : $msg_eng).
            "       </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();
?>