<?php
require("config.php");
require("includes/debug.php");
require("includes/functions.php");
require("includes/logincheck.php");
require("includes/settings.php");
require("includes/cspuseroptions.php");

$pf_pm = unserialize($_SESSION["_profiles_pm"]);
$opc_log = unserialize($_SESSION["_opcoes_log"]);
if (is_null($opc_log)) {
    $opc_log = array();
}

$qtd_logins_perfis = $_SESSION['_qtd_logins_perfis'];
$saldo_revenda = saldo_revenda($_SESSION['adminid'], $perfil);

//var_dump($_SESSION);
$adduserstatus = "";
$username = "";
$password = "";
$displayname = "";
$email = "";
$comment = "";
$usrgroup = "";
$ipmask = "";
$profiles = "";
$maxconnections = "";
$admin = "";
$enabled = "";
$mapexclude = "";
$debug = "";
$customvalues = "";
$ecmrate = "";
$startdate = "";
$expiredate = "";

$conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
mysql_select_db($dbname, $conn);

$sql = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");

$line = mysql_fetch_array($sql);

$autoloaddef = $line["autoloaddef"];
$hidehelp = $line["hidehelp"];
if ($autoloaddef == "1") {
    $adduserstatus = "11";
    $username = "";
    $password = "1234";
    $displayname = "";
    $email = "";
    $comment = "";
    $usrgroup = "";
    $startdate = "";
    $expiredate = "";
    $ipmask = $line["def_ipmask"];
    $profiles = $line["def_profiles"];
    $maxconnections = $line["def_maxconnections"];
    $admin = $line["def_admin"];
    $enabled = $line["def_enabled"];
    $mapexclude = $line["def_mapexclude"];
    $debug = $line["def_debug"];
    $customvalues = $line["def_customvalues"];
    $ecmrate = $line["def_ecmrate"];
}
mysql_close($conn);

$conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
mysql_select_db($dbname, $conn);

$sql = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");
$line = mysql_fetch_array($sql);


mysql_close($conn);

if (isset($_POST["badduser"]) and $_POST["badduser"] == "Add user") {

    if (!isset($_POST["profiles"])) {

        $profiles = "";
    } else {

        $profiles = $_POST["profiles"];
        $maxconnections = (is_numeric($_POST["maxconnections"]) && $_POST["maxconnections"] > 0) ? $_POST["maxconnections"] : 1;


        // saldo revenda pre paga
        if ($_SESSION['rev_pre'] == '1') {

            $_saldo_revenda = saldo_revenda_pre($_SESSION['adminid']);
            $saldo_revenda = $_saldo_revenda[$_SESSION['adminid']];

            $valor_base_pre = valor_base_pre($_POST['expiredate']);
            
            //var_dump($saldo_revenda);exit();
            
            // |??? testa valor zerado ??? 
            if ($saldo_revenda['saldo_real'] < ($valor_base_pre * $maxconnections)) {

                $adduserstatus = 9;
                
            }

            // saldo revenda pos     
        } else {

            $qtd_logins_atual = saldo_revenda2($_SESSION['adminid']);
            $valor_base = 0;

            if ($qtd_logins_atual <= $valor_base) {

                $adduserstatus = 8;
            }
        }
    }

    $login = $_SESSION['_indt_rev'] . $_POST["username"]; // Cadastrar login com prefixo

    $_POST["startdate"] = date('Y-m-d');

    //salvando no banco de dados
    if ($adduserstatus == "") {

        list($adduserstatus, $id_inserido) = adduser($login, $_POST["password"], $_POST["displayname"], $_POST["ipmask"], $profiles, $_POST["maxconnections"], $_POST["admin"], $_POST["enabled"], $_POST["mapexclude"], $_POST["debug"], $_POST["email"], $_POST['dd'], $_POST['telefone'], $_POST['dd_cel'], $_POST['celular'], $_POST["comment"], $_POST["usrgroup"], $_POST["customvalues"], $_POST["ecmrate"], $_POST["startdate"], $_POST["expiredate"], $_POST['obs_user'], $_POST['valor_cob']);
    }

    if ($adduserstatus != "0") {

        $username = $_POST["username"];
        $password = $_POST["password"];
        $displayname = $_POST["displayname"];
        $ipmask = $_POST["ipmask"];
        $maxconnections = $_POST["maxconnections"];
        $admin = strtolower($_POST["admin"]);
        $enabled = strtolower($_POST["enabled"]);
        $mapexclude = strtolower($_POST["mapexclude"]);
        $debug = strtolower($_POST["debug"]);
        $email = $_POST["email"];
        $comment = $_POST["comment"];
        $usrgroup = $_POST["usrgroup"];
        $customvalues = replacechars($_POST["customvalues"]);
        $ecmrate = $_POST["ecmrate"];
        $startdate = $_POST["startdate"];
        $expiredate = $_POST["expiredate"];

        if (!isset($_POST["profiles"])) {

            $profiles = "N;";
        } else {

            $profiles = serialize($_POST["profiles"]);
        }
    }

    if ($adduserstatus == "0") {


        // debitando da cota pre paga

        if ($_SESSION['rev_pre'] == '1' && $_SESSION['adminlevel'] == '1') {

            atualiza_cota_pre($_SESSION['adminid'], 0, ($valor_base_pre * $maxconnections));
        }


        if (isset($_POST['enviar_email'])) {

            $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
            mysql_select_db($dbname, $conn);

            $dados['modelo_email'] = 's:' . $_SESSION['_modelo_padrao_sistema'];

            //Verifica se tem modelo proprio definido.
            if (is_numeric($_SESSION['_modelo_padrao_rev']) && $_SESSION['_modelo_padrao_rev'] > 0) {
                $dados['modelo_email'] = 'r:' . $_SESSION['_modelo_padrao_rev'];
            }

            $dados['emails'][] = $_POST["email"];
            $dados['ids'][] = $id_inserido;
            $dados['aids'][] = $_SESSION['adminid'];

            $p = urlencode(base64_url_encode(json_encode($dados)));

            //Enviando
            $script = "<script>"
                    . "var janela = window.open('enviaremail.php?p={$p}','Enviando Email','width=400,height=350');"
                    . "window.self.location = 'manusers.php?action=add&user={$_POST["username"]}';"
                    . "</script>";
            echo $script;
        } else {

            header("Location: manusers.php?action=add&user={$_POST["username"]}");
        }

        exit();
    }
}
if (isset($_POST["badduser"]) and $_POST["badduser"] == "add_permanecer") {

    if (!isset($_POST["profiles"])) {

        $profiles = "";
    } else {

        $profiles = $_POST["profiles"];
        $maxconnections = (is_numeric($_POST["maxconnections"]) && $_POST["maxconnections"] > 0) ? $_POST["maxconnections"] : 1;

        // saldo revenda pre paga
        if ($_SESSION['rev_pre'] == '1') {

            $_saldo_revenda = saldo_revenda_pre($_SESSION['adminid']);
            $saldo_revenda = $_saldo_revenda[$_SESSION['adminid']];

            $valor_base_pre = valor_base_pre($_POST['expiredate']);

            // |??? testa valor zerado ??? 
            if ($saldo_revenda['saldo_real'] < ($valor_base_pre * $maxconnections)) {

                $adduserstatus = 9;
            }

            // saldo revenda pos     
        } else {

            $qtd_logins_atual = saldo_revenda2($_SESSION['adminid']);
            $valor_base = 0;

            if ($qtd_logins_atual <= $valor_base) {

                $adduserstatus = 8;
            }
        }
    }

    $login = $_SESSION['_indt_rev'] . $_POST["username"]; // Cadastrar login com prefixo

    $_POST["startdate"] = date('Y-m-d');

    if ($adduserstatus == "") {

        list($adduserstatus, $id_inserido) = adduser($login, $_POST["password"], $_POST["displayname"], $_POST["ipmask"], $profiles, $_POST["maxconnections"], $_POST["admin"], $_POST["enabled"], $_POST["mapexclude"], $_POST["debug"], $_POST["email"], $_POST['dd'], $_POST['telefone'], $_POST['dd_cel'], $_POST['celular'], $_POST["comment"], $_POST["usrgroup"], $_POST["customvalues"], $_POST["ecmrate"], $_POST["startdate"], $_POST["expiredate"], $_POST['obs_user'], $_POST['valor_cob']);
    }

    if ($adduserstatus != "0") {

        $username = $_POST["username"];
        $password = $_POST["password"];
        $displayname = $_POST["displayname"];
        $ipmask = $_POST["ipmask"];
        $maxconnections = $_POST["maxconnections"];
        $admin = strtolower($_POST["admin"]);
        $enabled = strtolower($_POST["enabled"]);
        $mapexclude = strtolower($_POST["mapexclude"]);
        $debug = strtolower($_POST["debug"]);
        $email = $_POST["email"];
        $comment = $_POST["comment"];
        $usrgroup = $_POST["usrgroup"];
        $customvalues = replacechars($_POST["customvalues"]);
        $ecmrate = $_POST["ecmrate"];
        $startdate = $_POST["startdate"];
        $expiredate = $_POST["expiredate"];

        if (!isset($_POST["profiles"])) {

            $profiles = "N;";
        } else {

            $profiles = serialize($_POST["profiles"]);
        }
    }

    if ($adduserstatus == "0") {

        // debitando da cota pre paga

        if ($_SESSION['rev_pre'] == '1' && $_SESSION['adminlevel'] == '1') {

            atualiza_cota_pre($_SESSION['adminid'], 0, ($valor_base_pre * $maxconnections));
        }

        if (isset($_POST['enviar_email'])) {

            $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
            mysql_select_db($dbname, $conn);

            $dados['modelo_email'] = 's:' . $_SESSION['_modelo_padrao_sistema'];

            //Verifica se tem modelo proprio definido.
            if (is_numeric($_SESSION['_modelo_padrao_rev']) && $_SESSION['_modelo_padrao_rev'] > 0) {
                $dados['modelo_email'] = 'r:' . $_SESSION['_modelo_padrao_rev'];
            }

            $dados['emails'][] = $_POST["email"];
            $dados['ids'][] = $id_inserido;
            $dados['aids'][] = $_SESSION['adminid'];
            $p = urlencode(base64_url_encode(json_encode($dados)));

            //Enviando
            $script = "<script>"
                    . "var janela = window.open('enviaremail.php?p={$p}','Enviando Email','width=400,height=350');"
                    . "window.self.location = 'adduser.php?action=add&user={$_POST["username"]}';"
                    . "</script>";
            echo $script;
        } else {
            header("Location: adduser.php?action=add&user={$_POST["username"]}");
        }

        exit();
    }
}
//add_permanecer

if (isset($_POST["badduser"]) and $_POST["badduser"] == "Add user and stay") {
    if (!isset($_POST["profiles"])) {
        $profiles = "";
    } else {
        $profiles = $_POST["profiles"];
    }
    $_POST["startdate"] = date('Y-m-d');
    //exit($_POST["startdate"]);
    $adduserstatus = adduser($_POST["username"], $_POST["password"], $_POST["displayname"], $_POST["ipmask"], $profiles, $_POST["maxconnections"], $_POST["admin"], $_POST["enabled"], $_POST["mapexclude"], $_POST["debug"], $_POST["email"], $_POST["comment"], $_POST["usrgroup"], $_POST["customvalues"], $_POST["ecmrate"], $_POST["startdate"], $_POST["expiredate"]);

    if ($adduserstatus == "1" or $adduserstatus == "2") {
        $username = $_POST["username"];
        $password = $_POST["password"];
        $displayname = $_POST["displayname"];
        $ipmask = $_POST["ipmask"];
        $maxconnections = $_POST["maxconnections"];
        $admin = strtolower($_POST["admin"]);
        $enabled = strtolower($_POST["enabled"]);
        $mapexclude = strtolower($_POST["mapexclude"]);
        $debug = strtolower($_POST["debug"]);
        $email = $_POST["email"];
        $comment = $_POST["comment"];
        $usrgroup = $_POST["usrgroup"];
        $customvalues = replacechars($_POST["customvalues"]);
        $ecmrate = $_POST["ecmrate"];
        $startdate = $_POST["startdate"];
        $expiredate = $_POST["expiredate"];
        if (!isset($_POST["profiles"])) {
            $profiles = "N;";
        } else {
            $profiles = serialize($_POST["profiles"]);
        }
    }
    if ($adduserstatus == "0") {
        $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
        mysql_select_db($dbname, $conn);
        $sql = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");
        $line = mysql_fetch_array($sql);
        $autoloaddef = $line["autoloaddef"];
        if ($autoloaddef == "1") {
            $adduserstatus = "12";
            $username = "";
            $password = "";
            $displayname = "";
            $email = "";
            $comment = "";
            $usrgroup = "";
            $startdate = "";
            $expiredate = "";
            $ipmask = $line["def_ipmask"];
            $profiles = $line["def_profiles"];
            $maxconnections = $line["def_maxconnections"];
            $admin = $line["def_admin"];
            $enabled = $line["def_enabled"];
            $mapexclude = $line["def_mapexclude"];
            $debug = $line["def_debug"];
            $customvalues = $line["def_customvalues"];
            $ecmrate = $line["def_ecmrate"];
        }
        mysql_close($conn);
    }
}

/* if (isset($_POST["badduser"]) and $_POST["badduser"] == "Random username") {
  $adduserstatus = "10";
  if (!isset($_POST["profiles"])) {
  $profiles = "N;";
  } else {
  $profiles = serialize($_POST["profiles"]);
  }
  $password = trim(stripslashes($_POST["password"]));
  $displayname = trim($_POST["displayname"]);
  $ipmask = trim($_POST["ipmask"]);
  $maxconnections = trim($_POST["maxconnections"]);
  $admin = strtolower($_POST["admin"]);
  $enabled = strtolower($_POST["enabled"]);
  $mapexclude = strtolower($_POST["mapexclude"]);
  $debug = strtolower($_POST["debug"]);
  $email = trim($_POST["email"]);
  $comment = $_POST["comment"];
  $usrgroup = $_POST["usrgroup"];
  $customvalues = replacechars($_POST["customvalues"]);
  $ecmrate = $_POST["ecmrate"];
  $startdate = $_POST["startdate"];
  $expiredate = $_POST["expiredate"];
  $username = randomstring();
  }
  if (isset($_POST["badduser"]) and $_POST["badduser"] == "Random password") {
  $adduserstatus = "10";
  if (!isset($_POST["profiles"])) {
  $profiles = "N;";
  } else {
  $profiles = serialize($_POST["profiles"]);
  }
  $username = trim(stripslashes($_POST["username"]));
  $displayname = trim($_POST["displayname"]);
  $ipmask = trim($_POST["ipmask"]);
  $maxconnections = trim($_POST["maxconnections"]);
  $admin = strtolower($_POST["admin"]);
  $enabled = strtolower($_POST["enabled"]);
  $mapexclude = strtolower($_POST["mapexclude"]);
  $debug = strtolower($_POST["debug"]);
  $email = trim($_POST["email"]);
  $comment = $_POST["comment"];
  $usrgroup = $_POST["usrgroup"];
  $customvalues = replacechars($_POST["customvalues"]);
  $ecmrate = $_POST["ecmrate"];
  $startdate = $_POST["startdate"];
  $expiredate = $_POST["expiredate"];
  $password = randomstring();
  }
  if (isset($_POST["badduser"]) and $_POST["badduser"] == "Random username & password") {
  $adduserstatus = "10";
  if (!isset($_POST["profiles"])) {
  $profiles = "N;";
  } else {
  $profiles = serialize($_POST["profiles"]);
  }
  $displayname = trim($_POST["displayname"]);
  $ipmask = trim($_POST["ipmask"]);
  $maxconnections = trim($_POST["maxconnections"]);
  $admin = strtolower($_POST["admin"]);
  $enabled = strtolower($_POST["enabled"]);
  $mapexclude = strtolower($_POST["mapexclude"]);
  $debug = strtolower($_POST["debug"]);
  $email = trim($_POST["email"]);
  $comment = $_POST["comment"];
  $usrgroup = $_POST["usrgroup"];
  $customvalues = replacechars($_POST["customvalues"]);
  $ecmrate = $_POST["ecmrate"];
  $startdate = $_POST["startdate"];
  $expiredate = $_POST["expiredate"];
  $username = randomstring();
  $password = randomstring();
  }


  /*if (isset($_POST["badduser"]) and $_POST["badduser"] == "Load defaults") {
  $adduserstatus = "11";
  $username = trim(stripslashes($_POST["username"]));
  $password = trim($_POST["password"]);
  $displayname = trim($_POST["displayname"]);
  $email = trim($_POST["email"]);
  $comment = $_POST["comment"];
  $usrgroup = $_POST["usrgroup"];
  $startdate = $_POST["startdate"];
  $expiredate = $_POST["expiredate"];
  $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
  mysql_select_db($dbname, $conn);
  $sql = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");
  $line = mysql_fetch_array($sql);
  $ipmask = $line["def_ipmask"];
  $profiles = $line["def_profiles"];
  $maxconnections = $line["def_maxconnections"];
  $admin = $line["def_admin"];
  $enabled = $line["def_enabled"];
  $mapexclude = $line["def_mapexclude"];
  $debug = $line["def_debug"];
  $customvalues = $line["def_customvalues"];
  $ecmrate = $line["def_ecmrate"];
  mysql_close($conn);
  }

  if (isset($_POST["badduser"]) and $_POST["badduser"] == "Clear fields") {
  $adduserstatus = "";
  $username = "";
  $password = "";
  $displayname = "";
  $ipmask = "";
  $maxconnections = "";
  $admin = "";
  $enabled = "";
  $mapexclude = "";
  $debug = "";
  $profiles = "";
  $email = "";
  $comment = "";
  $usrgroup = "";
  $customvalues = "";
  $ecmrate = "";
  $startdate = "";
  $expiredate = "";
  } */
if (isset($_POST["badduser"]) and $_POST["badduser"] == "Sair") {
    header("Location: manusers.php");
}
if (isset($_GET["action"]) and $_GET["action"] == "add" and $_GET["user"] <> "") {
    $status = "<div class='alert alert-success'>** Usuário " . $_GET["user"] . " Adicionado com Sucesso.";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta http-equiv="Content-Type" content="text/html; charset=<?php print($charset); ?>" />
            <title><?php print($longtitle); ?></title>
            <link rel="shortcut icon" href="favicon.ico"/>
            <link rel="apple-touch-icon" href="favicon.png"/>            
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
            <link rel="stylesheet" href="/resources/demos/style.css" />
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
                <link href="css/main.css" rel="stylesheet" type="text/css"/>
                <style>
                    table{
                        font-size: 12pt;
                    }
                </style>
                <script>
                    $(function () {
                        $("#expiredate").datepicker({
                            dateFormat: "dd/mm/yy 23:59:59"
                                    /*showOn: "button",
                                     buttonImage: "images/calendar/calendar.gif",
                                     buttonImageOnly: true*/
                        });
                    });
                </script>
                <!--<link href="css/calendar.css" type="text/css" media="screen" rel="stylesheet">
                <script type="text/javascript" src="js/mootools-core.js"></script>
                <script type="text/javascript" src="js/mootools-more.js"></script>
                <script type="text/javascript" src="js/mootools-locale.js"></script>
                <script type="text/javascript" src="js/calendar.js"></script>
                <script type="text/javascript">
                window.addEvent('domready', function() {
                //new CalendarEightysix('startdate', { prefill: false, startMonday: true, toggler: 'togglestart', format: '%Y-%m-%d', hiddenInputName: 'stdate' });
                new CalendarEightysix('expiredate', { 
                    prefill: false, 
                    startMonday: true, 
                    toggler: 'toggleexpire', 
                    format: '%Y-%m-%d <?php echo date('H:i:s'); ?>', 
                    hiddenInputName: 'exdate' });
                });
                </script>-->
                <script type="text/javascript">
                    //checked=false;
                    function checkedAll(obj) {
                        var check = obj.checked;
                        var el = document.getElementsByName('profiles[]');
                        el.length;
                        for (var i = 0; i < el.length; i++) {
                            el[i].checked = check;
                        }
                    }
                </script>
                <script language="JavaScript">
                    function onlyNumbers(evt)
                    {
                        var e = event || evt; // for trans-browser compatibility
                        var charCode = e.which || e.keyCode;
                        if (charCode > 31 && (charCode < 48 || charCode > 57))
                            return false;
                        return true;
                    }
                </script>
                <script>
                    function usTeste(obj) {
                        var cond = obj.checked;
<?php
$d = date('Y-m-d');
$amanha = date('d/m/Y H:i:s', strtotime("+24 hours"));
//pegando config user teste
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$rs = $db->query("SELECT tempo_login_teste FROM cmum_settings ORDER BY id DESC LIMIT 1");
$config = $rs->fetch_assoc();
$db->close();

if (isset($config["tempo_login_teste"])) {
    $amanha = date('d/m/Y H:i:s', strtotime("+{$config["tempo_login_teste"]} hours"));
}

echo "var data = '{$amanha}';\n";
?>
                        if (cond == true) {
                            document.getElementById('expiredate').value = data;
                            document.getElementById('expiredate').readOnly = true;
                            document.getElementById('toggleexpire').setAttribute('style', 'display: none; visibility: hidden;');

                        } else {
                            document.getElementById('expiredate').value = '';
                            document.getElementById('expiredate').readOnly = false;
                            document.getElementById('toggleexpire').setAttribute('style', 'display:; visibility: visible;');
                        }

                    }
                    $(document).on('input', '.numeros', function () {
                        var v = $(this).val().replace(/[^0-9.]/, "");
                        $(this).val(v);
                    });
                </script>
                </head>

                <body onLoad="focus();
                        adduser.username.focus()">

<?php require_once 'topo.php'; ?>

                    <table width="980" height="20" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="">
                        <tr  >
                            <td width="" style="border: solid 0px;">&nbsp;</td>
<?php
require("includes/addusrtwocol.php");
?>
                            <td width="" style="border: solid 0px;">&nbsp;</td>
                        </tr>
                    </table>
                    <table width="980" height="20" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="">
                        <tr >
                            <td height="20" width="780">&nbsp;</td>
                        </tr>
                    </table>
<?php
$adduserstatus = "";
require("includes/footer.php");
?>
                    <!--</div>-->
                </body>
                </html>
