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

$_SESSION['url_referer'][] = $_SERVER['HTTP_REFERER'];

$pf_pm = unserialize($_SESSION["_profiles_pm"]);
$opc_log = unserialize($_SESSION["_opcoes_log"]);

if (is_null($opc_log)) {
    $opc_log = array();
}

if (isset($_POST["bedituser"]) and $_POST["bedituser"] == "Save") {

    // dados do login que está sendo editado

    $id_login = $_POST['uid'];

    $con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

    $rs = $con->query("SELECT * FROM cmum_udb WHERE id = '{$id_login}'");

    $login_edit = array();

    if ($rs->num_rows > 0) {

        $login_edit = $rs->fetch_assoc();
    }

    // pega os dados da revenda pai

    $rs = $con->query("SELECT * FROM cmum_admins WHERE id = '{$login_edit['addedby']}'");

    $revenda_pai = array();

    if ($rs->num_rows > 0) {

        $revenda_pai = $rs->fetch_assoc();
    }

    // verifica os erros
    $erro = array();

    if ($_POST['profiles'] == "") {

        $erro[1] = "O perfil nao foi preenchido.";
    }

    // erros vencimento vazio
    if ($_POST["expiredate"] == "") {

        $erro[2] = "O Vencimento nao foi preenchido.";

    // verifica se o vencimento foi alterado
    } else {

        if ($revenda_pai['rev_pre'] == '1') {
            
            $vencimento_atual = strtotime($login_edit['expiredate']);

            $vencimento_salvo = strtotime(str_replace("/", "-", $_POST["expiredate"]));
            
            $_saldo_revenda_pre = saldo_revenda_pre($revenda_pai['id']);
            
            $saldo_revenda_pre = $_saldo_revenda_pre[$revenda_pai['id']];
            
            
            // verifica se o vencimento passado é i maior do que já salvo
            if ($vencimento_salvo > $vencimento_atual) {

                $valor_base_pre = valor_base_pre($_POST["expiredate"]);                
                               
                if($saldo_revenda_pre['saldo_real'] < $valor_base_pre){
                    
                    $erro[21] = "Saldo Pre-Pago esgotado, você precisa adquirir um plano.";
                    
                }
                                
                
            }           
                        
        }
        
    }
    
    //erros do tamanho do login 
    if (strlen($_POST["username"]) < 2 || strlen($_POST["username"]) > 20) {

        $erro[3] = "Login deve ter entre 3 e 20 caracteres";
    }
     //erros senha
    if (strlen($_POST["password"]) < 2 || strlen($_POST["password"]) > 15) {

        $erro[4] = "Senha deve ter entre 2 e 15 caracteres";
    }
    if ($_POST['username'] == "" || $_POST['displayname'] == "" || $_POST['password'] == "") {

        $erro[5] = "Login, senha e nome são obrigatórios";
    }
    if (($_POST['telefone'] != "" && $_POST['dd'] == "") || ($_POST['celular'] != "" && $_POST['dd_cel'] == "")) {

        $erro[6] = "O Campo DD deve ser preenchido.";
    }

    // se não tive erros edita
    if (empty($erro)) {

        $login = $_POST["username"]; // Cadastrar login com prefixo
        $_POST["startdate"] = date('Y-m-d', strtotime(str_replace("/", "-", $_POST["startdate"])));
        $_POST["expiredate"] = date('Y-m-d 23:59:59', strtotime(str_replace("/", "-", $_POST["expiredate"])));

        @$status = edituser($_POST["uid"], $login, $_POST["password"], $_POST["displayname"], $_POST["ipmask"], $_POST['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']);
        
        
        // se for revenda pre paga atualiza a cota
        if($revenda_pai['rev_pre'] == '1'){
            
            atualiza_cota_pre($revenda_pai['id'], 0, $valor_base_pre);       
            
        }
        
        if ($status === true) {

            foreach ($_SESSION['url_referer'] as $url_ref_primeira) {

                header('Location: ' . $url_ref_primeira);
                exit();
            }
        }
    }
}

if (isset($_POST["bedituser"]) and $_POST["bedituser"] == "Change username") {

    $p = base64_encode("{\"id\":{$_POST["uid"]},\"aid\":{$_SESSION['adminid']}}");
    header("Location: editusername.php?p=" . $p);
}

if (isset($_GET["p"]) and $_GET["p"] <> "") {

    $params = json_decode(base64_decode($_GET["p"]), true);

    $uid = $params["id"];

    if ($_SESSION["adminlevel"] == 1) {

        $_arvore = arvoreRevendas2();
        $arvore = $_arvore[$adminid];
        $ids_rev_arvore = array();

        if (!is_null($arvore)) {
            listaIdsRenvendasSub($arvore, $ids_rev_arvore);
        }

        if (array_search($params["aid"], $ids_rev_arvore) === false && $params["aid"] != $_SESSION["adminid"]) {
            header("Location: manusers.php");
        }
    }
} else {

    header("Location: manusers.php");
}
?>
<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: 10pt;
                    }
                </style>
                <script>
                    $(function () {
                        $("#expiredate").datepicker({
                            dateFormat: "yy-mm-dd 23:59:59"
                                    /*showOn: "button",
                                     buttonImage: "images/calendar/calendar.gif",
                                     buttonImageOnly: true*/
                        });
                    });
                </script>

                <script language="JavaScript">
                    checked = false;
                    function checkedAll(edituser) {
                        var aa = document.getElementById('edituser');
                        if (checked == false)
                        {
                            checked = true
                        }
                        else
                        {
                            checked = false
                        }
                        for (var i = 0; i < aa.elements.length; i++)
                        {
                            aa.elements[i].checked = checked;
                        }
                    }
                </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;
                    }
                    $(document).on('input', '.numeros', function () {
                        var v = $(this).val().replace(/[^0-9.]/, "");
                        $(this).val(v);
                    });
                </script>
                </head>

                <body onLoad="focus();
                        edituser.username.focus()">
                <!--<table width="980" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="border-left: 1px solid #DDDDDD; border-right: 1px solid #DDDDDD; text-align: left;">
                  <tr bgcolor="#006699">
                    <td height="22" colspan="6">&nbsp;</td>
                  </tr>
                  <tr bgcolor="#006699">
                    <td width="15" bgcolor="#006699">&nbsp;</td>
                    <td width="751" height="120" bgcolor="#006699"><?php //require("includes/header.php");              ?></td>
                    <td width="15" bgcolor="#006699">&nbsp;</td>
                  </tr>
                  <tr bgcolor="#006699">
                    <td height="18">&nbsp;</td>
                    <td height="18"><center><?php //require("includes/menu.php");             ?></center></td>
                    <td height="18">&nbsp;</td>
                  </tr>
                    <tr bgcolor="#006699">
                    <td height="18">&nbsp;</td>
                    <td height="18">&nbsp;</td>
                    <td height="18">&nbsp;</td>
                  </tr>
                </table>-->
<?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/editusrtwocol.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" >
                        <tr >
                            <td height="25%" width="780">&nbsp;</td>
                        </tr>
                    </table>
<?php
require("includes/footer.php");
?>
                </body>
                </html>
