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

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // 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;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //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"=>$db->error));
    
    //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"=>$db->error));
    
    //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"=>$db->error));
    
    //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"=>$db->error));
        
    $currency = $res->fetch_assoc();
    
    /* 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){
                $realfee = number_format($fee["nmlfeewithdrawals"], $currency['decimals'],'.','');
                $realamount = number_format($amount, $currency['decimals'],'.','');
            }else{
                $realfee = number_format(($fee["pctfeewithdrawals"]*$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 = ".$accountid;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $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 = ".$accountid.
	    "           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 = ".$accountid.
        "           AND orders.accountid = ".$accountid.
        "           AND orders.canceled IS NULL ".
        "           AND transactions.amount < 0 ".
        "           AND orders.type != 1 ".
        "       ) amount";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
        
        $balanceorder = $res->fetch_assoc();
    
        if(($balance["qty"] - $balanceorder['qty']) <= 0 || ($balance["qty"] - $balanceorder['qty']) < ($realamount + $realfee)){
            badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Saldo insuficiente",
            "eng"=>"Insufficient balance"), $lang, "Saldo insuficiente")));
        }
    }else{
        $sql = "SELECT SUM(amount) as qty FROM `transactions` WHERE accountid = ".$accountid;
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
        
        $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 = ".$accountid.
	    "           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 = ".$accountid.
        "           AND orders.accountid = ".$accountid.
        "           AND orders.canceled IS NULL ".
        "           AND transactions.amount < 0 ".
        "           AND orders.type != 1 ".
        "       ) amount";
        if (!$res=$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
        
        $balanceorder = $res->fetch_assoc();
        
        if(($balance["qty"] - $balanceorder['qty']) <= 0 || ($balance["qty"] - $balanceorder['qty']) < $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']))));
        }
    
        //Calculamos el monto real quitandole la comision
        if($fee["pctfeewithdrawals"] != null || $fee["nmlfeewithdrawals"] != null ){
            if($fee["pctfeewithdrawals"] == null){
                $realfee = number_format($amount - ($amount - $fee["nmlfeewithdrawals"]),$currency['decimals'], '.', '');
                $realamount = $amount - $realfee;
            }else{
                $realfee = number_format(($fee["pctfeewithdrawals"]*$amount)/100,$currency['decimals'], '.', '');
                $realamount = $amount - $realfee;
            }
        }else{
            $realfee = number_format((2*$amount)/100, $currency['decimals'], '.', '');
            $realamount = $amount - $realfee;
        }
    }
    
    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 = $db->error;
        $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 = $db->error;
        $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 = $db->error;
        $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 = $db->error;
        $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($amount).
    "       )";
    if (!$db->query($sql)){
        $error = $db->error;
        $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"=>$db->error));
        
    $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 = "Código de retiro AFX";
    $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
    
    $body = "<html>".
            "   <head>".
            "       <title></title>".
            "       <link href='https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap' rel='stylesheet'>".
            "       <link href='https://fonts.googleapis.com/css2?family=Roboto&display=swap' rel='stylesheet'>".
            "       <style>".
            "           .goodText {".
            "               font-family: 'Open Sans', sans-serif;".
            "           }".
            "           .code {".
            "               font-family: Helvetica, sans-serif".
            "           }".
            "           .copy {".
            "               font-family: 'Roboto', sans-serif;".
            "               font-weight: 400;".
            "               font-size: 12px;".
            "           }".
            "       </style>".
            "   </head>".
            "   <body>".
            "       <div style='background-color: #F8F8FA;padding: 20px;'>".
            "           <img style='margin: auto; display: block;margin-bottom:10px;' width='110' height='110' src='".$homeurl."/img/afx-logo-email.png'/>".
            "           <div style='margin: auto; display: block;background-color: #FFF;border-radius: 22px;width: 60%;padding:30px;'>".
            "               <img style='margin: auto; display: block;margin-bottom:20px;' width='160' height='130' src='".$homeurl."/img/img_retiro.png'/>".
            "               <h1 class='goodText' style='color:#474C58;text-align:center;font-size: 20px;font-weight: bold;'>Hola ".strtolower($email)."</h1>".
            "               <p class='goodText' style='font-size: 18px;color: #474C58;text-align:center;margin-bottom:30px;margin-left:20px;margin-right:20px;'>Para completar el retiro de fondos ingrese el c&oacute;digo a continuaci&oacute;n:</p>".
            "               <div style='margin: auto; display: block;background-color: #4287CE;border-radius: 8px;width: 200px; height: 57px;text-align:center;'>".
            "                   <p style='margin: auto; display: block;color: #FFF;font-size: 18px;text-align:center;line-height: 58px;font-weight:bold;letter-spacing: 10px;'>".$validator."</p>".
            "               </div>".
            "               <p class='goodText' style='text-align:center;font-size:12px;color: #474C58;'>Este c&oacute;digo expirar&aacute; en 10 minutos.</p>".
            "           </div>".
            "           <p class='copy' style='margin-top:40px; color: #767E93;text-align:center;'>&copy; 2020 - AFX Trade</p>".
            "       </div>".
            "   </body>".
            "</html>";
            
    enviarCorreo($fromeMail, strtolower($email), $subject, $body);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>