<?php
// app/api/deposits/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","paymentdate","amount","paymentaccountid","paymentref");
    if (!parametrosValidos($_POST, $parmsob)){
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(",", $parmsob)));
    }
    
    $paymentfile = $_FILES["paymentfile"];
    
    if($paymentfile["name"] == null){
        badEnd("400", array("msg"=>"Parametros obligatorios paymentfile"));
    }
    
    //Definicion de variables e inicializacion
    $out = new stdClass();
    $sessionid = $_POST["sessionid"];
    $accountid = $_POST["accountid"];
    $paymentdate = $_POST["paymentdate"];
    $amount = $_POST["amount"];
    $paymentaccountid = $_POST["paymentaccountid"];
    $paymentref = $_POST["paymentref"];
    
    //Validamos la session
    $idUserSession = isSessionValid($db, $sessionid);
    
    //Validamos el si el usuario puede hacer operaciones
    isLevelValid($db, $idUserSession);
    
    // Obtenemos el lenguaje del usuario
    $lang = updateLang($db,$sessionid);
    
    //Obtenemos la moneda en la cual se hace el deposito
    $sql = "SELECT * from accounts WHERE id = ".$accountid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db).$sql));
    
    //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 datos de la moneda
    $sql = "SELECT * FROM currencies WHERE id = ".$accountdata['currencyid'];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db).$sql));
    
    //Guardamos la data de la cuenta
    $currencydata = $rs->fetch_assoc();
    
    $sql = "SELECT * FROM accounts WHERE userid = -1".
    "       AND currencyid = ".$accountdata['currencyid'].
    "       AND paymentmethodid = -3";
    if (!$res=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db).$sql));
    
    $afxdata = $res->fetch_assoc();
    
    $amount = (float)number_format($amount, $currencydata['decimals'], '.', '');
    
    //Validamos los de las transferencia para validar que no exista la misma ref
    // en EL MISMO DIA
    $sql = "SELECT COUNT(paymentref) AS qty FROM deposits ".
    "       WHERE paymentref = '".$paymentref."' ".
    "       AND rejected IS NULL ".
    "       AND paymentaccountid = ".$paymentaccountid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>determinateDBError($db).$sql));
        
    $depositdata = $rs->fetch_assoc();
    
    if($depositdata['qty'] > 0){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Depósito duplicado",
            "eng"=>"Duplicate deposit"), $lang, "Depósito duplicado")));
    }
    
    //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).$sql));
    
    //Guardamos la data de la cuenta
    $userdata = $rs->fetch_assoc();
    
    $level = 1;
    
    if($userdata["level"] == 0){
        $level = 1;
    }else{
        $level = $userdata["level"];
    }
    
    //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).$sql));
    
    //Guardamos la data de la cuenta
    $fee = $rs->fetch_assoc();
    
    //Validamos que el monto sea mas que el minimo aceptado
    if(validateMin($accountdata["currencyid"], $userdata["type"], 1, $db, $amount)){
        badEnd("403", array("msg"=>determinateMsgFail(array(
            "esp"=>"Monto mínimo autorizado: ".numberFormatt($fee['mindeposit'], $currencydata['decimals']),
            "eng"=>"Minimum authorized amount: ".numberFormatt($fee['mindeposit'], $currencydata['decimals'])), $lang, "Monto mínimo autorizado: ".numberFormatt($fee['mindeposit'], $currencydata['decimals']))));
    }
    
    //Calculamos el monto real quitandole la comision
    if($fee["pctfeedeposits"] != null || $fee["nmlfeedeposits"] != null ){
        if($fee["pctfeedeposits"] == 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 = ".$idUserSession.
            "       AND preffeesfield = 'nmlfeedeposits'";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db).$sql));
            
            $userExg = $res->fetch_assoc();
            
            $realfee = number_format($amount - ($amount - ($fee["nmlfeedeposits"] - ($fee["nmlfeedeposits"]/100 * $userExg['exonerated']) )), $currencydata['decimals'], '.', '');
            
            $realamount = number_format($amount - $realfee, $currencydata['decimals'], '.', '');
            
            if($realfee >= $realamount){
                badEnd("403", array("msg"=>determinateMsgFail(array(
                    "esp"=>"Monto es menor a comisión",
                    "eng"=>"Amount is less than commission"), $lang, "Monto es menor a comisión")));
            }
            
        }else{
            
            $sql = "SELECT IF(exonerated IS NULL, 0, exonerated) AS exonerated FROM userportfolioprefs ".
            "       WHERE currencyid = ".$accountdata["currencyid"].
            "       AND userid = ".$idUserSession.
            "       AND preffeesfield = 'pctfeedeposits'";
            if (!$res=$db->query($sql))
                badEnd("500", array("msg"=>determinateDBError($db).$sql));
            
            $userExg = $res->fetch_assoc();
            
            $realfee = number_format((($fee["pctfeedeposits"] - ($fee["pctfeedeposits"]/100 * $userExg['exonerated']) )*$amount)/100, $currencydata['decimals'], '.', '');
            $realamount = number_format($amount - $realfee, $currencydata['decimals'], '.', '');
        }
    }else{
        $realfee = 0;
        $realamount = number_format($amount - $realfee, $currencydata['decimals'], '.', '');
    }
    
    //Consultamos los datos maximos
    $sql = "SELECT cmspreffees.* ".
    "       FROM cmspreffees, users, accounts ".
    "       WHERE cmspreffees.levelid = users.level ".
    "       AND cmspreffees.usertype = users.type ".
    "       AND users.id = ".$idUserSession.
    "       AND accounts.userid = users.id ".
    "       AND accounts.id = ".$accountid.
    "       AND accounts.currencyid = cmspreffees.currencyid";
    if (!$rs = $db->query($sql)){
        badEnd("500", array("msg"=>$db->error.$sql));
    }
    
    $rowPref = $rs->fetch_assoc();
    
    //Validamos primero el monto de las operaciones
    $sql = "SELECT SUM(deposits.amount) AS qty ".
    "       FROM deposits, transactions t, accounts, users ".
    "       WHERE t.id = deposits.transactionid ".
    "       AND t.accountid = accounts.id ".
    "       AND accounts.userid = users.id ".
    "       AND accounts.id = ".$accountid.
    "       AND (deposits.valid IS NOT NULL ".
    "       OR deposits.valid IS NULL) ".
    "       AND deposits.rejected IS NULL".
    "       AND MONTH(t.datecreated) = MONTH(NOW())".
    "       AND YEAR(t.datecreated) = YEAR(NOW())";
    if (!$res = $db->query($sql)){
        badEnd("500", array("msg"=>$db->error));
    }
    
    $movementData = $res->fetch_assoc();
    
    //Validamos si el monto total + monto operacion actual no excede el limite
    if((abs($movementData["qty"]) + $amount) >= $rowPref["maxamountmonthlyopdeposits"]){
        // Obtenemos la moneda de la cuenta
        $sql = "SELECT currencies.symbol AS symbol, currencies.decimals AS decimals ".
        "       FROM currencies, accounts".
        "       WHERE accounts.id = ".$accountid.
        "       AND accounts.currencyid = currencies.id";
        if (!$res = $db->query($sql)){
            badEnd("500", array("msg"=>determinateDBError($db)));
        }
    
        $currdata = $res->fetch_assoc();
    
        createAlert($db, 2, $idUserSession, 'Depósito, '.$currdata['symbol']." ".numberFormatt($amount, $currdata['decimals']));
    }
    
    //validateOperations($db, $accountid, $userdata["id"], $amount, 1);
    
    $db->autocommit(FALSE);
        
    //insertamos la trasaccion del deposito
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amount, ".
    "       amountghost, ".
    "       accountid, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Depósito', ".
    "       0, ".
    "       ".$amount.", ".
    "       ".$accountid.", ".
    "       NULL, ".
    "       NULL, ".
    "       NULL, ".
    "       ".$paymentaccountid.
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db).$sql;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //Guardamos el id de la transaccion de deposito
    $txid = (int)$db->insert_id;
    $out->id = $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).$sql;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //insertamos la comision del deposito
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amount, ".
    "       amountghost, ".
    "       accountid, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Comisión de Depósito', ".
    "       0, ".
    "       -".$realfee.", ".
    "       ".$accountid.", ".
    "       NULL, ".
    "       ".$txid.", ".
    "       NULL, ".
    "       ".$paymentaccountid.
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db).$sql;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //insertamos la comision del deposito
    $sql = "INSERT INTO transactions".
    "       (".
    "       datecreated, ".
    "       dsc, ".
    "       amount, ".
    "       amountghost, ".
    "       accountid, ".
    "       orderid, ".
    "       txid, ".
    "       accountorigin, ".
    "       accountdestination".
    "       )".
    "       VALUES(".
    "       NOW(), ".
    "       'Comisión de Depósito', ".
    "       0, ".
    "       ".$realfee.", ".
    "       ".$afxdata['id'].", ".
    "       NULL, ".
    "       ".$txid.", ".
    "       NULL, ".
    "       ".$paymentaccountid.
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db).$sql;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error, 'a'=>$afxdata));
    }
    
    //Obtenemos la extension de la imagen
    $ext = pathinfo($paymentfile['name'], PATHINFO_EXTENSION);
    
    //insertamos la comision del deposito
    $sql = "INSERT INTO deposits".
    "       (".
    "       paymentref, ".
    "       paymentaccountid, ".
    "       filetype, ".
    "       paymentdate, ".
    "       createddate, ".
    "       fee, ".
    "       transactionid, ".
    "       valid, ".
    "       amount ".
    "       )".
    "       VALUES(".
    "       '".$paymentref."', ".
    "       ".$paymentaccountid.", ".
    "       '".$paymentfile["type"]."', ".
    "       '".$paymentdate."', ".
    "       NOW(), ".
    "       ".$realfee.", ".
    "       ".$txid.", ".
    "       NULL, ".
    "       ".$amount." ".
    "       )";
    if (!$db->query($sql)){
        $error = determinateDBError($db).$sql;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //Creamos la direccion del folder
    $urlfolder = "../../../uploads/payments";
        
    //Movemos el FILE del directorio temporal al del sistema para su uso 
    if(!move_uploaded_file($paymentfile["tmp_name"], $urlfolder . "/" . $txid . "." . $ext)){
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>determinateMsgFail(array(
            "esp"=>"Error guardando la imagen",
            "eng"=>"Error saving image"), $lang, "Error guardando la imagen")));
    }
    // Y le agregamos la marca de agua
    $file = "uploads/payments/" . $txid . "." . $ext;
    $zona = new DateTimeZone('America/Caracas'); 
    $fecha = microtime(true)+$zona->getOffset(new DateTime());
    $dateW = date("d/m/Y",$fecha)." - ".date("h:i:s a",$fecha);
    $watermark = $dateW. " ".$weblink." #".$txid;
    $save = $urlfolder . "/" . $txid . "." . $ext;
    addTextWatermark($file,$watermark,$save, "../../../");

    // Obtenemos el nombre del usuario
    $sql = "SELECT users.usr AS email, 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).$sql));
        
    $userdataaudit = $res->fetch_assoc();
        
    $ipaddress = getRealIP();
    //auditoria
    setAudit($db, "OPERACIONES", $sessionid, "APP", "Se registró un depósito por ".$amount." (".$out->id.") en ".$currencydata['name'].", del usuario ".$userdataaudit['name'], $ipaddress);
    
    $db->commit();
    $db->close();
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die();
?>
