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

// 2. RUTA DINÁMICA: 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']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Seleccionamos los registros activos
    $stmt = $pdo->query("SELECT * FROM Web_Schedules WHERE status = 1 ORDER BY type DESC, name ASC");
    $schedules = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $schedules = [];
}
?>

<style>
    /* Estilos de Resplandor con temática Carnelian y Gold */
    .glow-common { border: 1px solid rgba(255,255,255,0.1) !important; }
    .glow-excellent { 
        border: 1px solid #00ffcc !important; 
        box-shadow: 0 0 15px rgba(0, 255, 204, 0.4), inset 0 0 10px rgba(0, 255, 204, 0.2);
    }
    .glow-ancient { 
        border: 1px solid #ffcc00 !important; 
        box-shadow: 0 0 15px rgba(255, 204, 0, 0.4), inset 0 0 10px rgba(255, 204, 0, 0.2);
    }
    .glow-socket { 
        border: 1px solid #bf40bf !important; 
        box-shadow: 0 0 15px rgba(191, 64, 191, 0.4), inset 0 0 10px rgba(191, 64, 191, 0.2);
    }
    .glow-boss { 
        border: 1px solid #990000 !important; /* Rojo Carmesí */
        box-shadow: 0 0 15px rgba(153, 0, 0, 0.6), inset 0 0 10px rgba(153, 0, 0, 0.3);
    }
    /* Estilo para los botones activos en modo Carnelian */
    .bg-carnelian { background-color: #990000 !important; color: #ffcc33 !important; border: 1px solid #ffcc33 !important; }
</style>

<div class="container mx-auto px-4" style="margin-top: 120px; margin-bottom: 80px;">
    <div class="max-w-6xl mx-auto text-center">
        <h1 class="text-5xl font-bold text-white mb-4 font-title tracking-tighter uppercase italic">
            Cronograma de <span style="color: #ffcc33;">Horarios</span>
        </h1>
        <p class="text-gray-400 mb-8 tracking-[0.2em] text-xs uppercase">Filtra y revisa los Horarios de Invasion y Eventos en tiempo real</p>

        <div class="flex justify-center mb-12">
            <div class="inline-flex p-1 bg-white/5 border border-white/10 rounded-xl backdrop-blur-sm">
                <button onclick="filterEvents('all')" id="btn-all" class="filter-btn px-6 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all duration-300 bg-carnelian">
                    Todos
                </button>
                <button onclick="filterEvents('event')" id="btn-event" class="filter-btn px-6 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all duration-300 text-gray-500 hover:text-white">
                    Eventos
                </button>
                <button onclick="filterEvents('invasion')" id="btn-invasion" class="filter-btn px-6 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all duration-300 text-gray-500 hover:text-white">
                    Invasiones
                </button>
            </div>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
            <?php if(count($schedules) > 0): ?>
                <?php foreach($schedules as $sch): ?>
                <div class="relative group event-card" data-type="<?php echo $sch['type']; ?>">
                    <div class="absolute -inset-0.5 bg-gradient-to-r from-red-900 to-red-600 rounded-2xl blur opacity-20 group-hover:opacity-50 transition duration-1000"></div>
                    
                    <div class="relative bg-[#0a0a0a] border border-white/10 rounded-2xl overflow-hidden">
                        <div class="relative h-40 overflow-hidden border-b border-white/5">
                            <?php $eventImg = !empty($sch['image_url']) ? $sch['image_url'] : 'assets/images/default-event.jpg'; ?>
                            <img src="<?php echo $eventImg; ?>" class="w-full h-full object-cover opacity-50 group-hover:scale-110 group-hover:opacity-80 transition duration-700">
                            <div class="absolute inset-0 bg-gradient-to-t from-[#0a0a0a] via-transparent to-transparent"></div>
                        </div>

                        <div class="p-8">
                            <div class="flex justify-between items-start mb-4">
                                <span class="text-[9px] bg-red-900/20 text-red-500 px-3 py-1 rounded-full uppercase font-bold tracking-widest border border-red-900/40">
                                    <?php echo ($sch['type'] == 'event') ? 'Evento Diario' : 'Invasión'; ?>
                                </span>
                                <span class="text-[9px] text-gray-500 font-mono italic"><?php echo htmlspecialchars($sch['gmt']); ?></span>
                            </div>

                            <h3 class="text-2xl font-bold text-white mb-2 uppercase tracking-tighter italic text-left">
                                <?php echo htmlspecialchars($sch['name']); ?>
                            </h3>

                            <p class="text-gray-400 text-[11px] leading-relaxed mb-6 h-10 overflow-hidden text-left">
                                <?php echo htmlspecialchars($sch['description'] ?? 'Sin descripción disponible.'); ?>
                            </p>

                            <div class="mb-6 text-left">
                                <p class="text-[8px] uppercase text-gray-600 font-bold tracking-[0.2em] mb-3">Recompensas Posibles</p>
                                <div class="flex flex-wrap gap-2">
                                    <?php 
                                    if(!empty($sch['drops'])):
                                        $dropsList = explode(',', $sch['drops']); 
                                        foreach($dropsList as $dropItem): 
                                            $parts = explode('|', $dropItem);
                                            $imageName = trim($parts[0]);
                                            $rarity = isset($parts[1]) ? trim($parts[1]) : 'common';
                                    ?>
                                            <div class="w-12 h-12 bg-white/5 rounded-xl flex items-center justify-center p-2 transition hover:scale-110 glow-<?php echo $rarity; ?>">
                                                <img src="assets/drops/<?php echo $imageName; ?>" 
                                                     title="Rareza: <?php echo ucfirst($rarity); ?>"
                                                     class="w-full h-full object-contain drop-shadow-lg">
                                            </div>
                                        <?php endforeach; 
                                    else: ?>
                                        <span class="text-[9px] text-gray-700 italic">No hay drops configurados</span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="grid grid-cols-3 gap-3 mb-8" id="timer-<?php echo $sch['id']; ?>">
                                <div class="bg-white/5 p-3 rounded-lg border border-white/5 text-center">
                                    <div class="text-xl font-bold text-white hours">00</div>
                                    <div class="text-[7px] text-gray-500 uppercase font-bold tracking-widest">Hrs</div>
                                </div>
                                <div class="bg-white/5 p-3 rounded-lg border border-white/5 text-center">
                                    <div class="text-xl font-bold text-white minutes">00</div>
                                    <div class="text-[7px] text-gray-500 uppercase font-bold tracking-widest">Min</div>
                                </div>
                                <div class="bg-white/5 p-3 rounded-lg border border-white/5 text-center">
                                    <div class="text-xl font-bold text-orange-500 seconds" style="color: #ffcc33;">00</div>
                                    <div class="text-[7px] text-gray-500 uppercase font-bold tracking-widest">Seg</div>
                                </div>
                            </div>

                            <div class="pt-4 border-t border-white/5">
                                <div class="flex flex-wrap gap-1">
                                    <?php 
                                    $times = explode(',', $sch['times']);
                                    foreach($times as $t): 
                                    ?>
                                        <span class="text-[9px] bg-white/5 text-gray-500 px-2 py-1 rounded font-mono border border-white/5">
                                            <?php echo trim($t); ?>
                                        </span>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <script>
                    (function() {
                        const timesStr = "<?php echo $sch['times']; ?>";
                        const container = document.getElementById('timer-<?php echo $sch['id']; ?>');
                        function update() {
                            const now = new Date();
                            const times = timesStr.split(',').map(t => t.trim());
                            let next = null;
                            times.forEach(t => {
                                const [h, m] = t.split(':');
                                let d = new Date(); d.setHours(parseInt(h), parseInt(m), 0, 0);
                                if (d < now) d.setDate(d.getDate() + 1);
                                if (!next || d < next) next = d;
                            });
                            const diff = next - now;
                            container.querySelector('.hours').innerText = Math.floor(diff / 36e5).toString().padStart(2, '0');
                            container.querySelector('.minutes').innerText = Math.floor((diff % 36e5) / 6e4).toString().padStart(2, '0');
                            container.querySelector('.seconds').innerText = Math.floor((diff % 6e4) / 1000).toString().padStart(2, '0');
                        }
                        setInterval(update, 1000); update();
                    })();
                </script>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col-span-full text-gray-500 italic py-20 bg-white/5 rounded-2xl border border-white/10">
                    No hay registros disponibles.
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function filterEvents(type) {
    const cards = document.querySelectorAll('.event-card');
    const btns = document.querySelectorAll('.filter-btn');
    
    btns.forEach(btn => {
        btn.classList.remove('bg-carnelian');
        btn.classList.add('text-gray-500');
        btn.style.backgroundColor = 'transparent';
        btn.style.color = '';
        btn.style.border = 'none';
    });
    
    const activeBtn = document.getElementById('btn-' + type);
    if(activeBtn) {
        activeBtn.classList.add('bg-carnelian');
        activeBtn.classList.remove('text-gray-500');
    }

    cards.forEach(card => {
        if (type === 'all' || card.getAttribute('data-type') === type) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}
</script>

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