<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Definindo o número de resultados por página
$results_per_page = isset($_GET['results']) ? (int)$_GET['results'] : 10; // Padrão para 10

if (isset($_GET['view'])) {
    $page = $_GET['view'];
} else {
    $page = 1;
}

$start_from = ($page - 1) * $results_per_page;
$db1 = new SQLite3('a/.eggziedb.db');

// Search functionality
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$searchQuery = '';
if (!empty($searchTerm)) {
    $searchQuery = "WHERE mac_address LIKE '%$searchTerm%' 
                    OR title LIKE '%$searchTerm%' 
                    OR username LIKE '%$searchTerm%' 
                    OR url LIKE '%$searchTerm%'"; // Adicionado busca por DNS
    $limit = ""; // Remove o limite durante a busca
} else {
    $limit = "LIMIT $start_from, $results_per_page"; // Adiciona limite quando não há busca
}

$result = $db1->query("SELECT COUNT(id) AS total FROM ibo $searchQuery");
$rownew = $result->fetchArray();
$totaleview = $rownew['total'];
$total_pages = ceil($rownew['total'] / $results_per_page);
$res1 = $db1->query("SELECT * FROM ibo $searchQuery ORDER BY id ASC $limit");

if (isset($_GET['delete'])) {
    $db1->exec('DELETE FROM ibo WHERE id=' . $_GET['delete']);
    // Verifica se a página atual é a primeira página para garantir que o parâmetro view seja definido corretamente
    $redirect_page = isset($_GET['view']) && $_GET['view'] > 1 ? 'users.php?view=' . $_GET['view'] : 'users.php';
    header('Location: ' . $redirect_page);
    exit; // Termina o script após o redirecionamento
}

// Processamento da exclusão em massa
if (isset($_POST['delete_selected'])) {
    if (!empty($_POST['selected_users'])) {
        $selected_ids = $_POST['selected_users'];
        foreach ($selected_ids as $id) {
            $db1->exec('DELETE FROM ibo WHERE id=' . intval($id));
        }
        // Redireciona após a exclusão
        header('Location: users.php');
        exit;
    }
}

include 'includes/header.php';
?>
<style>
    .pagination-select {
        padding: 5px 10px;
        background-color: transparent; /* Alterado para transparente */
        color: black; /* Alterado para preto para tornar visível */
        border: 1px solid black; /* Adiciona borda preta */
        cursor: pointer;
        border-radius: 5px; /* Adiciona bordas arredondadas */
    }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirme sua opção!</h2>
            </div>
            <div class="modal-body">
                Você realmente deseja excluir este usuário?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>
<main role="main" class="col-15 pt-4 px-5">
    <div class="">
        <div id="main">
            <!-- Content Row -->
            <div class="row">
                <!-- First Column -->
                <div class="col-lg-12">
                    <!-- Custom codes -->
                    <div class="card border-left-primary shadow h-100 card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-fw fa-user-plus"></i> Usuários</h6>
                        </div>
                        <div class="card-body">
                            <form method="get" class="mb-3">
                                <div class="form-group">
                                    <div class="input-group">
                                        <input type="text" name="search" class="form-control" placeholder="Pesquisar pelo Nome, MAC, Usuário ou DNS">
                                        <div class="input-group-append">
                                            <button type="submit" class="btn btn-primary">Pesquisar</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="results">Resultados por página:</label>
                                    <select name="results" id="results" class="form-control" onchange="this.form.submit()">
                                        <option value="10" <?php if ($results_per_page == 10) echo 'selected'; ?>>10</option>
                                        <option value="20" <?php if ($results_per_page == 20) echo 'selected'; ?>>20</option>
                                        <option value="50" <?php if ($results_per_page == 50) echo 'selected'; ?>>50</option>
                                        <option value="100" <?php if ($results_per_page == 100) echo 'selected'; ?>>100</option>
                                        <option value="200" <?php if ($results_per_page == 200) echo 'selected'; ?>>200</option>
                                        <option value="500" <?php if ($results_per_page == 500) echo 'selected'; ?>>500</option>
                                        <option value="1000" <?php if ($results_per_page == 1000) echo 'selected'; ?>>1000</option>
                                        <option value="2000" <?php if ($results_per_page == 2000) echo 'selected'; ?>>2000</option>
                                    </select>
                                </div>
                            </form>
                            <div class="form-group">
                                <div class="input-group">
                                    <a href="./users_create.php" class="btn btn-primary btn-icon-split">
                                        <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                                        <span class="text">Cadastrar Usuário</span>
                                    </a>
                                </div>
                            </div>
                            <form method="post" action="users.php">
                                <div class="form-group">
                                    <button type="submit" name="delete_selected" class="btn btn-danger mb-3">Excluir Selecionados</button>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-striped table-sm">
                                        <thead class="text-primary">
                                            <tr>
                                                <th><input type="checkbox" id="select-all"></th>
                                                <th>Nome</th>
                                                <th>Endereço MAC</th>
                                                <th>Usuário</th>
                                                <th>Data Expiracao</th>
                                                <th>DNS</th>
                                                <th>Editar</th>
                                                <th>Excluir</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row1 = $res1->fetchArray()) { ?>
                                                <tr>
                                                    <?php
                                                    $users_id = $row1['id'];
                                                    $user_mac = $row1['mac_address'];
                                                    $user_username = $row1['username'];
                                                    $user_expire_date = $row1['expire_date'];
                                                    $user_url = $row1['url'];
                                                    $user_title = $row1['title'];
                                                    ?>
                                                    <td><input type="checkbox" name="selected_users[]" value="<?php echo $users_id; ?>"></td>
                                                    <td><?php echo $user_title; ?></td>
                                                    <td><?php echo $user_mac; ?></td>
                                                    <td><?php echo $user_username; ?></td>
                                                    <td><?php echo $user_expire_date; ?></td>
                                                    <td><?php echo $user_url; ?></td>
                                                    <td>
                                                        <a class="btn btn-icon" href="./users_update.php?update=<?php echo $users_id; ?>">
                                                            <span class="icon text-white-50"><i class="fa fa-pencil-square" style="font-size:24px;color:blue"></i></span>
                                                        </a>
                                                    </td>
                                                    <td>
                                                        <a class="btn btn-icon delete-btn" href="#" data-href="./users.php?delete=<?php echo $users_id; ?>" data-toggle="modal" data-target="#confirm-delete">
                                                            <span class="icon text-white-50"><i class="fa fa-trash" style="font-size:24px;color:red"></i></span>
                                                        </a>
                                                    </td>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </form>
                            <?php if ($results_per_page < $totaleview && empty($searchTerm)) { ?>
                                <div class="pagination">
                                    <select class="pagination-select" onchange="window.location.href=this.value" style="border-radius: 5px;">
                                    <?php for ($i = 1; $i <= $total_pages; $i++) { ?>
                                    <option value='users.php?view=<?php echo $i; ?>&results=<?php echo $results_per_page; ?>' <?php if ($i == $page) echo "selected"; ?>><?php echo $i; ?></option>
                                    <?php } ?>
                                    </select>
                                </div>
                            <?php } ?>
                            <?php
                            include 'includes/footer.php';
                            require 'includes/egz.php';
                            ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
    // Selecionar/desselecionar todos os checkboxes
    document.getElementById('select-all').onclick = function() {
        const checkboxes = document.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    };
</script>