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

// Verificando e limpando urls referencia

if (isset($_SESSION['url_referer'])) {
    unset($_SESSION['url_referer']);
}

$admId = $_SESSION["adminid"];
$level = $_SESSION["adminlevel"];
$id = "";

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

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

if (isset($_GET["p"])) {

    $param = json_decode(base64_decode($_GET["p"]), true);
    if (key_exists("id", $param)) {
        $admId = $param["id"];
    }
}
/* if (isset($_GET['filtro_rev'])) {
  $admId = $_GET['filtro_rev'];
  } */
if (isset($_GET['mod_opc'])) {

    $ids = implode(",", $_POST['_ids_sel']);
    $ip_mudanca = $_SERVER['REMOTE_ADDR'];

    

    if ($_POST['_opc'] == 1 && ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && (!empty($opc_log) && array_search('4', $opc_log) !== false)))) {

        $nova_data_venc = date('Y-m-d H:i:s', strtotime(str_replace("/", "-", $_POST['_nova_data'])));
        //$SQL = "UPDATE cmum_udb SET expiredate='{$nova_data_venc}',id_rev_mudou_status='{$admId}',ip_atualizacao='{$ip_mudanca}'";
        $SQL = "UPDATE cmum_udb SET expiredate='{$nova_data_venc}',ip_atualizacao='{$ip_mudanca}'";
    }
    if ($_POST['_opc'] == 5) {

        $valor_cob = $_POST['_novo_valor'];
        $SQL = "UPDATE cmum_udb SET valor_cob='{$valor_cob}',ip_atualizacao='{$ip_mudanca}'";
    }
    if ($_POST['_opc'] == 2 && ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && (!empty($opc_log) && array_search('5', $opc_log) !== false)))) {

        $SQL = "UPDATE cmum_udb SET enabled='true',id_rev_mudou_status='0',ip_atualizacao='{$ip_mudanca}'";
    }
    if ($_POST['_opc'] == 3 && ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && (!empty($opc_log) && array_search('5', $opc_log) !== false)))) {

        $SQL = "UPDATE cmum_udb SET enabled='false',id_rev_mudou_status='{$admId}',ip_atualizacao='{$ip_mudanca}'";
    }
    if ($_POST['_opc'] == 4 && ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && (!empty($opc_log) && array_search('6', $opc_log) !== false)))) {

        $SQL = "DELETE FROM cmum_udb";
    }
    if ($_POST['_opc'] == 6) {

        $param = json_decode(base64_decode($_POST['_novo_revenda']), true);
        /*
         * '_ids_sel[]': ids_sel,
          _opc: v_opc,
          _novo_revenda: $('#p :selected').val()
         * {"id":"371"}
         */
        
        // verifica se a revenda é pre paga.
        /*if(is_pre_paga($param['id'])){
            
            $ret['erro'] = "A nova revenda não deve ser pre paga.";
             exit(json_encode($ret));
            
        }*/
        
        
        $SQL = "UPDATE cmum_udb SET addedby='{$param['id']}',ip_atualizacao='{$ip_mudanca}'";
    }

    $SQL .= " WHERE id IN ({$ids})";

    $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    $rs = $conn->query($SQL);

    if ($rs === TRUE) {

        $ret['sucesso'] = "Ação executada com sucesso";
        echo json_encode($ret);
    }

    exit();
}

if (isset($_POST["bdel"]) and $_POST["bdel"] == "Sim") {

    $status = '<div class="alert alert-success">' . removeuser($_POST["uid"], $_POST["username"]) . '</div>';
}

if (isset($_GET["action"]) and $_GET["action"] == "add" and $_GET["user"] <> "") {

    $status = "<div class='alert alert-success'>** Usuário " . $_GET["user"] . " Adicionado com Sucesso.</div>";
}


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

$strSQL = "SELECT us.*,DATE_FORMAT(us.expiredate,'%d/%m/%Y <span style=\"font-size: 7pt\">%H:%i:%s</span>') as expiredate_br,DATEDIFF(us.expiredate,us.added) as teste_ver,DATEDIFF(us.expiredate,NOW()) as data_dif,ad.username FROM cmum_udb AS us 
           INNER JOIN cmum_admins AS ad
           ON us.addedby = ad.id WHERE 1=1";

if ($level == 1 && !isset($param["id"])) {
    // pegando da arvore 
    $arvore = arvoreRevendas2();
    $ids_em_arvore[] = $admId;
    listaIdsRenvendasSub($arvore[$admId], $ids_em_arvore);
    //var_dump($ids_em_arvore,$admId);
    $ids_em_arvore_str = implode(',', $ids_em_arvore);
    $strSQL .= " AND us.addedby IN({$ids_em_arvore_str})";
} elseif (isset($param["id"])) {
    $strSQL .= " AND us.addedby = {$admId}";
}

if (isset($_GET['listopt'])) {
    if ($_GET['listopt'] == 'ativo') {
        $strSQL .= " AND (us.enabled = 'true' AND us.expiredate > NOW() AND DATEDIFF(us.expiredate,us.added) > 2)";
    } elseif ($_GET['listopt'] == 'desativado') {
        $strSQL .= " AND (us.enabled = 'false')";
    } elseif ($_GET['listopt'] == 'teste') {
        $strSQL .= " AND (us.enabled = 'true' AND us.expiredate > NOW() AND DATEDIFF(us.expiredate,us.added) <= 2)";
    } elseif ($_GET['listopt'] == 'vencido') {
        $strSQL .= " AND us.expiredate < NOW() AND (us.enabled <> 'false')";
    }
}
if (isset($_GET["inptbusca"])) {
    $_GET["inptbusca"] = trim(addslashes($_GET["inptbusca"]));
    $strSQL .= " AND (us.name LIKE '%{$_GET["inptbusca"]}%' OR us.email LIKE '%{$_GET["inptbusca"]}%' OR us.displayname LIKE '%{$_GET["inptbusca"]}%' OR ad.username LIKE '%{$_GET["inptbusca"]}%')";
}
//Ordenaçãoes
if (isset($_GET['orderby'])) {
    if ($_GET['orderby'] == "id") {
        $strSQL .= " ORDER BY us.id";
    }
    if ($_GET['orderby'] == "status") {
        $strSQL .= " ORDER BY us.enabled";
    }
    if ($_GET['orderby'] == "nome") {
        $strSQL .= " ORDER BY us.displayname";
    }
    if ($_GET['orderby'] == "login") {
        $strSQL .= " ORDER BY us.name";
    }
    if ($_GET['orderby'] == "conexoes") {
        $strSQL .= " ORDER BY us.maxconnections";
    }
    if ($_GET['orderby'] == "dias_restante") {
        $strSQL .= " ORDER BY data_dif";
    }
    if ($_GET['orderby'] == "vencimento") {
        $strSQL .= " ORDER BY us.expiredate";
    }
    //$c = "";
    if (isset($_GET['class']) && $_GET['class'] == "a") {
        $strSQL .= " ASC";
    }
    if (isset($_GET['class']) && $_GET['class'] == "d") {
        $strSQL .= " DESC";
    }

    /* if (isset($_SESSION['order_by'])) {
      $ordem = explode(".", $_SESSION['order_by']);
      if ($ordem[0] == $_GET['orderby']) {
      if ($ordem[1] == "ASC") {
      $c = "DESC";
      }
      if ($ordem[1] == "DESC") {
      $c = "ASC";
      }
      }
      } */
    //$strSQL .= " {$_GET['class']}";
    //$_SESSION['order_by'] = "{$_GET['orderby']}.$c";
} else {
    $strSQL .= " ORDER BY us.name ASC";
}
//var_dump($_SESSION['order_by']);
//var_dump($c);



$resultP = mysql_query($strSQL) or sqlerror();
//------- Paginação -----------
$total_registros = mysql_num_rows($resultP);
$num_reg_pagina = 100;
$num_paginas = ceil($total_registros / $num_reg_pagina);
$pag = isset($_GET['pag']) ? $_GET['pag'] : 1;
$inicio = $num_reg_pagina * ($pag - 1);
//Limites
$strSQL .= " LIMIT {$inicio},{$num_reg_pagina}";
$resultP = mysql_query($strSQL) or sqlerror();
//------- Fim Paginação -----------





if (isset($_POST["bedituser"]) and $_POST["bedituser"] == "Change username") {
    header("Location: editusername.php?id=" . $_POST["uid"]);
}
?>
<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=UTF-8" />
            <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" />
            <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" />           
                <!--<link href="media/css/jquery.dataTables.css" rel="stylesheet" type="text/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>
                <script>
                    $(function () {
                        $("#nova_data_venc").datepicker({
                            dateFormat: "dd/mm/yy 23:59:59"
                                    /*showOn: "button",
                                     buttonImage: "images/calendar/calendar.gif",
                                     buttonImageOnly: true*/
                        });
                    });
                </script>
                <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>                
                </head>
                <body>                        
<?php require_once 'topo.php'; ?>
                    <!-- Status -->

                    <table width="1000px" height="20" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="" id="">
<?php
$conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname, $conn);
$sSQL = "SELECT id,addedby,username,level,realname FROM cmum_admins WHERE id = $admId";
$result = mysql_query($sSQL);

$revs = array();
while ($linha = mysql_fetch_array($result)) {
    $revs[$linha['id']] = array('id' => $linha['id'], 'parent' => $linha['addedby'], 'title' => $linha['username']);
    $revID = $linha['addedby'];
    $level = $linha['level'];
    while ($level > 0) {
        $sSQL = "SELECT id,addedby,username,level,realname FROM cmum_admins WHERE id=$revID";
        $result = mysql_query($sSQL);
        $linha = mysql_fetch_array($result);
        $revs[$linha['id']] = array('id' => $linha['id'], 'parent' => $linha['addedby'], 'title' => $linha['username']);
        $revID = $linha['addedby'];
        $level = $linha['level'];
    }
}

//var_dump($revs);
function breadcrumbs($id) {
    //global $revs;                               
    //$p = base64_encode("{\"id\":{$GLOBALS['revs'][$id]['id']}}");
    $json["id"] = "{$GLOBALS['revs'][$id]['id']}";
    $p = base64_encode(json_encode($json));
    if ($id >= $_SESSION['adminid']) {
        if ($GLOBALS['revs'][$id]['parent'] > 0) {
            return breadcrumbs($GLOBALS['revs'][$id]['parent']) . "<li><a href='?p=$p'>" . $GLOBALS['revs'][$id]['title'] . "</a></li>";
            //return breadcrumbs($GLOBALS['revs'][$id]['parent']) . " -> " . $GLOBALS['revs'][$id]['title'];
        } else {
            return "<li><a href='?p=$p'>" . $GLOBALS['revs'][$id]['title'] . '</a></li>';
            //return $GLOBALS['revs'][$id]['title'];
        }
    }
}
?>
                        <tr>
                            <td><div>Você está em:</div><ul class="breadcrumb" style="height: 50px; line-height: 30px; padding-left:5px;"><?php echo breadcrumbs($admId) ?></ul></td>
                        </tr>
                        <?php if (isset($status) && $status != ""): ?>
                            <tr>                    
                                <td ><?php echo $status; ?></td>                    
                            </tr>
<?php endif; ?>
                    </table>


                    <!--- Clientes --->
                    <div style="width: 1000px; border: solid 0px; margin: auto;  padding-top: 10px; padding-bottom: 20px; padding-left: 0px; padding-right: 0px">
                        <table border="0" style="width: 1000px;">
                            <tr>
                                <td>
                                    <div style="">
                                        <label style="font-size: 8pt">Com selecionados:</label>
                                        <form >
                                            <select class="form-control sel-opc-td-lg" disabled="true">
                                                <option value="0">--Selecionar Opção--</option>
<?php if ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && $_SESSION['rev_pre'] == '0' && (!empty($opc_log) && array_search('4', $opc_log) !== false))): ?>
                                                    <option value="1">Alterar Vencimento</option>
<?php endif; ?>
                                                <option value="5">Mudar Valor Cobrado</option>
<?php if ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && (!empty($opc_log) && array_search('5', $opc_log) !== false))): ?>
                                                    <option value="2">Ativar</option>
                                                    <option value="3">Desativar</option>
                                                <?php endif; ?>
                                                <?php if ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && (!empty($opc_log) && array_search('6', $opc_log) !== false))): ?>
                                                    <option value="4">Excluir</option>
                                                <?php endif; ?>   
                                                <?php if ($_SESSION['rev_pre'] == '0' || $_SESSION['adminlevel'] == "0"): ?>    
                                                    <option value="6">Mudar Revenda</option> 
                                                <?php endif; ?>
                                            </select> 
                                        </form>
                                    </div>
                                </td>
                                <td align="right">
                                    <label style="font-size: 8pt">Selecionar Logins de</label>

                                    <form name="formFiltro" id="formFiltro" method="" action="?filtro=revenda">
                                        <table>
                                            <tr>
                                                <td>                                                    
                                                    <select name='p' class='form-control' id="p" onchange="this.form.submit()">
<?php
$json["id"] = "{$_SESSION['adminid']}";
$p = base64_encode(json_encode($json));
?>
                                                        <option value="<?php echo $p ?>"><?php echo $_SESSION['loginuser'] ?></option>
<?php
$arvore = arvoreRevendas2();
$arvore_lista = arvoreRevendasLista();
listaOptionsRenvendas($arvore[$_SESSION['adminid']], $arvore_lista, isset($_GET['p']) ? $_GET['p'] : "", $_SESSION['_hierarquia']);
?>
                                                    </select> 
                                                </td>
                                                <td>
                                                    <input type="submit" value="Filtrar" name="" <?php if ($numReg == 0) { ?>disabled="true"<?php } ?> class="btn btn-default"/>
                                                </td>
                                            </tr>
                                        </table>
                                    </form>
                                </td>
                                <td align="right"><label style="font-size: 8pt">Opções</label>
                                    <form>
<?php if (isset($_GET["p"])): ?>
                                            <input type="hidden" name="p" value="<?php echo $_GET["p"] ?>"/>
<?php endif; ?>
<?php if (isset($_GET["inptbusca"])): ?>
                                            <input type="hidden" name="listopt" value="<?php echo $_GET["inptbusca"] ?>"/>
<?php endif; ?>
                                        <table border="0">
                                            <tr>
                                                <td><select name="listopt" class="form-control" onchange="this.form.submit();">                                                                                      
                                                        <option value="todos" <?php if (isset($_GET['listopt']) && $_GET["listopt"] == 'todos') { ?> selected="true"<?php } ?>>Todos</option>
                                                        <option value="ativo" <?php if (isset($_GET['listopt']) && $_GET["listopt"] == 'ativo') { ?> selected="true"<?php } ?>>Ativos</option>
                                                        <option value="desativado" <?php if (isset($_GET['listopt']) && $_GET["listopt"] == 'desativado') { ?> selected="true"<?php } ?>>Desativados</option>
                                                        <option value="teste" <?php if (isset($_GET['listopt']) && $_GET["listopt"] == 'teste') { ?> selected="true"<?php } ?>>Logins Teste</option>
                                                        <option value="vencido" <?php if (isset($_GET['listopt']) && $_GET["listopt"] == 'vencido') { ?> selected="true"<?php } ?>>Logins Vencidos</option>
                                                    </select>
                                                </td>
                                                <!-- Campos Busca Removido --->
                                                <td><input type="submit" value="Filtrar" class="btn btn-default"/></td>
                                            </tr>
                                        </table>
                                    </form>
                                </td>

                                <td align="right">
                                    <label style="font-size: 8pt">Buscar</label>
                                    <form action="manusers.php?<?php echo url_query('busca', 'true') ?>" >
<?php if (isset($_GET["p"])): ?>
                                            <input type="hidden" name="p" value="<?php echo $_GET["p"] ?>"/>
<?php endif; ?>
<?php if (isset($_GET["listopt"])): ?>
                                            <input type="hidden" name="listopt" value="<?php echo $_GET["listopt"] ?>"/>
<?php endif; ?>
                                        <table>
                                            <td><input type="text" name="inptbusca" value="<?php echo isset($_GET["inptbusca"]) ? $_GET["inptbusca"] : ""; ?>" class="form-control"/></td>
                                            <td><input type="submit" value="IR" class="btn btn-default"/></td>
                                        </table>
                                    </form>
                                </td>
                            </tr>
                        </table>
                        <p style="border: solid 0x red; margin: 0px; text-align: right">
                            <a href="impressao_logins.php?<?php echo $_SERVER['QUERY_STRING']; ?>" style="text-decoration: none; font-size: 8pt" target="_blank"><img src="images/impressora.png" width="15px"/> Visualização para impressão</a>
                        </p> <!-- Pagina Impressão -->
                        <table class="table table-bordered table-condensed" style="font-size: 9pt">
                            <thead >
                                <tr>
                                    <th><input type="checkbox" class="marc-td"/>&nbsp;<span style="font-size: 8pt">Todos</span></th>
                                    <!--<th><a href="?<?php echo url_query(array("orderby", "class"), array("id", (isset($_GET['orderby']) && $_GET['orderby'] == "id") ? (($_GET['class'] == "a") ? "d" : "a") : "a")); ?>">ID</a></th>-->
                                    <th><a href="?<?php echo url_query(array("orderby", "class"), array("status", (isset($_GET['orderby']) && $_GET['orderby'] == "status") ? (($_GET['class'] == "a") ? "d" : "a") : "a")); ?>">Status</a></th>
                                    <th><a href="?<?php echo url_query(array("orderby", "class"), array("nome", (isset($_GET['orderby']) && $_GET['orderby'] == "nome") ? (($_GET['class'] == "a") ? "d" : "a") : "a")); ?>">Nome</a></th>
                                    <th><a href="?<?php echo url_query(array("orderby", "class"), array("login", (isset($_GET['orderby']) && $_GET['orderby'] == "login") ? (($_GET['class'] == "a") ? "d" : "a") : "a")); ?>">Login</a></th>                                    
                                    <th>Senha</th>
                                    <th>Contato</th>                                    
                                    <th>Revendedor</th>
                                    <th><a href="?<?php echo url_query(array("orderby", "class"), array("vencimento", (isset($_GET['orderby']) && $_GET['orderby'] == "vencimento") ? (($_GET['class'] == "a") ? "d" : "a") : "a")); ?>">Vencimento</a></th>
                                    <th><a href="?<?php echo url_query(array("orderby", "class"), array("dias_restante", (isset($_GET['orderby']) && $_GET['orderby'] == "dias_restante") ? (($_GET['class'] == "a") ? "d" : "a") : "a")); ?>">Restam</a></th>
                                    <th>Obs do Login</th>
                                    <th>Valor Cobrado</th>
                                    <th></th>
                                </tr>

                            </thead>
                            <tbody>

<?php if (mysql_num_rows($resultP) > 0): ?>

    <?php
    while ($line = mysql_fetch_array($resultP)) {
        //Difinindo o Status do Cliente
        $agora = date('Y-m-d H:i:s');
        //$img_status = "images/greendot.png";
        //$img_title = "Login Ativo";
        $_status = '<span class="label label-success">Ativo</span>';
        $login = $line['name'];
        $comp_tr = "";
        if ($line['data_dif'] < 0) {
            $line['data_dif'] = 0;
        }
        if ($line['data_dif'] <= 2 && $line['data_dif'] >= 0) {
            $_status = '<span class="label label-warning">Vencendo</span>';
            $comp_tr = "color: orange;";
        }

        if (($line['expiredate'] < $agora)) {
            $_status = '<span class="label label-danger">Vencido</span>';
            $comp_tr = "color: red;";
        }
        if (($line['enabled'] == "false")) {
            //$img_status = "images/reddot.png";
            //$img_title = "Login Vencido ou Desativado";
            $_status = '<span class="label label-danger">Desativado</span>';
            $comp_tr = "color: red;font-weight: bolder;";
        }
        //$line['status'] = "<img src='$img_status' width='25px' title='$img_title'/>";
        //Marcando Clientes Teste
        if ($line['teste_ver'] <= 2) {

            $line['name'] .= '<sup><span class="label label-info" style="font-size:7pt">Teste</span></sup>';
        }
        //Mostrando dias que restam para expirar
        //Perfis
        $us_pf_str = "";
        $ip_cad = "";
        $ip_atualizacao = "";
        $ls_us_pfs = unserialize($line['profiles']); // Perfis cadastrado para o usuario
        //Buscando Perfis no Sistema
        $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
        mysql_select_db($dbname, $conn);
        $SQL = "SELECT id,name FROM cmum_profiles";
        $rs_pf = mysql_query($SQL);
        //Transformando Perfis do Sistema em Array
        $ls_pf_st = array();
        while ($ln_pf = mysql_fetch_assoc($rs_pf)) {
            $ls_pf_st[$ln_pf['id']] = $ln_pf['name'];
        }
        foreach ($ls_us_pfs as $id_pf_us) {

            if (array_key_exists($id_pf_us, $ls_pf_st)) {

                $us_pf_str .= $ls_pf_st[$id_pf_us] . ",";
            }
        }
        $us_pf_str = substr($us_pf_str, 0, -1);
        if ($_SESSION["adminlevel"] == "0") {
            $ip_cad = "<br/> Ip de Cadastro: {$line["ip_cad"]}";
            $ip_atualizacao = "<br/> Ip de Atualização: {$line["ip_atualizacao"]}";
        }

        $pedit = base64_encode("{\"id\":{$line["id"]},\"aid\":{$line["addedby"]}}");
        $falha_login = "$login";
        $controles = "
                                          <a href='edituser.php?p=$pedit'><img src='images/edit.png'/></a>
                                          <a href='deluser.php?p=$pedit'><img src='images/delete.png'/></a>"
                . "&nbsp;<a href='falha_logins.php?login=$falha_login' class='falha_logins'><img src='images/falhas_login.png' width='15px' title='Falhas do Login no Servidor'/></a>";
        ?>
                                        <tr style="<?php echo $comp_tr; ?>">
                                        <?php if ($_SESSION['adminlevel'] == "1" && ($line['id_rev_mudou_status'] != "0" && $line['id_rev_mudou_status'] != $_SESSION['adminid'])): ?>
                                                <td><img src="images/cancel_48.png" width="20px"/></td>
                                        <?php else: ?>                                                
                                                <td><input type="checkbox" name="sel-logins[]" class="sel-login" value="<?php echo $line['id']; ?>"/></td>
                                        <?php endif; ?>
                                <!--<td><?php echo $line['id']; ?></td>-->
                                            <td><?php echo $_status; ?></td>
                                            <td style="font-size: 7pt"><?php echo $line['displayname']; ?></td>
                                            <td ><?php echo $line['name']; ?>&nbsp;<sup title="Numero de conexões">(<?php echo $line['maxconnections']; ?>)</sup></td>
                                            <td ><?php echo $line['password']; ?></td>
                                            <td style="font-size: 7pt">
                                                <p>Email: <?php echo $line['email']; ?><br/>
                                                    Telefone: <?php echo $line['dd']; ?>-<?php echo $line['telefone']; ?><br/>
                                                    celular: <?php echo $line['dd_cel']; ?>-<?php echo $line['celular']; ?><br/>
                                                </p>
                                            </td>                                            
                                            <td><?php echo $line['username']; ?></td>
                                            <td><?php echo $line['expiredate_br']; ?></td>
                                            <td><?php echo $line['data_dif']; ?><span style="font-size: 7pt">&nbsp;(dias)</span></td>
                                            <td style="font-size: 7pt"><?php echo "Cadastrado em:" . date('d/m/Y H:i', strtotime($line['added'])) . "<br/>" . $line['obs_user'] . "<br/>Perfis: " . $us_pf_str . $ip_cad . $ip_atualizacao ?></td>
                                            <td>R$ <?php echo $line['valor_cob']; ?></td>
        <?php if ($_SESSION['adminlevel'] == "1" && ($line['id_rev_mudou_status'] != "0" && $line['id_rev_mudou_status'] != $_SESSION['adminid'])): ?>
                                                <td>&nbsp;</td>
        <?php else: ?>
                                                <td><?php echo $controles; ?></td>
        <?php endif; ?>
                                        </tr>
                                        <?php } ?>

                                    <?php else: ?>
                                    <tr>
                                        <td colspan="9" style="text-align: center">Não existe resultado.</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="11">
                                        &nbsp;
                                    </td>



                                    <td colspan="2"> Mostrando de <?php echo $inicio + 1; ?> até <?php echo $inicio + mysql_num_rows($resultP); ?> num total de <?php echo $total_registros ?></td>
                                </tr>
<?php if ($num_paginas > 1): ?>
                                    <tr>
                                        <td colspan="11" align="center">
                                            <ul class="pagination">

    <?php
    if ($pag > 1) {
        if ($_SERVER["QUERY_STRING"] != "") {
            if (strpos($_SERVER["QUERY_STRING"], "pag") !== false) {
                $_SERVER["QUERY_STRING"] = preg_replace("/pag=[0-9]+/", "pag=1", $_SERVER["QUERY_STRING"]);
                echo "<li ><a href='?{$_SERVER["QUERY_STRING"]}'>< Primeira</a></li>";
            } else {
                echo "<li ><a href='?{$_SERVER["QUERY_STRING"]}&pag=1'>< Primeira</a></li>";
            }
        } else {
            echo "<li ><a href='?pag=1'>< Primeira</a></li>";
        }
    }

    for ($i = ($pag - 10); $i < $pag; $i++) {
        if ($i > 0) {
            if ($_SERVER["QUERY_STRING"] != "") {
                if (strpos($_SERVER["QUERY_STRING"], "pag") !== false) {
                    $_SERVER["QUERY_STRING"] = preg_replace("/pag=[0-9]+/", "pag={$i}", $_SERVER["QUERY_STRING"]);
                    echo "<li ><a href='?{$_SERVER["QUERY_STRING"]}'>{$i}</a></li>";
                } else {
                    echo "<li ><a href='?{$_SERVER["QUERY_STRING"]}&pag={$i}'>{$i}</a></li>";
                }
            } else {
                echo "<li ><a href='?pag={$i}'>{$i}</a></li>";
            }
        }
    }
    echo "<li class='active'><span>{$pag}<span class='sr-only'>(current)</span></span></li>";
    for ($i = ($pag + 1); $i < ($pag + 10); $i++) {
        if ($i <= $num_paginas) {
            if ($_SERVER["QUERY_STRING"] != "") {
                if (strpos($_SERVER["QUERY_STRING"], "pag") !== false) {
                    $_SERVER["QUERY_STRING"] = preg_replace("/pag=[0-9]+/", "pag={$i}", $_SERVER["QUERY_STRING"]);
                    echo "<li ><a href='?{$_SERVER["QUERY_STRING"]}'>{$i}</a></li>";
                } else {
                    echo "<li ><a href='?{$_SERVER["QUERY_STRING"]}&pag={$i}'>{$i}</a></li>";
                }
            } else {
                echo "<li ><a href='?pag={$i}'>{$i}</a></li>";
            }
        }
    }
    if ($pag < $num_paginas) {
        if ($_SERVER["QUERY_STRING"] != "") {
            if (strpos($_SERVER["QUERY_STRING"], "pag") !== false) {
                $_SERVER["QUERY_STRING"] = preg_replace("/pag=[0-9]+/", "pag={$num_paginas}", $_SERVER["QUERY_STRING"]);
                echo "<li ><a href='?{$_SERVER["QUERY_STRING"]}'>Ultima ></a></li>";
            } else {
                echo "<li ><a href=\"?{$_SERVER["QUERY_STRING"]}&pag={$num_paginas}\">Ultima ></a></li>";
            }
        } else {
            echo "<li ><a href=\"?pag={$num_paginas}\">Ultima ></a></li>";
        }
    }
    ?>
                                            </ul> 
                                        </td>
                                    </tr>
                                            <?php endif; ?>
                            </tfoot>


                        </table>
                    </div>
                    <!-- Modal nova data -->
                    <div class="modal modal-venc">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <h4 class="modal-title">Alterar Vencimento</h4>
                                </div>
                                <div class="modal-body">
                                    <div class="alert alert-warning">
                                        <p>Se a revenda for pre paga, os valores modificados não afetarão a cota a mesma.</p>
                                    </div>
                                    <label>Data de vencimento</label>
                                    <div class=>
                                        <input class="form-control" name="nova_data_venc" id="nova_data_venc"/>
                                    </div>

                                </div>
                                <div class="modal-footer">
                                    <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                                    <button type="button" class="btn btn-primary btn-sav-venc">Salvar</button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
                    <!-- Modal nova data -->
                    <div class="modal modal-valor">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <h4 class="modal-title">Mudar Valor Cobrado</h4>
                                </div>
                                <div class="modal-body">
                                    <label>Novo Valor</label>
                                    <div class="input-group">
                                        <div class="input-group-addon">R$ </div>
                                        <input class="form-control numeros" name="novo_valor_cob" id="novo_valor_cob" maxlength="8"/>
                                    </div>

                                </div>
                                <div class="modal-footer">
                                    <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                                    <button type="button" class="btn btn-primary btn-sav-valor">Salvar</button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
                    <!-- Modal Revenda -->
                    <div class="modal modal-revenda">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <h4 class="modal-title">Mudar Revenda</h4>
                                </div>
                                <div class="modal-body">
                                    <div class="alert alert-warning">
                                        <p>Se a nova revenda for pre paga, os logins modificados não afetarão a cota a mesma.</p>
                                    </div>
                                    <label>Nova Revenda</label>
                                    <div class="form-group"> 
                                        <select name='p' class='form-control' id="_p">
                                            <?php
                                            $json["id"] = "{$_SESSION['adminid']}";
                                            $p = base64_encode(json_encode($json));
                                            ?>

                                            <option value="<?php echo $p ?>"><?php echo $_SESSION['loginuser'] ?></option>
                                            <?php
                                            $arvore = arvoreRevendas2();
                                            $arvore_lista = arvoreRevendasLista();
                                            listaOptionsRenvendas($arvore[$_SESSION['adminid']], $arvore_lista, isset($_GET['_p']) ? $_GET['_p'] : "", $_SESSION['_hierarquia']);
                                            ?>
                                        </select> 
                            <!--<input class="form-control numeros" name="novo_valor_cob" id="novo_valor_cob" maxlength="8"/>-->
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                                    <button type="button" class="btn btn-primary btn-sav-revenda">Salvar</button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
                    <!-- Modal Confirma Exclusão -->
                    <div class="modal modal-conf-del">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <h4 class="modal-title">Confirmação</h4>
                                </div>
                                <div class="modal-body">
                                    Deseja mesmo <strong>deletar</strong> os itens selecionados?
                                </div>
                                <div class="modal-footer">
                                    <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                                    <button type="button" class="btn btn-primary btn-conf-del">Sim</button>&nbsp;<button type="button" class="btn btn-warning btn-conf-del-nao">Não</button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
                    <!-- Modal Confirma Ativação -->
                    <div class="modal modal-conf-ativ">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <h4 class="modal-title">Confirmação</h4>
                                </div>
                                <div class="modal-body">
                                    Deseja mesmo <strong>ativar</strong> os itens selecionados?
                                </div>
                                <div class="modal-footer">
                                    <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                                    <button type="button" class="btn btn-primary btn-conf-ativ">Sim</button>&nbsp;<button type="button" class="btn btn-warning btn-conf-ativ-nao">Não</button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
                    <!-- Modal Confirma Desativação -->
                    <div class="modal modal-conf-desat">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <h4 class="modal-title">Confirmação</h4>
                                </div>
                                <div class="modal-body">
                                    Deseja mesmo <strong>desativar</strong> os itens selecionados?
                                </div>
                                <div class="modal-footer">
                                    <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                                    <button type="button" class="btn btn-primary btn-conf-desat">Sim</button>&nbsp;<button type="button" class="btn btn-warning btn-conf-desat-nao">Não</button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
                    <!-- Modal Ação Sucesso -->
                    <div class="modal modal-acao-sucesso">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <h4 class="modal-title">Sucesso</h4>
                                </div>
                                <div class="modal-body">
                                    Ação executada com sucesso.
                                </div>
                                <div class="modal-footer">
                                    <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                                    <button type="button" class="btn btn-primary btn-conf-sucesso">Ok</button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
<?php
unset($activeusers);
unset($activeusersstate);
unset($userinfo);
require("includes/footer.php");
?>

                </body>
                <script>
                    $(document).ready(function () {
                        // açao click login falhados
                        $('.falha_logins').on('click', this, function () {
                            var url = $(this).prop('href');
                            var w = 600;
                            var h = 400;
                            var left = (screen.width / 2) - (w / 2);
                            var top = (screen.height / 2) - (h / 2);
                            var janela = window.open(url, "", "width=" + w + ", height=" + h + ", left=" + left + ", top=" + top);
                            /*var id_int = setInterval(function() {
                             if (janela.closed == true) {
                             window.self.location.reload();
                             clearInterval(id_int);
                             }
                             }, 1000);*/


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

                        //Ação para marcar todos
                        $('.marc-td').on('click', this, function () {
                            v = false;
                            $(this).is(':checked') ? v = true : v = false;
                            if (v == true) {
                                if ($('.sel-login').length > 0) {
                                    $('.sel-login').prop('checked', true);
                                    $('.sel-opc-td-lg').prop('disabled', false);
                                }
                            }
                            if (v == false) {
                                if ($('.sel-login').length > 0) {
                                    $('.sel-login').prop('checked', false);
                                    $('.sel-opc-td-lg').prop('disabled', true);
                                }
                            }
                        });
                        //Ação para clicks individuais
                        $('.sel-login').on('click', this, function () {
                            if ($('.sel-login:checked').length > 0) {
                                $('.sel-opc-td-lg').prop('disabled', false);
                            } else {
                                $('.sel-opc-td-lg').prop('disabled', true);
                            }
                        });
                        $('.sel-opc-td-lg').on('change', this, function () {
                            var v_opc = $(this).val();
                            if (v_opc == 0) {
                                return false;
                            }
                            // Mostrando o modal vencimento
                            if (v_opc == 1) {
                                $('.modal-venc').modal('show');
                                return false;
                            }
                            // Mostrando o modal nova valor
                            if (v_opc == 5) {
                                $('.modal-valor').modal('show');
                                return false;
                            }
                            if (v_opc == 4) {
                                /*var q = window.confirm('Deseja mesmo deletar estes itens?');
                                 if (q === false) {
                                 return q;
                                 }*/
                                $(".modal-conf-del").modal("show");
                                return false;
                            }
                            if (v_opc == 2) {
                                /*var q = window.confirm('Deseja mesmo ativar os itens selecionados?');
                                 if (q === false) {
                                 return q;
                                 }*/
                                $(".modal-conf-ativ").modal("show");
                                return false;
                            }
                            if (v_opc == 3) {
                                /*var q = window.confirm('Deseja mesmo desativar os itens selecionados?');
                                 if (q === false) {
                                 return q;
                                 }*/
                                $(".modal-conf-desat").modal("show");
                                return false;
                            }
                            if (v_opc == 6) {
                                $('.modal-revenda').modal('show');
                                return false;
                            }
                        });
                        //Confirma exclusão
                        $('.btn-conf-del').on('click', this, function () {
                            var v_opc = 4;
                            var ids_sel = [];
                            $.each($('.sel-login:checked'), function () {
                                ids_sel.push($(this).val());
                            });
                            $.ajax({
                                url: "manusers.php?mod_opc=true",
                                type: "POST",
                                data: {
                                    '_ids_sel[]': ids_sel,
                                    _opc: v_opc
                                },
                                dataType: 'json'
                            })
                                    .done(function (r) {
                                        if (r.sucesso) {
                                            //alert(r.sucesso);
                                            $(".modal-conf-del").modal("hide");
                                            $('.modal-acao-sucesso').modal("show");
                                        }
                                        //window.location.reload();
                                    })
                        });
                        //Cancela exclusão
                        $('.btn-conf-del-nao').on('click', this, function () {
                            $(".modal-conf-del").modal("hide");
                            //window.location.reload();
                            return false;
                        });
                        //Confirma Ativação
                        $('.btn-conf-ativ').on('click', this, function () {
                            var v_opc = 2;
                            var ids_sel = [];
                            $.each($('.sel-login:checked'), function () {
                                ids_sel.push($(this).val());
                            });
                            $.ajax({
                                url: "manusers.php?mod_opc=true",
                                type: "POST",
                                data: {
                                    '_ids_sel[]': ids_sel,
                                    _opc: v_opc
                                },
                                dataType: 'json'
                            })
                                    .done(function (r) {
                                        if (r.sucesso) {
                                            //alert(r.sucesso);
                                            $(".modal-conf-ativ").modal("hide");
                                            $('.modal-acao-sucesso').modal("show");
                                        }
                                        //window.location.reload();
                                    })
                        });
                        //Cancela ativação
                        $('.btn-conf-ativ-nao').on('click', this, function () {
                            $(".modal-conf-ativ").modal("hide");
                            //window.location.reload();
                            return false;
                        });
                        //Confirma desativação
                        $('.btn-conf-desat').on('click', this, function () {
                            var v_opc = 3;
                            var ids_sel = [];
                            $.each($('.sel-login:checked'), function () {
                                ids_sel.push($(this).val());
                            });
                            $.ajax({
                                url: "manusers.php?mod_opc=true",
                                type: "POST",
                                data: {
                                    '_ids_sel[]': ids_sel,
                                    _opc: v_opc
                                },
                                dataType: 'json'
                            })
                                    .done(function (r) {
                                        if (r.sucesso) {
                                            //alert(r.sucesso);
                                            $(".modal-conf-desat").modal("hide");
                                            $('.modal-acao-sucesso').modal("show");
                                        }
                                        //window.location.reload();
                                    })
                        });
                        //Cancela ativação
                        $('.btn-conf-desat-nao').on('click', this, function () {
                            $(".modal-conf-desat").modal("hide");
                            //window.location.reload();
                            return false;
                        });
                        //Ação botão sucesso
                        $('.btn-conf-sucesso').on('click', this, function () {
                            $('.modal-acao-sucesso').modal("hide");
                            //window.location.reload();
                        });
                        //Quando modal sucesso ocultar
                        $('.modal-acao-sucesso').on('hidden.bs.modal', function (e) {
                            // do something...
                            e.preventDefault();
                            window.location.reload();
                        });

                        $('.btn-sav-venc').on('click', this, function () {
                            var v_opc = 1;
                            if ($('#nova_data_venc').val() == "") {
                                alert('Preencha a data');
                                return false;
                            }
                            var ids_sel = [];
                            $.each($('.sel-login:checked'), function () {
                                ids_sel.push($(this).val());
                            });
                            $.ajax({
                                url: "manusers.php?mod_opc=true",
                                type: "POST",
                                data: {
                                    '_ids_sel[]': ids_sel,
                                    _opc: v_opc,
                                    _nova_data: $('#nova_data_venc').val()
                                },
                                dataType: 'json'
                            })
                                    .done(function (r) {
                                        if (r.sucesso) {
                                            //alert(r.sucesso);
                                            $('.modal-venc').modal('hide');
                                            $('.modal-acao-sucesso').modal("show");

                                        }
                                        //window.location.reload();
                                    })

                        });
                        $('.btn-sav-valor').on('click', this, function () {
                            var v_opc = 5;
                            if ($('#novo_valor_cob').val() == "") {
                                alert('Preencha o valor');
                                return false;
                            }

                            var ids_sel = [];
                            $.each($('.sel-login:checked'), function () {
                                ids_sel.push($(this).val());
                            });
                            $.ajax({
                                url: "manusers.php?mod_opc=true",
                                type: "POST",
                                data: {
                                    '_ids_sel[]': ids_sel,
                                    _opc: v_opc,
                                    _novo_valor: $('#novo_valor_cob').val()
                                },
                                dataType: 'json'
                            })
                                    .done(function (r) {
                                        if (r.sucesso) {
                                            //alert(r.sucesso);
                                            $('.modal-valor').modal('hide');
                                            $('.modal-acao-sucesso').modal("show");
                                        }
                                        //window.location.reload();
                                    })

                        });
                        $('.btn-sav-revenda').on('click', this, function () {
                            var v_opc = 6;
                            if ($('#p').val() == "") {
                                alert('Preencha o valor');
                                return false;
                            }
                            var ids_sel = [];
                            $.each($('.sel-login:checked'), function () {
                                ids_sel.push($(this).val());
                            });
                            $.ajax({
                                url: "manusers.php?mod_opc=true",
                                type: "POST",
                                data: {
                                    '_ids_sel[]': ids_sel,
                                    _opc: v_opc,
                                    _novo_revenda: $('#_p :selected').val()
                                },
                                dataType: 'json'
                            })
                                    .done(function (r) {
                                        
                                        if (r.sucesso) {
                                           
                                            $('.modal-revenda').modal('hide');
                                            $('.modal-acao-sucesso').modal("show");
                                            
                                        }
                                        if(r.erro){
                                            
                                            alert(r.erro); 
                                            
                                        }
                                    });
                        });
                    });

                </script>
                </html>
