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

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);

    $stmt = $pdo->query("SELECT * FROM Web_Guides ORDER BY date_posted DESC");
    $guides = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $guides = [];
}
?>

<style>
    .font-title { font-family: 'Cinzel', serif; }
    .bg-carnelian { background: #990000 !important; color: #ffcc33 !important; border: 1px solid #ffcc33 !important; }
    .red-crystal-icon { filter: drop-shadow(0 0 8px #ff0000); color: #ff0000; }
    
    /* FIX: Scrollbar personalizada para el contenido largo */
    #guide-content-area::-webkit-scrollbar { width: 8px; }
    #guide-content-area::-webkit-scrollbar-track { background: rgba(0,0,0,0.3); }
    #guide-content-area::-webkit-scrollbar-thumb { 
        background: linear-gradient(to bottom, #990000, #450a0a); 
        border-radius: 10px;
        border: 2px solid #0d0d0d;
    }

    /* Evitar que el modal se desborde */
    #modal-inner-container {
        height: 85vh; /* Altura máxima fija */
    }

    .guide-card:hover { transform: translateY(-5px); border-color: #990000; box-shadow: 0 10px 30px rgba(153, 0, 0, 0.3); }
</style>

<div class="container mx-auto px-4" style="margin-top: 120px; margin-bottom: 80px;">
    <div class="max-w-6xl mx-auto">
        
        <div class="text-center mb-12">
            <h1 class="text-5xl font-bold text-white mb-4 font-title tracking-tighter uppercase italic">
                BIBLIOTECA DE <span style="color: #ffcc33;">SABIDURÍA</span>
            </h1>
            <div class="relative max-w-2xl mx-auto mb-10">
                <input type="text" id="guide-search" onkeyup="searchGuides()" 
                    placeholder="Buscar guía por palabra clave..." 
                    class="w-full bg-white/5 border border-white/10 rounded-2xl py-5 px-6 pl-14 text-white placeholder-gray-500 focus:outline-none focus:border-red-600 transition-all">
                <i data-lucide="search" class="absolute left-5 top-1/2 -translate-y-1/2 text-red-600 w-6 h-6"></i>
            </div>

            <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="filterCategory('all')" id="cat-all" class="cat-btn px-6 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all duration-300 bg-carnelian">Todas</button>
                    <button onclick="filterCategory('Web')" id="cat-Web" class="cat-btn px-6 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all duration-300 text-gray-500 hover:text-white">Web</button>
                    <button onclick="filterCategory('Eventos')" id="cat-Eventos" class="cat-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="filterCategory('Servidor')" id="cat-Servidor" class="cat-btn px-6 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all duration-300 text-gray-500 hover:text-white">Servidor</button>
                </div>
            </div>
        </div>

        <div id="guides-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach($guides as $guide): ?>
                <div class="guide-item group" data-category="<?php echo $guide['category']; ?>" data-title="<?php echo strtolower($guide['title']); ?>">
                    <div onclick="openGuide(<?php echo htmlspecialchars(json_encode($guide)); ?>)" 
                        class="guide-card bg-[#0a0a0a] border border-white/10 rounded-2xl p-6 cursor-pointer transition-all duration-500 h-full">
                        <span class="text-[9px] bg-red-900/20 text-red-500 px-3 py-1 rounded-full uppercase font-black border border-red-900/30 mb-4 inline-block"><?php echo $guide['category']; ?></span>
                        <h3 class="text-xl font-bold text-white uppercase tracking-tighter mb-3"><?php echo htmlspecialchars($guide['title']); ?></h3>
                        <p class="text-gray-500 text-xs line-clamp-2"><?php echo strip_tags($guide['content']); ?></p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div id="guide-modal" class="fixed inset-0 z-[9999] hidden flex items-center justify-center p-4 bg-black/90 backdrop-blur-sm">
    <div id="modal-inner-container" class="bg-[#0d0d0d] border-2 border-red-900/50 rounded-[2rem] w-full max-w-6xl overflow-hidden relative shadow-2xl flex flex-col md:flex-row">
        
        <button onclick="closeGuide()" class="absolute top-6 right-6 z-20 bg-red-600 text-white p-2 rounded-full hover:scale-110 transition">
            <i data-lucide="x" class="w-6 h-6"></i>
        </button>

        <div class="w-full md:w-5/12 h-48 md:h-full relative overflow-hidden flex-shrink-0">
            <img id="modal-image" src="" class="w-full h-full object-cover opacity-60">
            <div class="absolute inset-0 bg-gradient-to-r from-transparent to-[#0d0d0d] hidden md:block"></div>
        </div>

        <div id="guide-content-area" class="w-full md:w-7/12 p-8 md:p-14 overflow-y-auto bg-[#0d0d0d]">
            <span id="modal-category" class="text-[10px] text-red-500 font-black uppercase tracking-widest mb-2 block"></span>
            <h2 id="modal-title" class="text-4xl md:text-5xl font-title text-white uppercase italic tracking-tighter mb-6"></h2>
            
            <div class="flex items-center gap-4 text-gray-600 text-[10px] uppercase font-bold mb-8 border-b border-white/5 pb-4">
                <span><i data-lucide="calendar" class="w-3 h-3 inline mr-1 text-red-600"></i> <span id="modal-date"></span></span>
            </div>

            <div id="modal-content" class="text-gray-400 text-sm md:text-base leading-relaxed space-y-4">
                </div>
            
            <div class="h-20"></div>
        </div>
    </div>
</div>

<script>
    lucide.createIcons();

    function openGuide(guide) {
        document.getElementById('modal-title').innerText = guide.title;
        document.getElementById('modal-category').innerText = guide.category;
        document.getElementById('modal-date').innerText = new Date(guide.date_posted).toLocaleDateString();
        document.getElementById('modal-content').innerHTML = guide.content;
        document.getElementById('modal-image').src = guide.image_path ? guide.image_path : 'assets/images/default-guide.jpg';

        document.getElementById('guide-modal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
        
        // Resetear el scroll del contenido al inicio cada vez que se abra una nueva guía
        document.getElementById('guide-content-area').scrollTop = 0;
    }

    function closeGuide() {
        document.getElementById('guide-modal').classList.add('hidden');
        document.body.style.overflow = 'auto';
    }

    function searchGuides() {
        const input = document.getElementById('guide-search').value.toLowerCase();
        document.querySelectorAll('.guide-item').forEach(item => {
            item.style.display = item.getAttribute('data-title').includes(input) ? 'block' : 'none';
        });
    }

    function filterCategory(cat) {
        document.querySelectorAll('.cat-btn').forEach(btn => {
            btn.classList.remove('bg-carnelian');
            btn.classList.add('text-gray-500');
        });
        document.getElementById('cat-' + cat).classList.add('bg-carnelian');
        document.getElementById('cat-' + cat).classList.remove('text-gray-500');

        document.querySelectorAll('.guide-item').forEach(item => {
            item.style.display = (cat === 'all' || item.getAttribute('data-category') === cat) ? 'block' : 'none';
        });
    }
</script>