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

$itensPorPagina = 10;
$paginaAtual = $_GET['view'] ?? 1;
$offset = ($paginaAtual - 1) * $itensPorPagina;
$ajax = $_GET['ajax'] ?? 0;

$db = new SQLite3('a/.eggziedb.db');

// Busca dinâmica (via AJAX)
$search = $_GET['search'] ?? '';

// Filtragem por busca
$where = '';
if ($search !== '') {
    $where = " WHERE username LIKE '%$search%' OR mac_address LIKE '%$search%'";
}

// Contagem total
$totalQuery = $db->query('SELECT COUNT(id) AS total FROM ibo' . $where);
$totalResult = $totalQuery->fetchArray();
$totalItens = $totalResult['total'];
$totalPaginas = ceil($totalItens / $itensPorPagina);

// Seleção de dados
$dataQuery = $db->query('SELECT * FROM ibo' . $where . ' ORDER BY id ASC LIMIT ' . $offset . ', ' . $itensPorPagina);

// Exclusão
if (isset($_GET['delete'])) {
    $db->exec('DELETE FROM ibo WHERE id=' . $_GET['delete']);
    header('Location: users.php');
    exit;
}

// --- AJAX: retornar somente a tabela ---
if ($ajax) {
    echo '<table class="table table-striped table-sm">
            <thead class="text-primary">
                <tr>
                    <th>Título</th>
                    <th>Endereço MAC</th>
                    <th>Usuário</th>
                    <th>Data de Expiração</th>
                    <th>DNS</th>
                    <th>Editar</th>
                    <th>Excluir</th>
                </tr>
            </thead>
            <tbody>';
    while ($row = $dataQuery->fetchArray()) {
        echo '<tr>
                <td>' . $row['title'] . '</td>
                <td>' . $row['mac_address'] . '</td>
                <td>' . $row['username'] . '</td>
                <td>' . $row['expire_date'] . '</td>
                <td>' . $row['url'] . '</td>
                <td><a class="btn btn-icon" href="./users_update.php?update=' . $row['id'] . '"><i class="fas fa-pencil-alt" style="font-size:24px;color:blue"></i></a></td>
                <td><a class="btn btn-icon" href="#" data-href="./users.php?delete=' . $row['id'] . '" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-trash" style="font-size:24px;color:red"></i></a></td>
              </tr>';
    }
    echo '</tbody></table>';

    // Paginação
    if ($itensPorPagina < $totalItens) {
        for ($i = 1; $i <= $totalPaginas; $i++) {
            $link = 'users.php?view=' . $i;
            if ($search !== '') $link .= '&search=' . urlencode($search);
            $active = ($i == $paginaAtual) ? 'active' : '';
            echo '<a class="btn btn-outline-primary ' . $active . '" href="' . $link . '">Página ' . $i . '</a> ';
        }
    }
    exit;
}

include 'includes/header.php';
?>

<main role="main" class="col-15 pt-4 px-2">
    <div id="main">
        <h1 class="h3 mb-1 text-gray-800">Usuários</h1>
        <a class="btn btn-primary btn-icon-split mb-2" href="./users_create.php">
            <span class="icon text-white-50"><i class="fas fa-plus"></i></span>
            <span class="text">Criar</span>
        </a>

        <!-- Busca dinâmica -->
        <input type="text" id="searchInput" class="form-control mb-3" placeholder="Pesquisar por Usuário ou MAC">

        <div class="table-responsive" id="tableContainer">
            <table class="table table-striped table-sm">
                <thead class="text-primary">
                    <tr>
                        <th>Título</th>
                        <th>Endereço MAC</th>
                        <th>Usuário</th>
                        <th>Data de Expiração</th>
                        <th>DNS</th>
                        <th>Editar</th>
                        <th>Excluir</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $dataQuery->fetchArray()): ?>
                        <tr>
                            <td><?= $row['title'] ?></td>
                            <td><?= $row['mac_address'] ?></td>
                            <td><?= $row['username'] ?></td>
                            <td><?= $row['expire_date'] ?></td>
                            <td><?= $row['url'] ?></td>
                            <td><a class="btn btn-icon" href="./users_update.php?update=<?= $row['id'] ?>"><i class="fas fa-pencil-alt" style="font-size:24px;color:blue"></i></a></td>
                            <td><a class="btn btn-icon" href="#" data-href="./users.php?delete=<?= $row['id'] ?>" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-trash" style="font-size:24px;color:red"></i></a></td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>

            <!-- Paginação -->
            <?php if ($itensPorPagina < $totalItens): ?>
                <?php for ($i = 1; $i <= $totalPaginas; $i++):
                    $link = 'users.php?view=' . $i;
                    $active = ($i == $paginaAtual) ? 'active' : '';
                ?>
                    <a class="btn btn-outline-primary <?= $active ?>" href="<?= $link ?>">Página <?= $i ?></a>
                <?php endfor; ?>
            <?php endif; ?>
        </div>
    </div>
</main>

<!-- Modal de confirmação -->
<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>Confirmar</h2>
            </div>
            <div class="modal-body">
                Deseja realmente excluir este usuário?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>

<script>
// Busca dinâmica (live search sem cache)
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keyup', function() {
    const query = this.value;
    fetch('users.php?ajax=1&search=' + encodeURIComponent(query))
        .then(response => response.text())
        .then(html => {
            document.getElementById('tableContainer').innerHTML = html;
        });
});
</script>

<style>
.table-responsive { overflow-x: auto; }
.table td, .table th { vertical-align: middle; }
.btn-icon i { font-size: 20px; }
@media (max-width: 768px) {
    .table td, .table th { font-size: 14px; padding: 0.3rem; }
    .btn-icon i { font-size: 18px; }
}
</style>

<?php
include 'includes/footer.php';
require 'includes/egz.php';
?>