<?php
// app/api/deposits/insert

    header("Content-Type:application/json");
    include("../dbconn.php");
    include("../utils.php");
    
    // 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"=>$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 datos de la moneda
    $sql = "SELECT * FROM currencies WHERE id = ".$accountdata['currencyid'];
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    //Guardamos la data de la cuenta
    $currencydata = $rs->fetch_assoc();
    
    //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 paymentaccountid = ".$paymentaccountid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $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"=>$db->error));
    
    //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"=>$db->error));
    
    //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){
            $realfee = number_format($amount - ($amount - $fee["nmlfeedeposits"]), $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{
            $realfee = number_format(($fee["pctfeedeposits"]*$amount)/100, $currencydata['decimals'], '.', '');
            $realamount = number_format($amount - $realfee, $currencydata['decimals'], '.', '');
        }
    }else{
        $realfee = 0;
        $realamount = number_format($amount - $realfee, $currencydata['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 = $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 = $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 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 = $db->error;
        $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.", ".
    "       ".$paymentaccountid.", ".
    "       NULL, ".
    "       ".$txid.", ".
    "       NULL, ".
    "       ".$paymentaccountid.
    "       )";
    if (!$db->query($sql)){
        $error = $db->error;
        $db->rollback();
        $db->close();
        badEnd("500", array("msg"=>$error));
    }
    
    //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 = $db->error;
        $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")));
    }
    
    // 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 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();
?>
