<?php
// Configurações e Sessão
session_start();

// --- INCLUSÕES ESSENCIAIS ---
// ATENÇÃO: Verifique se esses arquivos existem e estão no caminho correto.
require_once 'includes/conexao.php'; 
// ----------------------------

// Título da Página
$page_title = "Ranking - Pokemon Relics";

// --- 1. CONFIGURAÇÕES DO RANKING ---
$limit = 20; // Players por página
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$offset = ($page - 1) * $limit;
$type = isset($_GET['type']) ? $_GET['type'] : 'level';

// Usuário Logado (para destaque)
$loggedName = isset($_SESSION['character_name']) ? $_SESSION['character_name'] : null;

// Definição dos Tipos de Ranking (SIMPLIFICADO: APENAS LEVEL, FISHING E CATCH)
$rankingTypes = [
    'level'      => ['title' => 'Top Level', 'column' => 'experience', 'display' => 'level', 'icon' => 'fas fa-trophy'],
    'fishing'    => ['title' => 'Fishing Skill', 'column' => 'skill_fishing', 'display' => 'skill_fishing', 'icon' => 'fas fa-fish'],
    'catch'      => ['title' => 'Total Catchs', 'column' => 'catch_count', 'display' => 'catch_count', 'icon' => 'fas fa-dot-circle'],
    // Pokedex e Tournament removidos dos botões, mas mantidos na lógica caso o usuário tente o link direto
    'pokedex'    => ['title' => 'Pokedex', 'column' => 'pokedex_count', 'display' => 'pokedex_count', 'icon' => 'fas fa-book'],
    'tournament' => ['title' => 'Vitorias', 'column' => 'tournament_wins', 'display' => 'tournament_wins', 'icon' => 'fas fa-medal']
];

// Array simplificado para exibição dos botões
$menuTypes = [
    'level' => $rankingTypes['level'],
    'fishing' => $rankingTypes['fishing'],
    'catch' => $rankingTypes['catch']
];

// Validação de Segurança
if (!array_key_exists($type, $rankingTypes)) $type = 'level';
$cfg = $rankingTypes[$type];
$orderBy = $cfg['column'];
$displayCol = $cfg['display'];

// --- 2. CONSULTA AO BANCO DE DADOS ---
$players = [];
$error = null;
$totalPages = 1;

if (isset($pdo) && $pdo instanceof PDO) {
    try {
        // Query Principal: Incluindo 'online' e 'premdays' (VIP/Free status)
        $sql = "SELECT p.id, p.name, p.level, p.looktype, p.lookhead, p.lookbody, p.looklegs, p.lookfeet, 
                       p.skill_fishing, p.catch_count, p.level, 
                       p.$orderBy as stat_val, p.$displayCol as display_val,
                       a.premdays, p.online, 
                       g.name as guild_name 
                 FROM players p
                 LEFT JOIN accounts a ON p.account_id = a.id
                 LEFT JOIN guild_membership gm ON p.id = gm.player_id
                 LEFT JOIN guilds g ON gm.guild_id = g.id
                 WHERE p.group_id < 2 AND p.deleted = 0 AND p.name LIKE :search
                 ORDER BY p.$orderBy DESC 
                 LIMIT :limit OFFSET :offset";

        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':search', "%$search%");
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        $players = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Contagem Total (Paginação)
        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM players WHERE group_id < 2 AND deleted = 0 AND name LIKE ?");
        $countStmt->execute(["%$search%"]);
        $totalPlayers = $countStmt->fetchColumn();
        $totalPages = ceil($totalPlayers / $limit);

    } catch (PDOException $e) {
        $players = [];
        $error = "Erro ao carregar ranking. Verifique a conexão com o banco de dados ou a query.";
    }
} else {
    $error = "Erro fatal: A variável \$pdo não foi definida em 'includes/conexao.php'.";
}

// --- INCLUINDO O HEADER ---
include 'includes/header.php'; 
?>

<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@400;700;800&display=swap">

<style>
    /* --- CONFIGURAÇÕES DE CORES E BASE --- */
    :root {
        --bg-dark: #0f172a;
        --bg-card: #1e293b;
        --primary: #3b82f6;
        --primary-glow: rgba(59, 130, 246, 0.5);
        --accent: #f59e0b; /* Gold */
        --accent-silver: #94a3b8; /* Silver */
        --accent-bronze: #b45309; /* Bronze */
        --text-main: #f1f5f9;
        --text-muted: #94a3b8;
        --status-vip: #10b981; /* Esmeralda/Verde */
        --status-free: #64748b; /* Cinza para Free */
        --status-online: #22c55e; /* Verde para Online */
        --status-offline: #ef4444; /* Vermelho para Offline */
    }

    body {
        background-color: #0b1120;
        color: var(--text-main);
        overflow-x: hidden !important;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    /* HEADER */
    .page-header {
        background: linear-gradient(180deg, rgba(15,23,42,0.9) 0%, rgba(15,23,42,1) 100%), url('images/hero-bg.jpg') center/cover;
        padding: 60px 0 40px 0;
        text-align: center;
        border-bottom: 1px solid rgba(255,255,255,0.05);
        margin-top: -20px;
    }
    
    .page-title {
        font-family: 'Rajdhani', sans-serif;
        font-size: 3.5rem;
        font-weight: 800;
        background: linear-gradient(to right, #fff, #93c5fd);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-shadow: 0 0 30px rgba(59, 130, 246, 0.3);
        margin-bottom: 10px;
    }

    /* FILTROS E NAVEGAÇÃO */
    .ranking-nav {
        background: var(--bg-card);
        border: 1px solid rgba(255,255,255,0.05);
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 30px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.2);
    }

    .btn-rank-filter {
        background: transparent;
        border: 1px solid rgba(255,255,255,0.1);
        color: var(--text-muted);
        padding: 10px 20px;
        border-radius: 50px;
        font-weight: 600;
        transition: all 0.3s;
        text-transform: uppercase;
        font-size: 0.85rem;
        margin: 5px;
    }
    .btn-rank-filter:hover, .btn-rank-filter.active {
        background: var(--primary);
        color: white;
        border-color: var(--primary);
        box-shadow: 0 0 15px var(--primary-glow);
        transform: translateY(-2px);
    }

    /* TABELA DE RANKING CUSTOMIZADA */
    .ranking-card {
        background: var(--bg-card);
        border-radius: 16px;
        border: 1px solid rgba(255,255,255,0.05);
        overflow: hidden;
        box-shadow: 0 10px 30px rgba(0,0,0,0.2);
    }

    .table-custom {
        width: 100%;
        border-collapse: collapse;
        color: var(--text-main);
    }
    
    .table-custom thead {
        background: rgba(0,0,0,0.3);
        border-bottom: 2px solid rgba(255,255,255,0.05);
    }
    
    .table-custom th {
        padding: 20px;
        text-transform: uppercase;
        font-size: 0.8rem;
        letter-spacing: 1px;
        color: var(--text-muted);
        font-weight: 700;
    }

    .table-custom tbody tr {
        border-bottom: 1px solid rgba(255,255,255,0.02);
        transition: background 0.2s;
    }

    .table-custom tbody tr:hover {
        background: rgba(59, 130, 246, 0.05);
    }

    /* DESTAQUE PARA USUÁRIO LOGADO */
    .is-me {
        background: rgba(245, 158, 11, 0.1) !important;
        border-left: 3px solid var(--accent);
    }

    .table-custom td {
        padding: 15px 20px;
        vertical-align: middle;
    }

    /* OUTFIT/AVATAR - (Letra Inicial no Círculo) */
    .outfit-display {
        width: 64px;
        height: 64px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
        border-radius: 50%;
        background: linear-gradient(135deg, var(--primary), #1e40af);
        border: 3px solid rgba(255,255,255,0.2);
        box-shadow: 0 0 15px var(--primary-glow);
        position: relative;
    }
    .outfit-display .initial-letter {
        color: white;
        font-size: 2.2rem;
        font-weight: 800;
        font-family: 'Rajdhani', sans-serif;
        text-shadow: 0 2px 5px rgba(0,0,0,0.5);
    }
    
    /* BADGES DE POSIÇÃO */
    .rank-badge {
        font-family: 'Rajdhani', sans-serif;
        font-weight: 800;
        font-size: 1.2rem;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background: rgba(255,255,255,0.05);
        margin: 0 auto;
    }
    .rank-1 { color: var(--accent); background: rgba(245, 158, 11, 0.1); box-shadow: 0 0 10px rgba(245, 158, 11, 0.2); font-size: 1.5rem; }
    .rank-2 { color: var(--accent-silver); background: rgba(148, 163, 184, 0.1); font-size: 1.3rem; }
    .rank-3 { color: var(--accent-bronze); background: rgba(180, 83, 9, 0.1); font-size: 1.3rem; }

    /* NOME DO JOGADOR - REMOVE DESTAQUE NA PRIMEIRA LETRA */
    .player-name-link {
        font-size: 1.3rem;
        font-weight: 600;
        color: var(--text-main);
        transition: color 0.2s;
    }
    .player-name-link:hover {
        color: var(--primary);
    }
    
    /* STATUS BADGES MELHORADOS */
    .status-badge {
        font-size: 0.7rem;
        font-weight: bold;
        padding: 3px 8px;
        border-radius: 5px;
        margin-right: 4px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        display: inline-block; /* Garante que os badges se alinhem bem */
        box-shadow: 0 0 5px rgba(0,0,0,0.3);
    }
    .status-badge.online { background: var(--status-online); color: white; }
    .status-badge.offline { background: var(--status-offline); color: white; }
    .status-badge.vip { background: var(--status-vip); color: white; }
    .status-badge.free { background: var(--status-free); color: white; }


    /* PAGINAÇÃO DARK */
    .pagination .page-link {
        background: var(--bg-card);
        border: 1px solid rgba(255,255,255,0.1);
        color: var(--text-main);
        margin: 0 2px;
        border-radius: 4px;
    }
    .pagination .page-link:hover, .pagination .active .page-link {
        background: var(--primary);
        border-color: var(--primary);
        color: white;
    }

    /* INPUT DE BUSCA ESTILIZADO */
    .search-input {
        background: rgba(0,0,0,0.3);
        border: 1px solid rgba(255,255,255,0.1);
        color: white;
        padding: 10px 15px;
        border-radius: 50px;
        padding-right: 40px;
    }
    .search-input:focus {
        background: rgba(0,0,0,0.5);
        border-color: var(--primary);
        outline: none;
        box-shadow: 0 0 10px var(--primary-glow);
    }

    /* MOBILE ADJUSTMENTS */
    @media (max-width: 768px) {
        .page-title { font-size: 2.5rem; }
        .btn-rank-filter { font-size: 0.7rem; padding: 8px 12px; margin: 2px; }
        .table-custom th, .table-custom td { padding: 10px 5px; font-size: 0.9rem; }
        .hide-mobile { display: none; }
        .outfit-display { width: 50px; height: 50px; }
        .outfit-display .initial-letter { font-size: 1.8rem; }
        .player-name-link { font-size: 1.1rem; }
    }
</style>

<div class="page-header">
    <div class="container" data-aos="fade-down">
        <h1 class="page-title">RANKING GLOBAL</h1>
        <p class="text-muted">Conheça as lendas vivas do servidor</p>
        
        <?php if(isset($_SESSION['account_id'])): ?>
            <a href="logout.php" class="btn btn-outline-danger btn-sm px-4 rounded-pill mt-3">
                <i class="fas fa-sign-out-alt me-2"></i> SAIR DA CONTA
            </a>
        <?php endif; ?>
    </div>
</div>

<div class="container my-5">
    <?php if ($error): ?>
        <div class="alert alert-danger" role="alert">
            <p>**ERRO:** <?php echo $error; ?></p>
        </div>
    <?php endif; ?>

    <div class="ranking-nav" data-aos="fade-up">
        <div class="row align-items-center gy-3">
            <div class="col-lg-8">
                <div class="d-flex flex-wrap justify-content-center justify-content-lg-start">
                    <?php foreach($menuTypes as $key => $data): // Menu simplificado ?>
                        <a href="?type=<?php echo $key; ?>" class="btn-rank-filter <?php echo ($type == $key) ? 'active' : ''; ?>">
                            <i class="<?php echo $data['icon']; ?> me-1"></i> <?php echo $data['title']; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="col-lg-4">
                <form action="" method="GET" class="position-relative">
                    <input type="hidden" name="type" value="<?php echo $type; ?>">
                    <input type="text" name="search" class="form-control search-input" placeholder="Buscar treinador..." value="<?php echo htmlspecialchars($search); ?>">
                    <button type="submit" class="btn position-absolute top-50 end-0 translate-middle-y text-muted pe-3">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="ranking-card" data-aos="fade-up" data-aos-delay="100">
        <div class="table-responsive">
            <table class="table-custom">
                <thead>
                    <tr>
                        <th class="text-center" width="80">Posição</th>
                        <th class="text-center" width="100">Avatar</th>
                        <th>Nome</th>
                        <th class="hide-mobile">Guilda</th>
                        <th class="text-center">Status (<?php echo $cfg['title']; ?>)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($players) > 0): ?>
                        <?php 
                        $rank = $offset + 1;
                        foreach($players as $p): 
                            
                            // Letra Inicial para o Avatar
                            $initialLetter = strtoupper(mb_substr($p['name'], 0, 1, 'UTF-8'));
                            
                            // Classes de Destaque
                            $rankClass = 'rank-badge';
                            if($rank == 1) $rankClass .= ' rank-1';
                            elseif($rank == 2) $rankClass .= ' rank-2';
                            elseif($rank == 3) $rankClass .= ' rank-3';

                            // É o usuário logado?
                            $isMeClass = ($loggedName == $p['name']) ? 'is-me' : '';

                            // Status
                            // Checa se premdays é maior que 0 E se a data de expiração (premdays * 86400) é maior que a hora atual (time())
                            $isVip = ($p['premdays'] > 0) && ($p['premdays'] > (time() / 86400));
                            $isOnline = ($p['online'] == 1);
                        ?>
                        <tr class="<?php echo $isMeClass; ?>">
                            <td class="text-center">
                                <div class="<?php echo $rankClass; ?>">
                                    <?php echo $rank; ?>
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="outfit-display">
                                    <span class="initial-letter"><?php echo $initialLetter; ?></span>
                                </div>
                            </td>
                            <td>
                                <a href="character.php?name=<?php echo urlencode($p['name']); ?>" class="text-decoration-none player-name-link">
                                    <?php echo htmlspecialchars($p['name']); ?>
                                </a>
                                <div class="small mt-1">
                                    <?php if($isOnline): ?>
                                        <span class="status-badge online">ONLINE</span>
                                    <?php else: ?>
                                        <span class="status-badge offline">OFFLINE</span>
                                    <?php endif; ?>
                                    
                                    <?php if($isVip): ?>
                                        <span class="status-badge vip"><i class="fas fa-crown"></i> VIP ACCOUNT</span>
                                    <?php else: ?>
                                        <span class="status-badge free">FREE ACCOUNT</span>
                                    <?php endif; ?>
                                    
                                    <?php if($isMeClass): ?> 
                                        <span class="status-badge bg-primary">VOCÊ</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="hide-mobile">
                                <?php if($p['guild_name']): ?>
                                    <a href="guilds.php?name=<?php echo urlencode($p['guild_name']); ?>" class="text-decoration-none text-muted fw-bold hover-white">
                                        <i class="fas fa-shield-alt text-primary me-1"></i> <?php echo htmlspecialchars($p['guild_name']); ?>
                                    </a>
                                <?php else: ?>
                                    <span class="text-muted opacity-25">-</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <div class="fw-bold fs-4" style="color: var(--primary); font-family: 'Rajdhani', sans-serif;">
                                    <?php 
                                        // Valor correto para o ranking (Level, Fishing ou Catch)
                                        echo number_format($p['display_val'], 0, ',', '.'); 
                                    ?>
                                </div>
                                <div class="text-muted small" style="font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px;">
                                    <?php 
                                        // Título do ranking atual (Top Level, Fishing Skill, Total Catchs)
                                        echo $cfg['title']; 
                                    ?>
                                </div>
                            </td>
                        </tr>
                        <?php $rank++; endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="text-center py-5">
                                <i class="fas fa-ghost fa-3x text-muted mb-3 opacity-50"></i>
                                <p class="text-muted">Nenhum jogador encontrado neste ranking.</p>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="d-flex justify-content-center mt-5">
        <nav>
            <ul class="pagination">
                <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?type=<?php echo $type; ?>&search=<?php echo $search; ?>&page=<?php echo $page - 1; ?>">&laquo;</a>
                </li>
                
                <?php 
                $start = max(1, $page - 2);
                $end = min($totalPages, $page + 2);
                for($i = $start; $i <= $end; $i++): 
                ?>
                    <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                        <a class="page-link" href="?type=<?php echo $type; ?>&search=<?php echo $search; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>

                <li class="page-item <?php echo ($page >= $totalPages) ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?type=<?php echo $type; ?>&search=<?php echo $search; ?>&page=<?php echo $page + 1; ?>">&raquo;</a>
                </li>
            </ul>
        </nav>
    </div>
    <?php endif; ?>

</div>

<?php 
// --- INCLUINDO O FOOTER ---
include 'includes/footer.php'; 
?>

<script>
    AOS.init({ once: true });
</script>