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

// Configuração de Resultados por Página (Filtro)
$limit_get = isset($_GET['limit']) ? $_GET['limit'] : 10;
$results_per_page = ($limit_get === 'all') ? 999999 : (int)$limit_get;

include '../includes/header2.php';

error_reporting(0);
$page = isset($_GET['view']) ? (int)$_GET['view'] : 1;

if (!isset($_GET['view']) && $_SESSION['aviso_seller'] == 0) {    
    $file_path = '../a/revenda_mensagem.json';
    if (file_exists($file_path)) {
        $file_content = file_get_contents($file_path);
        $data_array = json_decode($file_content, true);
        $titulo = $data_array['title'];
        $mensagem = $data_array['content'];
    }
    $_SESSION['aviso_seller'] = 1;
}

$seller_name = $_SESSION['seller_name'];
$start_from = ($page - 1) * $results_per_page;
$db1 = new SQLite3('../a/.eggziedb.db');

// --- LÓGICA DE PESQUISA E FILTROS ---
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$filterSeller = isset($_GET['f_seller']) ? $_GET['f_seller'] : '';

// Condição base: mostrar apenas o que pertence à revenda logada
$conditions = ["seller = '$seller_name'"];

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

$whereClause = "WHERE " . implode(" AND ", $conditions);

// Busca lista de vendedores para o filtro (apenas os que pertencem a este painel)
$sellersList = $db1->query("SELECT DISTINCT seller FROM ibo WHERE seller = '$seller_name' ORDER BY seller ASC");

// Contagem para Paginação
$resultCount = $db1->query("SELECT COUNT(id) AS total FROM ibo $whereClause");
$rowCount = $resultCount->fetchArray();
$totaleview = $rowCount['total'];
$total_pages = ceil($totaleview / $results_per_page);

// Query Final com todas as informações
$res1 = $db1->query("SELECT * FROM ibo $whereClause ORDER BY id DESC LIMIT $start_from, $results_per_page");

if (isset($_GET['delete'])) {
    $db1->exec('DELETE FROM ibo WHERE id=' . (int)$_GET['delete']);
    echo "<script>window.location.href='index.php';</script>";
    exit();
}
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Poppins:wght@300;400;600&display=swap');

    :root {
        --neon-emerald: #00ff88;
        --neon-gold: #ffcc00;
        --dark-bg: #050a0e;
        --glass-bg: rgba(255, 255, 255, 0.02);
        --glass-border: rgba(0, 255, 136, 0.15);
    }

    /* Blindagem total contra fundo branco */
    html, body, #wrapper, #content-wrapper, #content, .bg-white, .container-fluid, .card-body {
        background-color: var(--dark-bg) !important;
        color: #e0e0e0 !important;
    }

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

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

    .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-emerald) !important;
        text-shadow: 0 0 8px var(--neon-emerald);
        margin: 0;
        text-transform: uppercase;
    }

    /* Tabela Estilizada com todas as colunas */
    .table-modern { color: #e0e0e0 !important; border-collapse: separate; border-spacing: 0 8px; width: 100%; }
    .table-modern thead th { border: none !important; color: var(--neon-emerald); text-transform: uppercase; font-size: 0.65rem; padding: 12px; letter-spacing: 1px; }
    .table-modern tbody tr { background: rgba(255, 255, 255, 0.02); transition: 0.3s; }
    .table-modern tbody tr:hover { background: rgba(0, 255, 136, 0.05); transform: scale(1.002); }
    .table-modern td { border: none !important; padding: 12px !important; vertical-align: middle !important; font-size: 0.85rem; }

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

    .btn-emerald {
        background: transparent;
        border: 1px solid var(--neon-emerald);
        color: var(--neon-emerald) !important;
        font-family: 'Orbitron', sans-serif;
        font-size: 0.75rem;
        transition: 0.4s;
        text-transform: uppercase;
        padding: 8px 15px;
    }

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

    code { background: transparent; color: var(--neon-gold); font-weight: bold; padding: 0; }
    .small-dns { font-size: 0.7rem; opacity: 0.6; display: block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    
    /* Paginação */
    .pagination-neon { display: flex; gap: 5px; justify-content: center; margin-top: 20px; }
    .page-link-neon { background: #000; border: 1px solid var(--glass-border); color: #fff; padding: 6px 12px; border-radius: 4px; text-decoration: none; }
    .page-link-neon.active { border-color: var(--neon-emerald); color: var(--neon-emerald); background: rgba(0, 255, 136, 0.1); }
</style>

<div class="container-fluid 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> Painel de Usuários</h6>
            <span class="badge" style="border: 1px solid var(--neon-gold); color: var(--neon-gold);">Ativos: <?php echo $totaleview; ?></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" style="color: var(--neon-emerald)">Pesquisa Geral</label>
                        <input type="text" name="search" class="form-control form-control-futuristic" placeholder="MAC, Nome..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="small text-uppercase" style="color: var(--neon-emerald)">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" style="color: var(--neon-emerald)">Exibir</label>
                        <select name="limit" class="form-control form-control-futuristic" onchange="this.form.submit()">
                            <?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' ? 'Tudo' : "$o por pág."; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-5 text-right">
                        <button type="submit" class="btn btn-emerald"><i class="fas fa-filter mr-1"></i> Filtrar</button>
                        <a href="users_create.php" class="btn btn-emerald"><i class="fas fa-plus mr-1"></i> Ativar</a>
                    </div>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-modern">
                    <thead>
                        <tr>
                            <th>Título</th>
                            <th>MAC Address</th>
                            <th>Username</th>
                            <th>Vendedor</th>
                            <th>Validade</th>
                            <th>DNS</th>
                            <th>Extra</th>
                            <th class="text-center">Editar</th>
                            <th class="text-center">Deletar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row1 = $res1->fetchArray()): ?>
                            <tr>
                                <td class="font-weight-bold" style="color: #fff;"><?php echo $row1['title']; ?></td>
                                <td><code><?php echo $row1['mac_address']; ?></code></td>
                                <td><?php echo $row1['username']; ?></td>
                                <td><span class="badge" style="border: 1px solid #444; color: #aaa; background: transparent;"><?php echo $row1['seller']; ?></span></td>
                                <td><span class="text-warning"><?php echo $row1['expire_date']; ?></span></td>
                                <td><span class="small-dns" title="<?php echo $row1['url']; ?>"><?php echo $row1['url']; ?></span></td>
                                <td><small style="opacity: 0.5;"><?php echo $row1['extra']; ?></small></td>
                                <td class="text-center">
                                    <a href="./users_update.php?update=<?php echo $row1['id']; ?>">
                                        <i class="fas fa-edit" style="color: var(--neon-emerald); font-size: 1.1rem; text-shadow: 0 0 5px var(--neon-emerald);"></i>
                                    </a>
                                </td>
                                <td class="text-center">
                                    <a href="#" data-href="./index.php?delete=<?php echo $row1['id']; ?>" data-toggle="modal" data-target="#confirm-delete">
                                        <i class="fas fa-ban" style="color: #ff4b2b; font-size: 1.1rem; text-shadow: 0 0 5px #ff4b2b;"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_pages > 1 && $limit_get !== 'all'): ?>
                <div class="pagination-neon">
                    <?php 
                    $params = "&limit=$limit_get&search=".urlencode($searchTerm)."&f_seller=".urlencode($filterSeller);
                    if($page > 1) echo "<a href='?view=".($page-1)."$params' class='page-link-neon'>&laquo;</a>";
                    for($i=1; $i<=$total_pages; $i++) {
                        $active = ($i == $page) ? 'active' : '';
                        echo "<a href='?view=$i$params' class='page-link-neon $active'>$i</a>";
                    }
                    if($page < $total_pages) echo "<a href='?view=".($page+1)."$params' class='page-link-neon'>&raquo;</a>";
                    ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background: #0a0f14; border: 1px solid var(--neon-emerald); color: #fff;">
            <div class="modal-header border-0"><h5 style="font-family: 'Orbitron'; color: var(--neon-emerald);">Confirmar</h5></div>
            <div class="modal-body">Deseja remover permanentemente este usuário?</div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Sair</button>
                <a class="btn btn-danger btn-sm btn-ok">Excluir</a>
            </div>
        </div>
    </div>
</div>

<script>
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
</script>

<?php 
include '../includes/footer2.php';
require '../includes/egz2.php';
?>