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

// LÓGICA DE EXCLUSÃO (Processa antes do HTML)
if (isset($_GET["delete"])) {
    if (!isset($_GET['token']) || !hash_equals($_SESSION['admin_token'], $_GET['token'])) {
        header("Location: login.php"); 
        exit();
    }

    $delete_id = $_GET['delete'];
    
    $db_panel = new SQLite3("./api/.anspanel.db");
    $db_panel->exec("DELETE FROM USERS WHERE id= '$delete_id'");
    $db_panel->close();

    $db_user = new SQLite3("./api/.ansdb.db");
    $db_user->exec("DELETE FROM ibo WHERE id_user = '$delete_id'");
    $db_user->close();

    header("Location: stores.php?status=deleted");
    exit();
}

include "includes/header.php";

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}
?>

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

    /* OCULTAR ELEMENTOS DO HEADER */
    .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;
    }

    /* CARD PREMIUM */
    .premium-card {
        background: #070e1b !important;
        border: 1px solid #1e293b !important;
        border-radius: 20px;
        padding: 15px;
        box-shadow: 0 10px 25px rgba(0,0,0,0.3);
        box-sizing: border-box; /* Garante que o padding não estoure o card */
    }

    .header-section { margin-bottom: 20px; }
    .header-section h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
    .header-section p { color: #64748b; font-size: 0.8rem; }

    /* BOTÃO NOVA REVENDA */
    .btn-premium-add {
        width: 100%; margin-top: 15px; padding: 16px; border-radius: 14px;
        background: #10b981 !important; color: #fff !important;
        font-weight: 800; font-size: 0.85rem; text-transform: uppercase;
        display: flex; align-items: center; justify-content: center; gap: 10px;
        text-decoration: none !important; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.2);
        box-sizing: border-box; /* Fix para não sair da direita */
    }

    /* BARRA DE PESQUISA */
    .search-wrapper { position: relative; margin: 20px 0; width: 100%; }
    .search-box {
        width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important;
        color: #fff; padding: 15px 15px 15px 45px; border-radius: 12px; font-size: 0.9rem;
        box-sizing: border-box; /* Fix para não sair da direita */
    }
    .search-wrapper i { position: absolute; left: 18px; top: 18px; color: #475569; }

    /* TABELA RESPONSIVA COM ROLAGEM */
    .table-responsive {
        width: 100% !important; display: block !important;
        overflow-x: auto !important; -webkit-overflow-scrolling: touch;
        border-radius: 12px; border: 1px solid rgba(255,255,255,0.05);
        box-sizing: border-box;
    }
    .table-responsive::-webkit-scrollbar { height: 4px; }
    .table-responsive::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 10px; }

    .table { margin: 0; min-width: 850px; color: #cbd5e1; width: 100%; }
    .table th { background: #0f172a; color: #10b981; padding: 15px; font-size: 0.7rem; text-transform: uppercase; border: none; }
    .table td { border-top: 1px solid rgba(255,255,255,0.03); padding: 16px; vertical-align: middle; font-size: 0.85rem; }

    /* BADGES E BOTÕES */
    .badge-mac-limit { background: rgba(16, 185, 129, 0.1); color: #10b981; padding: 5px 12px; border-radius: 8px; font-weight: 800; }
    
    .action-btns { display: flex; gap: 8px; }
    .btn-act { width: 38px; height: 38px; display: flex; align-items: center; justify-content: center; border-radius: 10px; transition: 0.2s; }
    .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); }
</style>

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

    <div class="premium-card">
        <div class="header-section">
            <h1>Gestão de Revendas</h1>
            <p>Controle de lojas e limites de usuários</p>
            
            <a href="stores_create.php" class="btn-premium-add">
                <i class="fas fa-plus-circle"></i> Nova Revenda
            </a>
        </div>

        <div class="search-wrapper">
            <i class="fas fa-search"></i>
            <input type="text" id="search" class="search-box" placeholder="Pesquisar loja ou usuário...">
        </div>

        <div class="table-responsive">
            <table class="table" id="myTable">
                <thead>
                    <tr>
                        <th width="50">ID</th>
                        <th>NOME / LOJA</th>
                        <th>USUÁRIO</th>
                        <th>SENHA</th>
                        <th class="text-center">LIMITE MACS</th>
                        <th class="text-center">AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $db = new SQLite3("./api/.anspanel.db");
                    $res = $db->query("SELECT * FROM USERS WHERE (ADMIN != 1 OR ADMIN IS NULL) AND store_type = 1 ORDER BY id DESC");
                    while ($row = $res->fetchArray()):
                        $id = $row["id"];
                    ?>
                    <tr>
                        <td><span style="color: #64748b;">#<?= $id ?></span></td>
                        <td style="font-weight: 800; color: #fff;"><?= htmlspecialchars($row["NAME"]) ?></td>
                        <td><span style="color: #3b82f6; font-weight: 600;"><?= htmlspecialchars($row["USERNAME"]) ?></span></td>
                        <td style="font-family: monospace; letter-spacing: 1px;"><?= htmlspecialchars($row["PASSWORD"]) ?></td>
                        <td class="text-center"><span class="badge-mac-limit"><?= $row["mac_amount"] ?></span></td>
                        <td>
                            <div class="action-btns">
                                <a href="./stores_update.php?update=<?= $id ?>" class="btn-act btn-act-edit">
                                    <i class="fas fa-pen-nib"></i>
                                </a>
                                <button onclick="confirmDelete(<?= $id ?>)" class="btn-act btn-act-del">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </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
    $("#search").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#myTable tbody tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

    // ALERTAS PREMIUM
    const swalConfig = { background: '#070e1b', color: '#fff' };
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('status') === 'deleted') {
        Swal.fire({ ...swalConfig, icon: 'success', title: 'Removido!', text: 'Revendedor e clientes excluídos.', confirmButtonColor: '#10b981' });
    }

    // FUNÇÃO DE EXCLUSÃO
    function confirmDelete(id) {
        Swal.fire({
            ...swalConfig,
            title: 'Excluir Revenda?',
            text: "Atenção: Todos os clientes deste revendedor também serão apagados!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#1e293b',
            confirmButtonText: 'Sim, Apagar Tudo',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'stores.php?delete=' + id + '&token=<?= $_SESSION['admin_token'] ?>';
            }
        });
    }
</script>

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