<?php
// 1. CARGAR CONFIGURACIÓN Y DETERMINAR TEMPLATE ACTIVO
require_once('config/settings.php');
if (file_exists('active_template.php')) { 
    include 'active_template.php'; 
}

// 2. RUTAS DINÁMICAS: Header desde la carpeta Desing del template activo
include('templates/' . ACTIVE_TEMPLATE . '/Desing/header.php');

try {
    $dsn = "dblib:host={$db_settings['host']};dbname={$db_settings['name']};charset=UTF8";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    
    // Consultamos la tabla de configuración completa
    $query = $pdo->query("SELECT setting_key, setting_value FROM Web_Ranking_Config");
    $config = $query->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (Exception $e) {
    // Valores por defecto si falla la conexión
    $config = [
        'show_resets' => '1', 'show_level' => '1', 'show_pk' => '1', 
        'show_master' => '1', 'show_mresets' => '0', 'show_gens' => '0'
    ];
}
?>

<style>
    /* Estilos Carnelian & Gold para Rankings */
    @keyframes slideIn { from { opacity: 0; transform: translateY(20px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }
    @keyframes fadeOut { from { opacity: 1; transform: translateY(0); } to { opacity: 0; transform: translateY(-20px); } }
    
    .rank-row { opacity: 0; }
    
    /* Botones de Tabulación Estilo Cristal Rojo */
    .tab-btn { 
        position: relative; 
        overflow: hidden; 
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); 
        white-space: nowrap; 
        background: rgba(153, 0, 0, 0.05); /* Rojo muy tenue */
        border: 1px solid rgba(255, 204, 51, 0.1); /* Borde Oro tenue */
        color: #9ca3af;
    }
    
    .tab-btn.active { 
        background: #990000; /* Carnelian Red */
        color: #ffcc33; /* Gold */
        border-color: #ffcc33; 
        box-shadow: 0 0 20px rgba(153, 0, 0, 0.4), inset 0 0 10px rgba(255, 204, 51, 0.2);
    }
    
    .tab-btn:not(.active):hover { 
        background: rgba(153, 0, 0, 0.2); 
        border-color: #ffcc33; 
        color: white;
    }

    .btn-nav {
        border: 1px solid rgba(255, 204, 51, 0.2);
        background: rgba(10, 10, 10, 0.6);
        color: #ffcc33;
    }

    .btn-nav:hover:not(:disabled) {
        background: #990000;
        border-color: #ffcc33;
    }

    .btn-nav:disabled { opacity: 0.15; cursor: not-allowed; filter: grayscale(1); }
</style>

<div class="container mx-auto px-4 py-32 min-h-screen">
    <div class="max-w-6xl mx-auto"> 
        <div class="text-center mb-12">
            <h2 class="text-4xl font-black text-white uppercase tracking-tighter italic mb-2">
                Hall of <span style="color: #ffcc33;">Fame</span>
            </h2>
            <div class="h-1 w-24 bg-[#990000] mx-auto mb-4"></div> <p class="text-[10px] text-gray-500 font-bold uppercase tracking-[0.5em] mb-8">Los guerreros más poderosos del reino</p>
            
            <div class="flex flex-wrap justify-center gap-3">
                <?php 
                $tabs = [
                    'resets' => ['key' => 'show_resets', 'icon' => 'refresh-cw', 'label' => 'Resets'],
                    'mresets' => ['key' => 'show_mresets', 'icon' => 'rotate-cw', 'label' => 'M. Resets'],
                    'level' => ['key' => 'show_level', 'icon' => 'trending-up', 'label' => 'Nivel'],
                    'master' => ['key' => 'show_master', 'icon' => 'zap', 'label' => 'M. Level'],
                    'pk' => ['key' => 'show_pk', 'icon' => 'swords', 'label' => 'Asesinos'],
                    'gens' => ['key' => 'show_gens', 'icon' => 'shield', 'label' => 'Gens'],
                    'bc' => ['key' => 'show_bc', 'icon' => 'castle', 'label' => 'BC Score'],
                    'ds' => ['key' => 'show_ds', 'icon' => 'skull', 'label' => 'DS Score'],
                    'cc' => ['key' => 'show_cc', 'icon' => 'swords', 'label' => 'CC Score'],
                    'it' => ['key' => 'show_it', 'icon' => 'flame', 'label' => 'Illusion'],
                    'duels' => ['key' => 'show_duels', 'icon' => 'trophy', 'label' => 'Duelos'],
                ];

                $first = true;
                foreach($tabs as $id => $data): 
                    if(($config[$data['key']] ?? '0') == '1' || ($id == 'resets')): // Forzamos resets como fallback si no hay config
                ?>
                    <button onclick="changeRanking('<?php echo $id; ?>', this)" 
                            class="tab-btn <?php echo $first ? 'active' : ''; ?> px-6 py-3 rounded-sm text-[9px] font-black uppercase tracking-widest flex items-center gap-2">
                        <i data-lucide="<?php echo $data['icon']; ?>" class="w-3 h-3"></i> <?php echo $data['label']; ?>
                    </button>
                <?php 
                    $first = false;
                    endif; 
                endforeach; 
                ?>
            </div>
        </div>

        <div class="relative min-h-[600px] mb-12">
            <div id="ranking-content" class="space-y-4">
                </div>
        </div>

        <div class="glass-mmo max-w-xs mx-auto p-2 rounded-sm border border-[#ffcc33]/20 flex items-center justify-between shadow-2xl bg-black/60 backdrop-blur-md">
            <button id="btn-prev" onclick="prevPage()" class="btn-nav p-4 rounded-sm transition-all">
                <i data-lucide="chevron-left" class="w-5 h-5"></i>
            </button>
            <div class="text-center">
                <span id="page-num" class="block text-[11px] font-black text-white uppercase tracking-tighter">Página 1</span>
                <span id="total-pages-label" class="block text-[8px] text-[#ffcc33] font-bold uppercase">de --</span>
            </div>
            <button id="btn-next" onclick="nextPage()" class="btn-nav p-4 rounded-sm transition-all">
                <i data-lucide="chevron-right" class="w-5 h-5"></i>
            </button>
        </div>

    </div>
</div>

<script>
// Lógica JS Original mantenida y adaptada
let activeBtn = document.querySelector('.tab-btn.active');
let currentType = activeBtn ? activeBtn.getAttribute('onclick').match(/'([^']+)'/)[1] : 'resets';

let currentPage = 1;
let totalPages = 1;
let isBusy = false;

function loadRanking() {
    if(isBusy) return;
    const container = document.getElementById('ranking-content');
    if(!container) return;
    
    isBusy = true;
    const oldRows = container.querySelectorAll('.rank-row');
    
    oldRows.forEach((row, i) => {
        row.style.animation = `fadeOut 0.3s ease forwards`;
        row.style.animationDelay = `${i * 0.02}s`;
    });

    setTimeout(() => {
        fetch(`api_ranking.php?type=${currentType}&p=${currentPage}`)
            .then(response => {
                totalPages = parseInt(response.headers.get('X-Total-Pages')) || 1;
                return response.text();
            })
            .then(html => {
                container.innerHTML = html;
                document.getElementById('page-num').innerText = `P\u00e1gina ${currentPage}`;
                document.getElementById('total-pages-label').innerText = `de ${totalPages}`;
                document.getElementById('btn-prev').disabled = (currentPage === 1);
                document.getElementById('btn-next').disabled = (currentPage >= totalPages);
                if(window.lucide) lucide.createIcons();
                isBusy = false;
            })
            .catch(err => {
                console.error("Error:", err);
                isBusy = false;
            });
    }, oldRows.length > 0 ? 300 : 0);
}

function changeRanking(type, btn) {
    if(btn.classList.contains('active') || isBusy) return;
    currentType = type;
    currentPage = 1;
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    loadRanking();
}

function nextPage() { if(currentPage < totalPages && !isBusy) { currentPage++; loadRanking(); } }
function prevPage() { if(currentPage > 1 && !isBusy) { currentPage--; loadRanking(); } }

// Inicialización
document.addEventListener('DOMContentLoaded', loadRanking);
</script>

<?php 
// 3. RUTA DINÁMICA: Footer desde Desing
include('templates/' . ACTIVE_TEMPLATE . '/Desing/footer.php'); 
?>