<?php
// --- 1. CONFIGURAÇÃO DE ERROS ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

// --- 2. CONEXÃO ROBUSTA ---
$conectado = false;
$caminhos = ['conexao.php', '../conexao.php', '../../conexao.php'];

foreach ($caminhos as $caminho) {
    if (file_exists($caminho)) {
        require_once $caminho;
        $conectado = true;
        break;
    }
}

if (!$conectado) {
    die("Erro: Conexão não encontrada.");
}

// --- 3. VERIFICAÇÃO DE LOGIN ---
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

try {
    // --- 4. CONFIGURAÇÃO DO SISTEMA ---
    $busca = isset($_GET['busca']) ? trim($_GET['busca']) : '';
    $pagina = isset($_GET['p']) ? (int)$_GET['p'] : 1;
    if ($pagina < 1) $pagina = 1;

    $limite = 15; // Quantidade de clãs por página
    $offset = ($pagina - 1) * $limite;

    // Filtro SQL
    $sqlWhere = "WHERE classificacao = 'ativo'"; 
    $params = [];

    if (!empty($busca)) {
        $sqlWhere .= " AND (nome LIKE :busca OR lider LIKE :busca)";
        $params[':busca'] = "%$busca%";
    }

    // A. Contagem Total (Para a Paginação)
    $stmtCount = $pdo->prepare("SELECT COUNT(*) FROM cla $sqlWhere");
    if (!empty($busca)) { $stmtCount->bindParam(':busca', $params[':busca']); }
    $stmtCount->execute();
    $total_registros = $stmtCount->fetchColumn();
    $total_paginas = ceil($total_registros / $limite);

    // B. Busca dos Clãs (LÓGICA NOVA: Pontos -> Reputação -> ID)
    $sqlFinal = "SELECT * FROM cla 
                 $sqlWhere 
                 ORDER BY pontos DESC, reputacao DESC, id ASC 
                 LIMIT :limite OFFSET :offset";

    $stmt = $pdo->prepare($sqlFinal);
    if (!empty($busca)) { $stmt->bindParam(':busca', $params[':busca']); }
    $stmt->bindParam(':limite', $limite, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $clas = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Erro SQL: " . $e->getMessage());
}

// Função de Cor
function getRepColor($rep) {
    if ($rep >= 100) return '#00ff44'; // Verde
    if ($rep >= 50) return '#00d2ff';  // Azul
    return '#ff2222';                  // Vermelho
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ranking de Clãs</title>
    
    <link rel="stylesheet" href="css/dashboardmed.css"> 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        /* Variáveis de Backup */
        :root {
            --primary: #0000FF; 
            --neon-bright: #3333FF;
            --card-bg: rgba(5, 5, 20, 0.9);
        }

        body {
            background-color: #02020a;
            color: #ffffff;
            font-family: 'Segoe UI', sans-serif;
            
            /* --- AQUI ESTÁ A IMAGEM DE FUNDO IGUAL AO DASHBOARD --- */
            /* Ajuste o nome do arquivo 'rpg-login-background.jpg' se necessário */
            background: linear-gradient(rgba(2, 2, 10, 0.8), rgba(2, 2, 10, 0.8)), url('../rpg-login-background.jpg');
            
            background-size: cover;
            background-position: center center;
            background-attachment: fixed; /* O fundo fica fixo ao rolar */
        }

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

        /* --- FLEXBOX PARA CENTRALIZAR OS CARDS --- */
        .clan-grid {
            display: flex;
            flex-wrap: wrap; 
            justify-content: center; /* CENTRALIZA OS ITENS NA TELA */
            gap: 25px;
            margin-top: 20px;
        }

        .clan-card {
            background-color: var(--card-bg);
            border: 2px solid var(--primary);
            border-radius: 12px;
            padding: 20px;
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            transition: transform 0.3s, box-shadow 0.3s;
            box-shadow: 0 0 10px rgba(0, 0, 255, 0.2);
            overflow: hidden;
            
            /* Tamanho fixo para uniformidade */
            width: 300px; 
            flex-grow: 0;
            flex-shrink: 0;
            
            /* Efeito de vidro para ver o fundo levemente */
            backdrop-filter: blur(5px);
        }

        .clan-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0 25px var(--neon-bright);
            border-color: #fff;
        }

        /* Badge de Rank */
        .rank-badge {
            position: absolute;
            top: 0;
            right: 0;
            background: var(--primary);
            color: #fff;
            padding: 5px 12px;
            border-bottom-left-radius: 10px;
            font-weight: bold;
            font-size: 0.9rem;
            z-index: 2;
        }
        .rank-1 { background: #ffd700; color: #000; box-shadow: 0 0 15px #ffd700; }
        .rank-2 { background: #c0c0c0; color: #000; box-shadow: 0 0 15px #c0c0c0; }
        .rank-3 { background: #cd7f32; color: #000; box-shadow: 0 0 15px #cd7f32; }

        .clan-name {
            font-family: 'Times New Roman', serif;
            font-size: 1.6rem;
            color: var(--primary);
            text-transform: uppercase;
            text-shadow: 0 0 8px var(--primary);
            margin-bottom: 10px;
            border-bottom: 1px solid #333;
            padding-bottom: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .clan-desc {
            font-size: 0.85rem;
            color: #aaa;
            font-style: italic;
            height: 45px;
            overflow: hidden;
            margin-bottom: 15px;
        }

        .clan-stats p {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 0.95rem;
            color: #ccc;
            border-bottom: 1px dashed rgba(255,255,255,0.1);
            padding-bottom: 2px;
        }
        .stat-val { font-weight: bold; color: #fff; }

        .btn-view {
            width: 100%;
            background: transparent;
            border: 1px solid var(--primary);
            color: var(--primary);
            padding: 10px;
            border-radius: 6px;
            margin-top: 15px;
            cursor: pointer;
            text-transform: uppercase;
            font-size: 0.8rem;
            transition: 0.3s;
        }
        .btn-view:hover {
            background: var(--primary);
            color: #000;
            box-shadow: 0 0 10px var(--primary);
        }

        /* Busca e Paginação */
        .search-bar { width: 100%; max-width: 500px; padding: 12px; background: rgba(0,0,0,0.7); border: 2px solid var(--primary); color: #fff; border-radius: 25px; text-align: center; outline: none; }
        .search-bar:focus { box-shadow: 0 0 15px var(--primary); }
        
        .pagination { text-align: center; margin-top: 30px; display: flex; justify-content: center; gap: 5px; flex-wrap: wrap; }
        .page-btn { display: inline-block; padding: 8px 12px; border: 1px solid var(--primary); color: #888; text-decoration: none; border-radius: 4px; transition: 0.3s; background: rgba(0,0,0,0.6); }
        .page-btn.active, .page-btn:hover { background: var(--primary); color: #fff; box-shadow: 0 0 10px var(--primary); color: white !important; }
    </style>
</head>
<body>
    <div class="container">
        
        <div style="text-align: center; margin-bottom: 30px;">
            <h1 style="color: var(--primary); font-family: 'Times New Roman', serif; text-transform: uppercase; font-size: 2.5rem; text-shadow: 0 0 15px var(--primary);">
                Ranking de Clãs
            </h1>
            <a href="../dashboard.php" style="text-decoration: none;">
                <button style="background: rgba(0,0,0,0.8); border: 1px solid var(--primary); color: #fff; padding: 10px 20px; cursor: pointer; border-radius: 5px; margin-top: 10px;">
                   Menu Principal
                </button>
            </a>
            <a href="../dashboardmed.php" style="text-decoration: none;">
                <button style="background: rgba(0,0,0,0.8); border: 1px solid var(--primary); color: #fff; padding: 10px 20px; cursor: pointer; border-radius: 5px; margin-top: 10px;">
                    Voltar ao Jogo
                </button>
            </a>
        </div>

        <div style="text-align: center; margin-bottom: 30px;">
            <form action="" method="GET">
                <input type="text" name="busca" class="search-bar" placeholder="Buscar Clã ou Líder..." value="<?= htmlspecialchars($busca) ?>">
            </form>
        </div>

        <div class="clan-grid">
            <?php if (empty($clas)): ?>
                <div style="width: 100%; text-align: center; padding: 50px; color: #ccc; border: 2px dashed #333; border-radius: 10px; background: rgba(0,0,0,0.6);">
                    <i class="fas fa-search" style="font-size: 3rem; margin-bottom: 15px;"></i><br>
                    Nenhum clã encontrado.
                </div>
            <?php else: ?>
                <?php 
                $rank = $offset + 1; // Calcula o Rank baseado na página atual
                foreach ($clas as $cla): 
                    // Prepara dados
                    $nome = $cla['nome'] ?? 'Desconhecido';
                    $lider = $cla['lider'] ?? 'Ninguém';
                    $pontos = number_format($cla['pontos'] ?? 0);
                    $reputacao = $cla['reputacao'] ?? 0;
                    $ameaca = $cla['ameaca'] ?? 0;
                    $desc = $cla['descricao'] ?? '';
                    
                    // Descrição curta
                    $desc_curta = (strlen($desc) > 90) ? substr($desc, 0, 90) . '...' : $desc;
                    if(empty($desc_curta)) $desc_curta = "Sem descrição disponível.";

                    // Estilo do Rank
                    $rankClass = '';
                    if ($rank == 1) $rankClass = 'rank-1';
                    elseif ($rank == 2) $rankClass = 'rank-2';
                    elseif ($rank == 3) $rankClass = 'rank-3';
                ?>
                    <div class="clan-card">
                        <div class="rank-badge <?= $rankClass ?>">#<?= $rank ?></div>
                        
                        <h3 class="clan-name"><?= htmlspecialchars($nome) ?></h3>
                        
                        <div class="clan-desc">
                            "<?= htmlspecialchars($desc_curta) ?>"
                        </div>

                        <div class="clan-stats">
                            <p><span>Líder:</span> <span class="stat-val" style="color: gold;"><?= htmlspecialchars($lider) ?></span></p>
                            <p><span>Pontos:</span> <span class="stat-val" style="color: cyan;"><?= $pontos ?></span></p>
                            <p><span>Reputação:</span> <span class="stat-val" style="color: <?= getRepColor($reputacao) ?>;"><?= $reputacao ?></span></p>
                            <p><span>Ameaça:</span> <span class="stat-val" style="color: #ff4444;"><?= $ameaca ?></span></p>
                        </div>

                        <button class="btn-view">
                            <i class="fas fa-eye"></i> Detalhes
                        </button>
                    </div>
                <?php 
                $rank++;
                endforeach; 
                ?>
            <?php endif; ?>
        </div>

        <?php if ($total_paginas > 1): ?>
        <div class="pagination">
            <?php if ($pagina > 1): ?>
                <a href="?p=<?= $pagina - 1 ?>&busca=<?= urlencode($busca) ?>" class="page-btn">&laquo; Anterior</a>
            <?php endif; ?>

            <?php for ($i = 1; $i <= $total_paginas; $i++): ?>
                <a href="?p=<?= $i ?>&busca=<?= urlencode($busca) ?>" class="page-btn <?= ($i == $pagina) ? 'active' : '' ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>

            <?php if ($pagina < $total_paginas): ?>
                <a href="?p=<?= $pagina + 1 ?>&busca=<?= urlencode($busca) ?>" class="page-btn">Próxima &raquo;</a>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div style="text-align: center; margin-top: 40px; border-top: 1px solid var(--primary); padding-top: 20px;">
            <p style="color: #aaa; font-size: 0.9rem;">&copy; 2025 RPG ERA MEDIEVAL</p>
        </div>

    </div>
</body>
</html>