<?php
session_start();
require '../conexao.php';

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

// Recupera filtros da URL para passar pro JS
$filtro_ordem = $_GET['ordem'] ?? 'valor_asc';
$filtro_dono = $_GET['dono'] ?? 'todos';
$paginaAtual = isset($_GET['pagina']) ? max(1, intval($_GET['pagina'])) : 1;

// Função auxiliar para links (será usada pelo JS na verdade, mas mantemos para os filtros)
function linkPagina($pag) {
    global $filtro_ordem, $filtro_dono;
    return "?pagina=$pag&ordem=$filtro_ordem&dono=$filtro_dono";
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mercado de Personagens - Mavilla</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../css/dashboard.css">
    
    <style>
        /* REUTILIZANDO O CSS NEON DEFINIDO ANTERIORMENTE */
        html, body { background: none !important; background-color: transparent !important; }
        body {
            background: url('../rpg-login-background.jpg') no-repeat center center fixed !important;
            background-size: cover !important;
            color: white;
            min-height: 100vh;
        }

        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }

        /* FILTROS */
        .filter-card {
            background-color: rgba(0, 5, 30, 0.9);
            border: 2px solid var(--primary);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 0 15px rgba(0, 0, 255, 0.2);
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
            justify-content: center;
        }
        .filter-group { display: flex; flex-direction: column; gap: 5px; }
        .filter-group label { color: #ccc; font-size: 0.8rem; font-weight: bold; }
        
        select.neon-input {
            background: #000; color: #fff; border: 1px solid var(--primary);
            padding: 8px; border-radius: 5px; outline: none; min-width: 150px;
        }
        .btn-filter {
            background: var(--primary); color: #fff; border: none; padding: 8px 20px;
            border-radius: 5px; cursor: pointer; font-weight: bold; text-transform: uppercase; height: 38px; align-self: flex-end;
        }
        .btn-filter:hover { background: #000; border: 1px solid var(--primary); box-shadow: 0 0 10px var(--neon-bright); }

        /* ESTILOS DA TABELA (Carregada via AJAX) */
        .table-container {
            overflow-x: auto;
            border: 2px solid var(--primary);
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,255,0.2);
            background: rgba(0, 0, 0, 0.85);
            animation: fadeIn 0.5s;
        }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

        table { width: 100%; border-collapse: collapse; color: white; }
        thead { background-color: rgba(0, 0, 255, 0.2); border-bottom: 2px solid var(--primary); }
        th { padding: 15px; text-align: center; text-transform: uppercase; font-size: 0.9rem; color: var(--neon-bright); text-shadow: 0 0 5px var(--primary); }
        td { padding: 12px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); font-size: 1rem; }
        tr:last-child td { border-bottom: none; }
        tr:hover { background-color: rgba(255,255,255,0.05); }
        
        .price-tag { color: #28a745; font-weight: bold; font-size: 1.1rem; text-shadow: 0 0 5px rgba(40,167,69,0.5); }
        .date-tag { color: #aaa; font-size: 0.8rem; font-style: italic; }
        .char-name { font-weight: bold; color: #fff; }

        .btn-table {
            padding: 6px 15px; border-radius: 4px; font-weight: bold; text-transform: uppercase;
            font-size: 0.8rem; cursor: pointer; border: 1px solid transparent; transition: 0.3s; background: transparent;
        }
        .btn-buy { color: #28a745; border-color: #28a745; }
        .btn-buy:hover { background: #28a745; color: #000; box-shadow: 0 0 15px #28a745; }
        .btn-cancel { color: #ff2222; border-color: #ff2222; }
        .btn-cancel:hover { background: #ff2222; color: #fff; box-shadow: 0 0 15px #ff2222; }

        /* Paginação */
        .pagination { display: flex; justify-content: center; gap: 8px; margin-top: 30px; flex-wrap: wrap; }
        .page-link {
            padding: 8px 12px; background: #000; border: 1px solid var(--primary); color: var(--primary);
            text-decoration: none; border-radius: 4px; font-weight: bold; font-size: 0.9rem;
        }
        .page-link:hover { background: var(--primary); color: #fff; box-shadow: 0 0 10px var(--primary); }
        .page-link.active { background: var(--primary); color: #fff; box-shadow: 0 0 15px var(--neon-bright); }
        .page-link.disabled { opacity: 0.5; pointer-events: none; border-color: #555; color: #555; }
        
        #loading-indicator { text-align: center; padding: 20px; color: var(--neon-bright); font-style: italic; display: none; }
    </style>
</head>
<body>

    <div class="container">
        
        <div class="listing-header-centered" style="text-align:center; margin-bottom:30px;">
            <h1 style="font-size: 2.5rem; color:var(--primary); text-shadow:0 0 15px var(--primary); margin-bottom: 20px;">
                PERSONAGENS À VENDA
            </h1>
            <a href="mercado.php">
                <button style="width: auto; padding: 10px 40px !important; background:#000; border:2px solid var(--primary); color:#fff; border-radius:8px; cursor:pointer; font-weight:bold;">Voltar ao Mercado</button>
            </a>
        </div>

        <form method="GET" class="filter-card">
            <div class="filter-group">
                <label>Ordenar Por:</label>
                <select name="ordem" class="neon-input">
                    <option value="valor_asc" <?= $filtro_ordem == 'valor_asc' ? 'selected' : '' ?>>Menor Preço (Barato)</option>
                    <option value="valor_desc" <?= $filtro_ordem == 'valor_desc' ? 'selected' : '' ?>>Maior Preço (Caro)</option>
                    <option value="data_desc" <?= $filtro_ordem == 'data_desc' ? 'selected' : '' ?>>Mais Recentes</option>
                </select>
            </div>

            <div class="filter-group">
                <label>Exibir:</label>
                <select name="dono" class="neon-input">
                    <option value="todos" <?= $filtro_dono == 'todos' ? 'selected' : '' ?>>Todos os Personagens</option>
                    <option value="ocultar_meus" <?= $filtro_dono == 'ocultar_meus' ? 'selected' : '' ?>>Ocultar os Meus</option>
                    <option value="somente_meus" <?= $filtro_dono == 'somente_meus' ? 'selected' : '' ?>>Somente os Meus</option>
                </select>
            </div>

            <button type="submit" class="btn-filter"><i class="fas fa-filter"></i> Filtrar</button>
        </form>

        <div id="loading-indicator"><i class="fas fa-sync fa-spin"></i> Atualizando lista...</div>

        <div id="lista-vendas-container"></div>

        <div id="paginacao-container" class="pagination"></div>

    </div>

    <script>
        // Pega os parâmetros atuais da URL
        const params = new URLSearchParams(window.location.search);
        const ordem = params.get('ordem') || 'valor_asc';
        const dono = params.get('dono') || 'todos';
        const pagina = params.get('pagina') || 1;

        function carregarTabela() {
            // Mostra loading sutil
            // document.getElementById('loading-indicator').style.display = 'block';

            fetch(`api_vendas.php?ordem=${ordem}&dono=${dono}&pagina=${pagina}`)
                .then(response => response.text())
                .then(html => {
                    // Separa o HTML da tabela dos dados de paginação (gambiarra segura)
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = html;
                    
                    const tabela = tempDiv.querySelector('.table-container');
                    const pagData = tempDiv.querySelector('#paginacao-data');
                    
                    if (tabela) {
                        document.getElementById('lista-vendas-container').innerHTML = tabela.outerHTML;
                    } else {
                         document.getElementById('lista-vendas-container').innerHTML = html; // Mensagem de vazio
                    }

                    if (pagData) {
                        atualizarPaginacao(parseInt(pagData.dataset.total), parseInt(pagData.dataset.atual));
                    }
                    
                    // document.getElementById('loading-indicator').style.display = 'none';
                })
                .catch(err => console.error("Erro ao atualizar:", err));
        }

        function atualizarPaginacao(totalPaginas, paginaAtual) {
            const container = document.getElementById('paginacao-container');
            if (totalPaginas <= 1) {
                container.innerHTML = '';
                return;
            }

            let html = '';
            
            // Botão Anterior
            if (paginaAtual > 1) {
                html += `<a href="?pagina=1&ordem=${ordem}&dono=${dono}" class="page-link">«</a>`;
                html += `<a href="?pagina=${paginaAtual - 1}&ordem=${ordem}&dono=${dono}" class="page-link">‹</a>`;
            } else {
                html += `<span class="page-link disabled">«</span>`;
                html += `<span class="page-link disabled">‹</span>`;
            }

            // Paginas Numeradas (Simplificado: Atual / Total)
            html += `<span class="page-link active">${paginaAtual} / ${totalPaginas}</span>`;

            // Botão Próximo
            if (paginaAtual < totalPaginas) {
                html += `<a href="?pagina=${paginaAtual + 1}&ordem=${ordem}&dono=${dono}" class="page-link">›</a>`;
                html += `<a href="?pagina=${totalPaginas}&ordem=${ordem}&dono=${dono}" class="page-link">»</a>`;
            } else {
                html += `<span class="page-link disabled">›</span>`;
                html += `<span class="page-link disabled">»</span>`;
            }

            container.innerHTML = html;
        }

        // Carrega imediatamente
        carregarTabela();

        // Atualiza a cada 3 segundos (Real-Time Simulado)
        setInterval(carregarTabela, 3000);
    </script>

</body>
</html>