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

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

// --- LÓGICA DE FILTROS E PAGINAÇÃO ---
$limit_get = isset($_GET['limit']) ? $_GET['limit'] : 20;
$results_per_page = ($limit_get === 'all') ? 999999 : (int)$limit_get;
$page = isset($_GET['view']) ? (int)$_GET['view'] : 1;
$start_from = ($page - 1) * $results_per_page;

$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$filterSeller = isset($_GET['f_seller']) ? $_GET['f_seller'] : '';
$filterServer = isset($_GET['f_server']) ? $_GET['f_server'] : '';

$conditions = [];
if (!empty($searchTerm)) {
    $conditions[] = "(mac_address LIKE '%$searchTerm%' OR title LIKE '%$searchTerm%' OR username LIKE '%$searchTerm%')";
}
if (!empty($filterSeller)) {
    $conditions[] = "seller = '$filterSeller'";
}
if (!empty($filterServer)) {
    $conditions[] = "title = '$filterServer'";
}

$whereClause = count($conditions) > 0 ? "WHERE " . implode(" AND ", $conditions) : "";

// Listas para os Selects
$sellersList = $db1->query("SELECT DISTINCT seller FROM ibo ORDER BY seller ASC");
$serversList = $db1->query("SELECT DISTINCT title FROM ibo ORDER BY title ASC");

$countResult = $db1->query("SELECT COUNT(id) AS total FROM ibo $whereClause");
$rowCount = $countResult->fetchArray();
$total_records = $rowCount['total'];
$total_pages = ceil($total_records / $results_per_page);

$res1 = $db1->query("SELECT * FROM ibo $whereClause ORDER BY id ASC LIMIT $start_from, $results_per_page");

if (isset($_GET['delete'])) {
    $ids_to_delete = explode(',', $_GET['delete']);
    foreach ($ids_to_delete as $id) {
        $db1->exec('DELETE FROM ibo WHERE id=' . (int)$id);
    }
    header('Location: users.php');
    exit();
}

include 'includes/header.php';
?>

<style>
    :root {
        --neon-blue: #00d4ff;
        --dark-bg: #06090c;
        --card-glass: rgba(13, 18, 24, 0.95);
        --border-glass: rgba(0, 212, 255, 0.2);
    }

    /* --- REMOÇÃO TOTAL DO FUNDO BRANCO --- */
    /* Força o fundo escuro em todos os possíveis contêineres do sistema */
    html, body, 
    #wrapper, 
    #content-wrapper, 
    #content, 
    .container-fluid,
    .bg-white,
    .bg-light {
        background-color: var(--dark-bg) !important;
        color: #f8f9fc !important;
    }

    body { 
        font-family: 'Poppins', sans-serif;
    }

    /* Card Futurista */
    .card-futuristic {
        background: var(--card-glass) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--border-glass) !important;
        border-radius: 15px !important;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    }

    .card-header-futuristic {
        background: rgba(0, 212, 255, 0.03) !important;
        border-bottom: 1px solid var(--border-glass) !important;
        padding: 1.5rem !important;
    }

    .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-blue) !important;
        text-shadow: 0 0 10px var(--neon-blue);
        letter-spacing: 2px;
        margin: 0;
    }

    /* Tabela Futurista */
    .table-modern {
        color: #e0e0e0 !important;
        border-collapse: separate;
        border-spacing: 0 10px;
    }

    .table-modern thead th {
        border: none !important;
        color: var(--neon-blue) !important;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 1px;
        padding: 15px;
    }

    .table-modern tbody tr {
        background: rgba(255, 255, 255, 0.02);
        transition: all 0.3s ease;
        border-radius: 10px;
    }

    .table-modern tbody tr:hover {
        background: rgba(0, 212, 255, 0.08);
        transform: scale(1.005);
    }

    .table-modern td {
        border: none !important;
        padding: 15px !important;
        vertical-align: middle !important;
    }

    /* Inputs e Botões */
    .form-control-futuristic {
        background: rgba(0, 0, 0, 0.4) !important;
        border: 1px solid var(--border-glass) !important;
        color: #fff !important;
        border-radius: 8px;
    }

    .form-control-futuristic:focus {
        border-color: var(--neon-blue) !important;
        box-shadow: 0 0 10px var(--neon-blue);
        outline: none;
    }

    .btn-neon {
        background: transparent;
        border: 1px solid var(--neon-blue);
        color: var(--neon-blue) !important;
        transition: 0.3s;
        border-radius: 8px;
    }

    .btn-neon:hover {
        background: var(--neon-blue);
        color: #000 !important;
        box-shadow: 0 0 20px var(--neon-blue);
    }

    /* Paginação */
    .page-link-neon {
        padding: 8px 15px;
        border: 1px solid var(--border-glass);
        background: rgba(255,255,255,0.02);
        color: #fff;
        margin: 0 3px;
        border-radius: 5px;
        text-decoration: none;
    }

    .page-link-neon.active {
        border-color: var(--neon-blue);
        color: var(--neon-blue);
        background: rgba(0, 212, 255, 0.1);
    }

    code {
        background-color: transparent !important;
    }
</style>

<main role="main" class="col-15 pt-4 px-5">
    <div class="card card-futuristic shadow mb-4">
        <div class="card-header-futuristic d-flex justify-content-between align-items-center">
            <h6><i class="fas fa-users-cog mr-2"></i> GERENCIAMENTO DE USUÁRIOS</h6>
            <span class="badge" style="border: 1px solid var(--neon-blue); color: var(--neon-blue);">Total: <?php echo $total_records; ?></span>
        </div>
        <div class="card-body">
            
            <form method="get" class="mb-4">
                <div class="row align-items-end">
                    <div class="col-md-3">
                        <label class="small text-uppercase">Pesquisa Geral</label>
                        <input type="text" name="search" class="form-control form-control-futuristic" placeholder="MAC, Nome, Servidor..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="small text-uppercase">Vendedor</label>
                        <select name="f_seller" class="form-control form-control-futuristic">
                            <option value="">Todos</option>
                            <?php while($s = $sellersList->fetchArray()): ?>
                                <option value="<?php echo $s['seller']; ?>" <?php echo $filterSeller == $s['seller'] ? 'selected' : ''; ?>><?php echo $s['seller']; ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="small text-uppercase">Servidor</label>
                        <select name="f_server" class="form-control form-control-futuristic">
                            <option value="">Todos</option>
                            <?php while($sv = $serversList->fetchArray()): ?>
                                <option value="<?php echo $sv['title']; ?>" <?php echo $filterServer == $sv['title'] ? 'selected' : ''; ?>><?php echo $sv['title']; ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="small text-uppercase">Exibir</label>
                        <select name="limit" class="form-control form-control-futuristic">
                            <?php $opts = [5,10,20,30,50,'all']; foreach($opts as $o): ?>
                                <option value="<?php echo $o; ?>" <?php echo $limit_get == $o ? 'selected' : ''; ?>><?php echo $o == 'all' ? 'Ver Tudo' : "$o por página"; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3 text-right">
                        <button type="submit" class="btn btn-neon p-2 px-3"><i class="fas fa-filter"></i></button>
                        <a href="users_create.php" class="btn btn-neon p-2 px-3"><i class="fas fa-plus"></i></a>
                        <button type="button" class="btn btn-outline-danger p-2 px-3" id="excluirSelecionados" style="border-radius:8px;"><i class="fas fa-trash"></i></button>
                    </div>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-modern">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selecionarTodos"></th>
                            <th>Usuário</th>
                            <th>Endereço Mac</th>
                            <th>Vencimento</th>
                            <th>Vendedor</th>
                            <th>Servidor</th>
                            <th>DNS</th>
                            <th>Editar</th>
                            <th>Deletar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row1 = $res1->fetchArray()): ?>
                            <tr>
                                <td><input type="checkbox" class="user-checkbox" value="<?php echo $row1['id']; ?>"></td>
                                <td class="font-weight-bold" style="color:#fff;"><?php echo $row1['username']; ?></td>
                                <td><code style="color:var(--neon-blue);"><?php echo $row1['mac_address']; ?></code></td>
                                <td><span class="text-warning"><?php echo $row1['expire_date']; ?></span></td>
                                <td><span class="badge" style="border: 1px solid #444; color: #aaa; background: transparent;"><?php echo $row1['seller']; ?></span></td>
                                <td style="color: #00d4ff; opacity: 0.8;"><?php echo $row1['title']; ?></td>
                                <td><small style="font-size: 10px; opacity: 0.5;"><?php echo $row1['url']; ?></small></td>
                                <td>
                                    <a href="./users_update.php?update=<?php echo $row1['id']; ?>">
                                        <i class="fa fa-edit" style="font-size:18px; color:var(--neon-blue)"></i>
                                    </a>
                                </td>
                                <td>
                                    <a href="./users.php?delete=<?php echo $row1['id']; ?>" onclick="return confirm('Confirmar exclusão?');">
                                        <i class="fa fa-ban" style="font-size:18px; color:#ff3e3e"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_pages > 1 && $limit_get !== 'all'): ?>
                <div class="d-flex justify-content-center mt-4">
                    <?php 
                        $url_params = "&limit=$limit_get&search=".urlencode($searchTerm)."&f_seller=$filterSeller&f_server=$filterServer";
                    ?>
                    <?php for($i=1; $i<=$total_pages; $i++): ?>
                        <a href="users.php?view=<?php echo $i . $url_params; ?>" class="page-link-neon <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                    <?php endfor; ?>
                </div>
            <?php endif; ?>

        </div>
    </div>
</main>

<script>
    document.getElementById('selecionarTodos').onclick = function() {
        var checkboxes = document.getElementsByClassName('user-checkbox');
        for (var checkbox of checkboxes) { checkbox.checked = this.checked; }
    }

    document.getElementById('excluirSelecionados').onclick = function() {
        var selecionados = [];
        var checkboxes = document.getElementsByClassName('user-checkbox');
        for (var checkbox of checkboxes) { if (checkbox.checked) selecionados.push(checkbox.value); }
        if (selecionados.length > 0) {
            if (confirm('Deseja deletar permanentemente ' + selecionados.length + ' usuários?')) {
                window.location.href = 'users.php?delete=' + selecionados.join(',');
            }
        }
    }
</script>

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