<?php
include 'auth.php'; 
session_start();
ini_set("display_errors", 0);

if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

$db = new SQLite3("./api/.ansdb.db");

// Lógica de Exclusão Individual
if (isset($_GET["delete"])) {
    $stmt = $db->prepare("DELETE FROM ibo WHERE id = :id");
    $stmt->bindValue(':id', $_GET["delete"], SQLITE3_INTEGER);
    $stmt->execute();
    header("Location: all_users.php?status=deleted");
    exit();
}

include "includes/header.php";
?>

<style>
    /* RESET E SEGURANÇA */
    * { box-sizing: border-box; }

    /* FUNDO TOTAL DARK */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
        overflow-x: hidden;
    }

    /* OCULTAR NAVBAR ORIGINAL */
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }

    .container-fluid { padding: 15px !important; }

    /* BOTÃO VOLTAR */
    .btn-back-nav {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        text-decoration: none !important;
        font-size: 0.85rem;
        font-weight: 600;
        margin-bottom: 20px;
        transition: 0.3s;
    }
    .btn-back-nav:hover { color: #3b82f6; }

    /* CARD PREMIUM */
    .premium-card {
        background: #070e1b !important;
        border: 1px solid #1e293b !important;
        border-radius: 20px;
        padding: 20px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.4);
        width: 100%;
        margin-bottom: 40px;
    }

    .premium-card h1 { 
        font-size: 1.5rem; 
        font-weight: 800; 
        color: #fff; 
        margin: 0 0 5px 0; 
    }

    /* BUSCA */
    .search-wrapper { position: relative; margin: 20px 0; }
    .search-box { 
        width: 100%; 
        background: #0f172a !important; 
        border: 1px solid #1e293b !important; 
        color: #fff !important; 
        padding: 15px 15px 15px 45px; 
        border-radius: 14px; 
        font-size: 0.9rem;
    }
    .search-wrapper i { position: absolute; left: 18px; top: 18px; color: #475569; }

    /* TABELA COM ROLAGEM CORRIGIDA */
    .table-responsive-custom { 
        width: 100%; 
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch;
        border-radius: 15px; 
        border: 1px solid rgba(255,255,255,0.05); 
    }

    .table { margin: 0; min-width: 900px; color: #cbd5e1; background: transparent !important; }
    .table thead th { 
        background: #0f172a !important; 
        color: #3b82f6 !important; 
        padding: 18px 15px; 
        font-size: 0.75rem; 
        text-transform: uppercase; 
        letter-spacing: 1px;
        border: none;
    }
    .table tbody td { 
        border-top: 1px solid rgba(255,255,255,0.03); 
        padding: 16px; 
        vertical-align: middle; 
        white-space: nowrap;
    }

    /* BADGES */
    .badge-user {
        background: rgba(59, 130, 246, 0.1);
        color: #3b82f6;
        padding: 5px 10px;
        border-radius: 8px;
        font-size: 0.75rem;
        font-weight: 700;
    }

    /* BOTÕES DE AÇÃO */
    .action-group { display: flex; gap: 8px; justify-content: center; }
    .btn-act { 
        padding: 10px 14px; 
        border-radius: 10px; 
        font-size: 0.75rem; 
        font-weight: 700; 
        text-decoration: none !important; 
        display: inline-flex; 
        align-items: center; 
        gap: 6px; 
        transition: 0.2s;
        border: none;
        cursor: pointer;
    }
    
    /* REMOVIDO CSS DO STATUS - MANTIDO APENAS EDIT E DEL */
    .btn-act-edit { background: rgba(59, 130, 246, 0.1); color: #3b82f6; border: 1px solid rgba(59, 130, 246, 0.2); }
    .btn-act-del { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); }

    .btn-act:hover { transform: translateY(-2px); filter: brightness(1.2); }
</style>

<div class="container-fluid">
    <a href="users.php" class="btn-back-nav">
        <i class="fas fa-chevron-left"></i> Voltar à Gerência
    </a>

    <div class="premium-card">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <h1>Lista Global</h1>
                <p style="color: #64748b; font-size: 0.8rem; margin: 0;">Todos os clientes cadastrados no sistema</p>
            </div>
        </div>

        <div class="search-wrapper">
            <i class="fas fa-search"></i>
            <input type="text" id="search" class="search-box" placeholder="Pesquisar por MAC, Nome ou Usuário...">
        </div>

        <div class="table-responsive-custom">
            <table class="table" id="myTable">
                <thead>
                    <tr>
                        <th width="80">ID</th>
                        <th>MAC ADDRESS</th>
                        <th>LOGIN / LINHA</th>
                        <th>NOME DO CLIENTE</th>
                        <th class="text-center">GESTÃO</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $res = $db->query("SELECT * FROM ibo ORDER BY id DESC");
                    while ($row = $res->fetchArray()):
                        $v_display_user = $row['username'] ?? $row['user'] ?? '---';
                    ?>
                    <tr>
                        <td><span style="color: #475569;">#<?= $row['id'] ?></span></td>
                        <td style="font-family: monospace; font-weight: 700; color: #fff; letter-spacing: 0.5px;">
                            <?= strtoupper($row['mac_address']) ?>
                        </td>
                        <td>
                            <span class="badge-user">
                                <i class="fas fa-user-circle mr-1"></i> <?= $v_display_user ?>
                            </span>
                        </td>
                        <td>
                            <span style="font-weight: 600;"><?= htmlspecialchars($row['title'] ?? 'Sem Nome') ?></span>
                        </td>
                        <td class="text-center">
                            <div class="action-group">
                                <a href="./users_update.php?update=<?= $row['id'] ?>" class="btn-act btn-act-edit" title="Editar">
                                    <i class="fas fa-edit"></i> EDITAR
                                </a>
                                <button onclick="confirmDelete(<?= $row['id'] ?>)" class="btn-act btn-act-del" title="Excluir">
                                    <i class="fas fa-trash"></i> EXCLUIR
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        
        <div class="text-center mt-3 d-md-none" style="color: #475569; font-size: 0.7rem;">
            <i class="fas fa-exchange-alt mr-1"></i> Arraste a tabela para os lados
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // Filtro de Busca Global
    $("#search").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#myTable tbody tr").filter(function() { 
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) 
        });
    });

    // Confirmação de Exclusão
    function confirmDelete(id) {
        Swal.fire({
            title: 'Excluir Usuário?',
            text: "Esta ação removerá o acesso do banco de dados permanentemente.",
            icon: 'warning',
            background: '#070e1b',
            color: '#fff',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#1e293b',
            confirmButtonText: 'Sim, Excluir',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'all_users.php?delete=' + id;
            }
        });
    }

    // Alertas de Status
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('status') === 'deleted') {
        Swal.fire({ 
            icon: 'success', 
            title: 'Removido!', 
            text: 'Usuário excluído com sucesso.',
            background: '#070e1b', 
            color: '#fff',
            confirmButtonColor: '#3b82f6'
        });
    }
</script>

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