<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>PromocionARTE FlowCRM™  De OrozDesign Powered By OrozCO</title>
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
    
    <style>
    .cat-chip{
        display:inline-flex;align-items:center;justify-content:center;gap:.5rem;
        padding:.5rem .75rem;border-radius:12px;border:1px solid rgba(0,0,0,.1);
        background:#0f172a;color:#fff;font-weight:600;transition:.2s ease;
        letter-spacing:.2px;
    }
    .cat-chip:hover{ background:#1f2937; }
    .cat-chip svg{ width:20px;height:20px }

    .club-card{
        background:#fff;border:1px solid rgba(0,0,0,.06);border-radius:14px;
        box-shadow:0 2px 8px rgba(0,0,0,.06);padding:20px;display:flex;flex-direction:column;
        transition:box-shadow .2s ease, transform .2s ease;
    }
    .club-card:hover{ box-shadow:0 10px 24px rgba(0,0,0,.12); transform:translateY(-2px); }
    .club-card__top{ display:flex;align-items:center;justify-content:space-between;margin-bottom:.5rem; }
    .club-card__top svg{ width:24px;height:24px;color:#0f172a;opacity:.9 }
    .club-card__title{ font-weight:800;font-size:1.05rem;color:#111827;line-height:1.25;margin:4px 0 2px; }
    .club-card__desc{ font-size:.9rem;color:#4b5563;line-height:1.45;margin-top:2px;flex:1 1 auto; }
    .club-card__meta{ display:flex;gap:.75rem;align-items:center;margin-top:.5rem;color:#6b7280;font-size:.78rem; }
    .club-card__meta .meta{ display:inline-flex;gap:.35rem;align-items:center; }
    .club-card__meta .meta svg{ width:16px;height:16px }
    .club-card__btn{
        margin-top:.9rem;display:inline-flex;gap:.5rem;align-items:center;justify-content:center;
        padding:.55rem 1rem;border-radius:10px;background:#0f172a;color:#fff;font-weight:700;
        transition:.2s ease;text-decoration:none
    }
    .club-card__btn:hover{ opacity:.9 }

    .pill{ display:inline-flex;gap:.35rem;align-items:center;border-radius:999px;
        font-weight:700;text-transform:uppercase;font-size:.7rem;padding:.35rem .6rem;
        background:#e5e7eb;color:#111827;letter-spacing:.3px;
    }
    .pill--new{ background:#ffc857;color:#0b1220 }
    .pill--hot{ background:var(--color-secondary,#9e1428);color:#fff }

    #recursos h3, #nuevos h3{ margin-bottom:.25rem }
    #results-counter{ color:#6b7280 }
</style>
</head>

<body data-page-title="Recursos Para Impulsar Tu Marca" 
      data-page-subtitle="Adquiere Herramientas Y Materiales Para Impulsar Tu Negocio" 
      data-page-icon="rocket">
    
    <div id="toast-container" class="toast-container"></div>
      
<?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
            <div class="show-widget-container hidden">
    <button class="show-widget-btn inline-flex items-center gap-3 text-base font-bold text-white bg-[var(--color-primary)] rounded-lg shadow-lg shadow-[var(--color-primary)]/20 py-3 px-6 transform hover:-translate-y-1 hover:shadow-xl transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--color-secondary)]"
        
        data-widget-id="recursos-intro-video">

        <i data-lucide="eye" class="w-5 h-5"></i>
        <span>VER VIDEO PRESENTACIÓN</span>
    </button>
</div>
        </header>

        <div id="content-area" class="p-4 md:p-8 space-y-8">

<section id="recursos-intro-video" class="p-6 md:p-10 video-widget">
    <div class="blob bl1"></div><div class="blob bl2"></div>
    <div class="relative grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
        <div class="text-white">
            <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 ring-1 ring-white/15 mb-4">
                <i data-lucide="folder-kanban" class="w-4 h-4"></i>
                <span class="text-xs tracking-wide uppercase">Recursos Premium</span>
            </div>
            <h1 class="text-3xl md:text-4xl lg:text-5xl font-black leading-tight flex items-center tracking-tighter">
                <i data-lucide="rocket" class="w-9 h-9" style="color: var(--color-highlight);"></i>
                <span style="color: var(--color-text-light);">PROMOCION</span><span style="color: var(--color-highlight);">ARTE</span>
            </h1>
            <h3 class="text-3xl md:text-4xl lg:text-5xl font-black leading-tight flex items-center gap-3">
                Centro De Recursos
            </h3>
            <p class="mt-3 md:mt-4 text-base md:text-lg text-white/90">
                <strong>Productos y Servicios Exclusivos.</strong> Aquí encontrarás una colección de productos digitales y material publicitario listos para usar que te ayudarán a impulsar tu marca.
            </p>
            <div class="mt-6 grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div class="rounded-xl bg-white/10 ring-1 ring-white/15 p-4">
                    <div class="flex items-center gap-2">
                        <i data-lucide="download-cloud" class="w-5 h-5 text-[#ffc857]"></i>
                        <p class="text-sm font-semibold">Productos Digitales</p>
                    </div>
                    <p class="text-xs text-white/80 mt-1">Descarga, curos, guías, herramientas, plantillas y otros recursos listos para usar.</p>
                </div>
                <div class="rounded-xl bg-white/10 ring-1 ring-white/15 p-4">
                    <div class="flex items-center gap-2">
                        <i data-lucide="printer" class="w-5 h-5 text-[#ffc857]"></i>
                        <p class="text-sm font-semibold">Material Impreso</p>
                    </div>
                    <p class="text-xs text-white/80 mt-1">Adquiere material para promocoinar tu negocio: volantes, tarjetas, brochurs y más.</p>
                </div>
            </div>
        </div>

        <div class="w-full">
            <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                <div class="relative w-full" style="padding-bottom: 56.25%;">
                    <video class="absolute top-0 left-0 w-full h-full object-cover" controls controlslist="nodownload nofullscreen" preload="metadata">
                        <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                        TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                    </video>
                    <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                        <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                        <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                        <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                    </div>
                </div>
                <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                        <span class="inline-flex items-center gap-2">
                            <i data-lucide="play-circle" class="w-4 h-4"></i>
                            Video Presentación
                        </span>

                        <button class="hide-widget-btn inline-flex items-center gap-2 text-xs font-black text-[var(--color-highlight)] hover:text-[var(--color-highlight)] transition-colors py-1 px-2 rounded-md" 
                                data-widget-id="recursos-intro-video" 
                                title="Ocultar el video de bienvenida">
                            OCULTAR VIDEO
                            <i data-lucide="square-x" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
            <section id="promocion" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                        <div>
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2">
                                <i data-lucide="rocket" class="w-7 h-7 text-[var(--color-primary)]"></i> EXPLORA NUESTROS RECURSOS DE MARKETING
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">ENCUENTRA HERRAMIENTAS Y SOLUCIONES PARA CRECER TU NEGOCIO.</p>
                        </div>
                    </div>
                    <div id="promotions-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                        </div>

                    <div id="load-more-promotions-container" class="text-center mt-8">
                        <button id="load-more-promotions-btn" class="btn-primary font-bold py-3 px-8 rounded-lg uppercase">
                            Cargar Más Recursos
                        </button>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<script>
(function() {
    'use strict';

    // =================================================================
    // ESTADO Y CONSTANTES DE LA APLICACIÓN
    // =================================================================
    const STATE = {
        loadedCount: 0,
        perPage: 6, // Número de promociones a cargar por vez
        totalAvailable: 0,
        isLoading: false
    };

    // =================================================================
    // CACHÉ DE ELEMENTOS DEL DOM
    // =================================================================
    const UI = {
        promotionsContainer: document.getElementById('promotions-container'),
        loadMoreButton: document.getElementById('load-more-promotions-btn'),
        mobileMenuButton: document.getElementById('mobile-menu-button'),
        sidebar: document.getElementById('sidebar'),
        sidebarOverlay: document.getElementById('sidebar-overlay'),
        phoneInput: document.getElementById('contact_phone') // Opcional, si existe en la página
    };

    // =================================================================
    // FUNCIONES DE UTILIDAD
    // =================================================================
    const sanitizeHTML = (str) => {
        if (!str) return '';
        const temp = document.createElement('div');
        temp.textContent = str;
        return temp.innerHTML;
    };

    const formatCurrency = (price) => {
        const number = parseFloat(price);
        return isNaN(number) ? '$0.00' : number.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
    };

    // =================================================================
    // LÓGICA DE RENDERIZADO
    // =================================================================
    function createPromotionCard(promo) {
        const card = document.createElement('div');
        card.className = 'promo-card bg-white rounded-lg shadow-md overflow-hidden group flex flex-col';

        const sanitizedProductName = sanitizeHTML(promo.product_name) || 'Producto sin nombre';
        const sanitizedDescription = sanitizeHTML(promo.description) || 'Sin descripción disponible.';
        const imageUrl = promo.image_url || 'https://placehold.co/600x400/cccccc/000000?text=IMAGEN+NO+DISPONIBLE';
        const formattedPrice = formatCurrency(promo.price);

        card.innerHTML = `
            <div class="overflow-hidden h-48">
                <img src="${imageUrl}" alt="${sanitizedProductName}" class="w-full h-full object-cover promo-card-image" loading="lazy">
            </div>
            <div class="p-6 flex flex-col flex-grow">
                <h4 class="text-xl font-extrabold text-[var(--color-primary)] mb-2 uppercase flex items-center gap-2">
                    <i data-lucide="tag" class="w-6 h-6 text-[var(--color-secondary)]"></i> ${sanitizedProductName}
                </h4>
                <p class="text-gray-600 text-sm mb-4 flex-grow">${sanitizedDescription}</p>
                <div class="flex items-center justify-between mb-4">
                    <span class="text-[var(--color-secondary)] text-2xl font-extrabold">${formattedPrice}</span>
                </div>
                <a href="${promo.purchase_url}" target="_blank" rel="noopener noreferrer" class="btn-secondary w-full mt-auto py-2 px-4 rounded-lg font-bold flex items-center justify-center gap-2 uppercase">
                    VER DETALLES <i data-lucide="arrow-right" class="w-4 h-4"></i>
                </a>
            </div>
        `;
        return card;
    }
    
    function renderPromotions(promotions) {
        if (!UI.promotionsContainer) return;

        // Usar un DocumentFragment para optimizar la inserción en el DOM
        const fragment = document.createDocumentFragment();
        promotions.forEach(promo => {
            fragment.appendChild(createPromotionCard(promo));
        });
        UI.promotionsContainer.appendChild(fragment);

        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    }

    function updateLoadMoreButton() {
        if (!UI.loadMoreButton) return;

        if (STATE.isLoading) {
            UI.loadMoreButton.textContent = 'Cargando...';
            UI.loadMoreButton.disabled = true;
        } else {
            const hasMore = STATE.loadedCount < STATE.totalAvailable;
            UI.loadMoreButton.classList.toggle('hidden', !hasMore);
            if (hasMore) {
                UI.loadMoreButton.textContent = 'Cargar Más Recursos';
                UI.loadMoreButton.disabled = false;
            }
        }
    }
    
    function showEmptyState() {
        if (UI.promotionsContainer) {
            UI.promotionsContainer.innerHTML = `<p class="col-span-full text-center text-gray-500">No hay recursos de marketing disponibles.</p>`;
        }
        if (UI.loadMoreButton) {
            UI.loadMoreButton.classList.add('hidden');
        }
    }

    function showErrorState(message = "No se pudieron cargar los recursos. Por favor, intente más tarde.") {
       if (UI.promotionsContainer) {
            UI.promotionsContainer.innerHTML = `<p class="col-span-full text-center text-red-500">${message}</p>`;
        }
        if (UI.loadMoreButton) {
            UI.loadMoreButton.classList.add('hidden');
        }
    }

    // =================================================================
    // LÓGICA DE DATOS (API)
    // =================================================================
    async function fetchPromotions() {
        if (STATE.isLoading) return;

        STATE.isLoading = true;
        updateLoadMoreButton();

        const url = `admin/admin_promotions.php?limit=${STATE.perPage}&offset=${STATE.loadedCount}`;

        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Error del servidor: ${response.status}`);
            }
            const data = await response.json();
            
            STATE.totalAvailable = data.total || 0;
            STATE.loadedCount += data.promotions.length;

            if (STATE.loadedCount === 0) {
                showEmptyState();
            } else {
                renderPromotions(data.promotions);
            }
            
        } catch (error) {
            console.error('Error al obtener las promociones:', error);
            showErrorState();
        } finally {
            STATE.isLoading = false;
            updateLoadMoreButton();
        }
    }

    // =================================================================
    // MANEJO DE EVENTOS E INICIALIZACIÓN
    // =================================================================
    function setupEventListeners() {
        if (UI.loadMoreButton) {
            UI.loadMoreButton.addEventListener('click', fetchPromotions);
        }

        if (UI.mobileMenuButton) {
            UI.mobileMenuButton.addEventListener('click', () => {
                UI.sidebar?.classList.toggle('-translate-x-full');
                UI.sidebarOverlay?.classList.toggle('hidden');
            });
        }

        if (UI.sidebarOverlay) {
            UI.sidebarOverlay.addEventListener('click', () => {
                UI.sidebar?.classList.add('-translate-x-full');
                UI.sidebarOverlay?.classList.add('hidden');
            });
        }
    }

    function init() {
        if (!UI.promotionsContainer) {
            console.error('Contenedor de promociones no encontrado. La aplicación no puede iniciarse.');
            return;
        }

        // Limpiar contenedor al inicio
        UI.promotionsContainer.innerHTML = '';

        // Manejar notificaciones iniciales
        const urlParams = new URLSearchParams(window.location.search);
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');
        if (notificationType && notificationMessage && typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        }

        // Aplicar máscara de teléfono si existe el campo
        if (UI.phoneInput && typeof IMask !== 'undefined') {
            IMask(UI.phoneInput, { mask: '(000) 000-0000' });
        }

        setupEventListeners();
        fetchPromotions(); // Carga inicial
    }

    // Iniciar la aplicación cuando el DOM esté listo
    document.addEventListener('DOMContentLoaded', init);

})();
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {

    // Función principal que maneja el ocultamiento, la reaparición y el Local Storage
    const toggleWidgetVisibility = (widgetId, isHidden) => {
        const widget = document.getElementById(widgetId);
        // Encuentra el contenedor del botón de mostrar usando el data-widget-id
        const showContainer = document.querySelector(`.show-widget-container [data-widget-id="${widgetId}"]`)?.closest('.show-widget-container');
        const videoPlayer = widget ? widget.querySelector('video') : null;

        if (!widget || !showContainer) return; // Se detiene si no encuentra los elementos

        if (isHidden) {
            // Acción para OCULTAR
            widget.classList.add('hidden');
            showContainer.classList.remove('hidden');
            // IMPORTANTE: Detiene el video para ahorrar recursos
            if (videoPlayer) videoPlayer.pause(); 
        } else {
            // Acción para MOSTRAR
            widget.classList.remove('hidden');
            showContainer.classList.add('hidden');
        }

        // Guarda la preferencia en Local Storage, individualmente para cada widget
        localStorage.setItem(`hide_${widgetId}`, isHidden ? 'true' : 'false');
    };

    // 1. Configurar los botones de OCULTAR (clase: hide-widget-btn)
    document.querySelectorAll('.hide-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a ocultar
            toggleWidgetVisibility(widgetId, true); 
        });
    });

    // 2. Configurar los botones de MOSTRAR (clase: show-widget-btn)
    document.querySelectorAll('.show-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a mostrar
            toggleWidgetVisibility(widgetId, false); 
        });
    });

    // 3. Comprobar y aplicar el estado guardado al cargar la página para TODOS los widgets
    document.querySelectorAll('.video-widget').forEach(widget => {
        const widgetId = widget.id;
        const isHidden = localStorage.getItem(`hide_${widgetId}`) === 'true';
        if (isHidden) {
            // Si el usuario lo ocultó antes, se aplica el estado de oculto
            toggleWidgetVisibility(widgetId, true);
        }
    });
});
</script>
</body>
</html>