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

// INCLUI O MOTOR DE LOGS
include_once 'api/db/logs_helper.php';

ini_set("display_errors", 0);
$db = new SQLite3("./api/.ansdb.db"); 

// LÓGICA DE EXCLUSÃO
if (isset($_GET["delete"])) {
    $id_del = $_GET["delete"];

    // --- BUSCA DADOS PARA O LOG ANTES DE APAGAR ---
    $res_info = $db->query("SELECT title, mac_address FROM ibo WHERE id=$id_del");
    $info = $res_info->fetchArray(SQLITE3_ASSOC);
    
    if ($info) {
        $nome_cliente = $info['title'];
        $mac_cliente = $info['mac_address'];
        $quem_fez = $_SESSION['NAME'] ?? "Revendedor ID: " . $_SESSION['id'];
        
        // REGISTRA A EXCLUSÃO
        registrar_log($quem_fez, "EXCLUIU CLIENTE: $nome_cliente | MAC: $mac_cliente");
    }

    $db->exec("DELETE FROM ibo WHERE id=$id_del");
    header("Location: users.php?status=deleted");
    exit();
}

include "includes/header.php";
?>

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

    /* FUNDO TOTAL DARK - CORREÇÃO DE ROLAGEM */
    html, body { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
        margin: 0;
        padding: 0;
        width: 100%;
        overflow-x: hidden; 
    }

    .main-panel, .content, .wrapper {
        background-color: #020617 !important;
        width: 100%;
    }

    .container-fluid { 
        padding: 15px !important; 
        width: 100%;
        max-width: 100%;
    }

    /* 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;
    }

    /* CARD PRINCIPAL */
    .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.3);
        width: 100%;
        margin-bottom: 40px;
    }

    .header-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
        margin-bottom: 20px;
    }

    .header-section h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    
    .row-buttons { display: flex; gap: 10px; }
    
    .btn-premium-action {
        padding: 12px 20px; border-radius: 12px; font-weight: 700; font-size: 0.75rem;
        text-transform: uppercase; text-decoration: none !important;
        display: flex; align-items: center; justify-content: center; gap: 8px;
    }
    .btn-add { background: #3b82f6 !important; color: #fff !important; }
    .btn-view { background: rgba(59, 130, 246, 0.1) !important; color: #3b82f6 !important; border: 1px solid rgba(59, 130, 246, 0.2) !important; }

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

    .table-responsive-custom {
        width: 100%;
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch; 
        border-radius: 15px;
        border: 1px solid rgba(255,255,255,0.05);
        margin-bottom: 10px;
    }

    .table { 
        margin: 0; 
        width: 100%; 
        min-width: 800px; 
        color: #cbd5e1; 
        background: transparent !important;
        border-collapse: collapse;
    }

    .table thead th { 
        background: #0f172a !important; 
        color: #3b82f6 !important; 
        padding: 18px 15px; 
        font-size: 0.7rem; 
        text-transform: uppercase; 
        border: none;
        white-space: nowrap;
    }

    .table tbody td { 
        border-top: 1px solid rgba(255,255,255,0.03); 
        padding: 15px; 
        vertical-align: middle;
        white-space: nowrap; 
    }

    /* AÇÕES */
    .action-btns { display: flex; gap: 8px; }
    .btn-act { 
        width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; 
        border-radius: 10px; text-decoration: none !important;
    }
    /* STATUS REMOVIDO DO CSS */
    .btn-act-msg { background: rgba(245, 158, 11, 0.1); color: #f59e0b; border: 1px solid rgba(245, 158, 11, 0.2); }
    .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); border: none; cursor: pointer; }

    .expire-badge { padding: 5px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: 700; }

    @media (max-width: 768px) {
        .header-section { flex-direction: column; align-items: flex-start; }
        .row-buttons { width: 100%; }
        .row-buttons a { flex: 1; }
    }
</style>

<div class="container-fluid">
    <a href="index.php" class="btn-back-nav"><i class="fas fa-chevron-left"></i> Voltar ao Início</a>

    <div class="premium-card">
        <div class="header-section">
            <div>
                <h1>Meus Clientes</h1>
                <p style="color: #64748b; font-size: 0.8rem; margin: 0;">Gerencie as ativações</p>
            </div>
            <div class="row-buttons">
                <a href="./users_create.php" class="btn-premium-action btn-add"><i class="fas fa-plus"></i> Novo</a>
                <a href="./all_users.php" class="btn-premium-action btn-view"><i class="fas fa-users"></i> Todos</a>
            </div>
        </div>

        <div class="search-wrapper">
            <i class="fas fa-search"></i>
            <input type="text" id="search" class="search-box" placeholder="Procurar cliente...">
        </div>

        <div class="table-responsive-custom">
            <table class="table" id="myTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>MAC ADDRESS</th>
                        <th>NOME</th>
                        <th>VENCIMENTO</th>
                        <th>AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $id_user_session = $_SESSION['id'];
                    $res = $db->query("SELECT * FROM ibo WHERE id_user = '$id_user_session' ORDER BY id DESC");
                    while ($row = $res->fetchArray()):
                        $is_expired = strtotime($row['expire_date']) < time();
                    ?>
                    <tr>
                        <td><span style="color: #475569; font-size: 0.75rem;"><?= $row['id'] ?></span></td>
                        <td style="font-family: monospace; font-weight: 700; color: #fff;"><?= strtoupper($row['mac_address']) ?></td>
                        <td><?= htmlspecialchars($row['title']) ?></td>
                        <td>
                            <span class="expire-badge" style="background: <?= $is_expired ? 'rgba(239, 68, 68, 0.1)' : 'rgba(34, 197, 94, 0.1)' ?>; color: <?= $is_expired ? '#ef4444' : '#22c55e' ?>;">
                                <?= date('d/m/Y', strtotime($row['expire_date'])) ?>
                            </span>
                        </td>
                        <td>
                            <div class="action-btns">
                                <a href="panaci_gerenciar_notemac.php?mac=<?= $row['mac_address'] ?>" class="btn-act btn-act-msg" title="Notificação"><i class="fas fa-bell"></i></a>
                                <a href="users_update.php?update=<?= $row['id'] ?>" class="btn-act btn-act-edit" title="Editar"><i class="fas fa-pen"></i></a>
                                <button onclick="confirmDelete(<?= $row['id'] ?>)" class="btn-act btn-act-del" title="Excluir"><i class="fas fa-trash-alt"></i></button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
        <p style="color: #475569; font-size: 0.7rem; margin-top: 10px;" class="text-center d-block d-md-none">
            <i class="fas fa-arrows-alt-h mr-1"></i> Deslize para o lado para ver mais
        </p>
    </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>
    $("#search").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#myTable tbody tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

    function confirmDelete(id) {
        Swal.fire({
            title: 'Excluir?', text: "Esta ação não pode ser desfeita!", icon: 'warning',
            background: '#070e1b', color: '#fff', showCancelButton: true,
            confirmButtonColor: '#ef4444', confirmButtonText: 'Sim, excluir!', cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) { window.location.href = 'users.php?delete=' + id; }
        });
    }
</script>

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