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

// LÓGICA DE EXCLUSÃO
if (isset($_GET["delete"])) {
    $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_mac.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: #f59e0b; font-size: 0.8rem; font-weight: 600; }

    /* BOTÃO NOVA REVENDA ANUAL */
    .btn-premium-gold {
        width: 100%; margin-top: 15px; padding: 16px; border-radius: 14px;
        background: #f59e0b !important; color: #000 !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(245, 158, 11, 0.2);
        box-sizing: border-box; /* FIX: LARGURA EXATA */
    }

    /* BARRA DE PESQUISA */
    .search-wrapper { position: relative; margin: 20px 0; width: 100%; box-sizing: border-box; }
    .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: LARGURA EXATA */
    }
    .search-wrapper i { position: absolute; left: 18px; top: 18px; color: #475569; }

    /* TABELA RESPONSIVA */
    .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: 900px; color: #cbd5e1; width: 100%; }
    .table th { background: #0f172a; color: #f59e0b; 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; }

    /* AÇÕES CENTRALIZADAS */
    .action-btns { 
        display: flex !important; 
        gap: 8px !important; 
        justify-content: center !important; 
        align-items: center !important;
        width: 100% !important;
    }
    .btn-act { 
        width: 38px; 
        height: 38px; 
        display: flex; 
        align-items: center; 
        justify-content: center; 
        border-radius: 10px; 
        transition: 0.2s; 
        text-decoration: none !important;
    }
    .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-radius: 10px; cursor: pointer; }

    /* BADGES */
    .badge-credits { background: rgba(255, 255, 255, 0.05); color: #fff; padding: 5px 12px; border-radius: 8px; font-weight: 700; font-family: monospace; }
    .badge-available { background: rgba(16, 185, 129, 0.15); color: #10b981; padding: 5px 12px; border-radius: 8px; font-weight: 800; }
</style>

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

    <div class="premium-card">
        <div class="header-section">
            <h1>Revendas Anuais</h1>
            <p><i class="fas fa-crown mr-1"></i> Modelo por Ativação/Créditos</p>
            
            <a href="stores_create.php" class="btn-premium-gold">
                <i class="fas fa-plus-circle"></i> Criar Revenda Anual
            </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>LOJA / REVENDEDOR</th>
                        <th>USUÁRIO</th>
                        <th class="text-center">TOTAL CRÉDITOS</th>
                        <th class="text-center">DISPONÍVEIS</th>
                        <th class="text-center">AÇÕES</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $db = new SQLite3("./api/.anspanel.db");
                    $db2 = new SQLite3("./api/.ansdb.db");
                    $res = $db->query("SELECT * FROM USERS WHERE (ADMIN != 1 OR ADMIN IS NULL) AND store_type = 2 ORDER BY id DESC");
                    while ($row = $res->fetchArray()):
                        $id = $row["id"];
                        $macs = $row["mac_amount"];
                        
                        $macsUsed = $db2->query("SELECT COUNT(*) as count FROM ibo WHERE id_user = '$id' AND active = 1 AND expire_date > date('now')");
                        $countUsed = $macsUsed->fetchArray()['count'];
                        $macsAvailable = $macs - $countUsed;
                    ?>
                    <tr>
                        <td><span style="color: #475569;">#<?= $id ?></span></td>
                        <td style="font-weight: 800; color: #fff;"><?= htmlspecialchars($row["NAME"]) ?></td>
                        <td><span style="color: #64748b; font-weight: 600;"><?= htmlspecialchars($row["USERNAME"]) ?></span></td>
                        <td class="text-center"><span class="badge-credits"><?= $macs ?></span></td>
                        <td class="text-center"><span class="badge-available"><?= $macsAvailable ?></span></td>
                        <td class="text-center">
                            <div class="action-btns">
                                <a href="stores_update.php?update=<?= $id ?>" class="btn-act btn-act-edit">
                                    <i class="fas fa-edit"></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>
    $("#search").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $("#myTable tbody tr").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

    const swalConfig = { background: '#070e1b', color: '#fff' };
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('status') === 'deleted') {
        Swal.fire({ ...swalConfig, icon: 'success', title: 'Excluído!', text: 'Revendedor removido com sucesso.', confirmButtonColor: '#f59e0b' });
    }

    function confirmDelete(id) {
        Swal.fire({
            ...swalConfig,
            title: 'Remover Revenda?',
            text: "CUIDADO: Isso apagará todas as ativações deste revendedor!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#1e293b',
            confirmButtonText: 'Sim, Apagar Tudo',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'stores_mac.php?delete=' + id;
            }
        });
    }
</script>

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