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

include_once 'db/db_connection.php';

$db_error_message = null;

try {
    $stmt = $pdo->query("SELECT * FROM website_config WHERE id = 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        $company_name_from_db = htmlspecialchars($config['company_name'] ?? 'Nombre de la Empresa');
        $contact_phone_from_db = htmlspecialchars($config['phone_primary'] ?? '');
        $website_url_from_db = htmlspecialchars($config['website_url'] ?? '');
        $value_proposition_from_db = htmlspecialchars($config['value_proposition'] ?? '');
    } else {
        $company_name_from_db = 'Nombre de la Empresa';
        $contact_phone_from_db = '';
        $website_url_from_db = '';
        $value_proposition_from_db = '';
        $db_error_message = 'No se encontró la configuración. Se usarán valores por defecto.';
    }
} catch (PDOException $e) {
    error_log("Error PDO al cargar configuración web: " . $e->getMessage());
    $company_name_from_db = 'Nombre de la Empresa';
    $contact_phone_from_db = '';
    $website_url_from_db = '';
    $value_proposition_from_db = '';
    $db_error_message = 'Error de Base de Datos al cargar configuración: ' . $e->getMessage();
} catch (Exception $e) {
    error_log("General Error al cargar configuración web: " . $e->getMessage());
    $company_name_from_db = 'Nombre de la Empresa';
    $contact_phone_from_db = '';
    $website_url_from_db = '';
    $value_proposition_from_db = '';
    $db_error_message = 'Error inesperado al cargar configuración: ' . $e->getMessage();
}

ob_end_clean();

// Datos de imágenes
require_once 'ia-stock/imagenes-limpieza.php';

shuffle($todasLasImagenes);

$imagenesProcesadas = [];
foreach ($todasLasImagenes as $img) {
    $rutaCompleta = 'ia-stock/images/' . $img['filename'];
    $orientacion = 'horizontal';

    if (file_exists($rutaCompleta)) {
        list($ancho, $alto) = getimagesize($rutaCompleta);
        if ($alto > $ancho) {
            $orientacion = 'vertical';
        }
    }
    
    $img['orientation'] = $orientacion;
    $imagenesProcesadas[] = $img;
}

$initialImagesToShow = 8;
$imagenesIniciales = array_slice($imagenesProcesadas, 0, $initialImagesToShow);
$totalImages = count($imagenesProcesadas);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Stock Imágenes IAStock™ 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">
    <script src="files/header-manager.js"></script>
<style>
    /* ---------- HERO / BANNER ---------- */
    .hero-image-overlay { position: relative; background-size: cover; background-position: center; border-radius: 12px; height: 250px; overflow: hidden; display: flex; align-items: center; justify-content: center; }
    .hero-image-overlay::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.7); }
    .overlay-text { position: relative; z-index: 10; }
    /* ---------- IMAGE CARDS ---------- */
    .image-card { background: #ffffff; border: 1px solid #e5e7eb; border-radius: 16px; overflow: hidden; display: flex; flex-direction: column; transition: all .2s ease; box-shadow: 0 6px 14px -8px rgba(2,6,23,.25); }
    .image-card:hover { transform: translateY(-6px); box-shadow: 0 18px 28px -14px rgba(2,6,23,.35); }
    .image-card__thumbnail { position: relative; background: #eef2f7; aspect-ratio: 4/3; overflow: hidden; }
    .image-card__thumbnail img { width: 100%; height: 100%; object-fit: cover; display: block; opacity: 0; transition: opacity .25s ease, transform .35s ease; }
    .image-card.loaded .image-card__thumbnail img { opacity: 1; }
    .image-card:hover .image-card__thumbnail img { transform: scale(1.03); }
    .thumb-skeleton { position: absolute; inset: 0; background: linear-gradient(90deg, #eef2f7 25%, #f5f7fb 37%, #eef2f7 63%); background-size: 400% 100%; animation: shimmer 1.2s infinite; }
    @keyframes shimmer { 0% { background-position: 100% 0 } 100% { background-position: 0 0 } }
    .image-card__content { padding: .8rem 1rem; display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; border-top: 1px solid #eef2f7; }
    .info-pill { display: inline-flex; align-items: center; gap: .4rem; padding: .28rem .6rem; border-radius: 999px; font-size: .74rem; font-weight: 800; }
    .pill--category { background: #f3f4f6; color: #374151; }
    .pill--orientation { background: #e0e7ff; color: #3730a3; }
    .image-card__actions { display: grid; grid-template-columns: 1fr 1fr; gap: .7rem; padding: 0 1rem 1rem; margin-top: .5rem; }
    .image-card__btn { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; padding: .6rem 1rem; border-radius: 10px; font-weight: 700; text-decoration: none; transition: .2s ease; font-size: .9rem; }
    .image-card__btn--view { background: #f3f4f6; color: #111827; border: 1px solid #e5e7eb; }
    .image-card__btn--view:hover { background: #e7eaf0; }
    .image-card__btn--download { background: var(--color-primary); color: #fff; }
    .image-card__btn--download:hover { filter: brightness(.95); }
    /* ---------- MODAL UNIFICADO ---------- */
    #modal { position: fixed; inset: 0; background: rgba(0, 0, 0, .8); z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 1rem; backdrop-filter: blur(5px); opacity: 0; visibility: hidden; transition: opacity .25s ease, visibility .25s ease; }
    #modal.show { opacity: 1; visibility: visible; }
    .modal-content { background: #000; border-radius: 16px; padding: 0; width: min(100%, 1080px); max-height: 90vh; display: flex; flex-direction: column; overflow: hidden; }
    .modal-header { display: flex; align-items: center; justify-content: space-between; padding: .85rem 1rem; border-bottom: 1px solid rgba(255,255,255,.1); background: #111; color: #fff; }
    .modal-title { font-weight: 800; font-size: 1rem; color: #fff; }
    .modal-actions { display: flex; align-items: center; gap: .5rem; }
    .modal-actions a { display: inline-flex; align-items: center; gap: .4rem; background: #fff; color: #0f172a; padding: .5rem .8rem; border-radius: 8px; font-weight: 800; text-decoration: none; transition: .2s ease; }
    .modal-actions a:hover { background: #f3f4f6; }
    .modal-close-btn { background: transparent; color: #fff; border: none; padding: 0.4rem 0.55rem; display: flex; align-items: center; justify-content: center; cursor: pointer; opacity: .8; transition: opacity .2s ease; }
    .modal-close-btn:hover { opacity: 1; }
    .modal-image-container { background: black; display: flex; align-items: center; justify-content: center; }
    .modal-image-container img { max-width: 100%; max-height: 80vh; object-fit: contain; }
    #image-grid-container { margin-top: 2rem; }

    /* ---------- NUEVOS ESTILOS PARA FILTROS ---------- */
    .filter-controls { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; margin-bottom: 2rem; padding: 1rem; background-color: #f9fafb; border-radius: 12px; border: 1px solid #e5e7eb; }
    .search-wrapper { position: relative; flex-grow: 1; min-width: 250px; }
    #search-input { width: 100%; padding: .75rem 1rem .75rem 2.5rem; border-radius: 8px; border: 1px solid #d1d5db; font-weight: 500; transition: all .2s; }
    #search-input:focus { outline: none; border-color: var(--color-primary); box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3); }
    .search-wrapper .icon { position: absolute; top: 50%; left: .8rem; transform: translateY(-50%); color: #6b7280; }
    .orientation-filters { display: flex; gap: .5rem; background: #e5e7eb; padding: .3rem; border-radius: 8px; }
    .orientation-filters button { padding: .5rem 1rem; border: none; background: transparent; border-radius: 6px; font-weight: 700; cursor: pointer; transition: all .2s; color: #374151; }
    .orientation-filters button.active { background: #ffffff; color: var(--color-primary); box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
    #no-results-message { display: none; text-align: center; padding: 3rem 1rem; background-color: #f9fafb; border-radius: 12px; }
</style>
</head>

<body
    data-page-title="Imágenes Para Negocios De Limpieza"
    data-page-subtitle="Recursos visuales para potenciar tu marca"
    data-page-icon="image">
    
   <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 'stock-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>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="bienvenida-ia-stock" class="p-0">
                <div class="relative overflow-hidden rounded-2xl md:rounded-3xl bg-gradient-to-br from-[var(--color-primary)] via-[#0b2242] to-[#07162d] text-white">
                    <div class="absolute -top-24 -left-16 h-72 w-72 rounded-full blur-3xl opacity-30 bg-[var(--color-secondary)]"></div>
                    <div class="absolute -bottom-24 -right-16 h-72 w-72 rounded-full blur-3xl opacity-30 bg-[var(--color-highlight)]"></div>

                    <div class="relative p-6 md:p-10">
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
                            <div>
                                <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="sparkles" class="w-4 h-4"></i>
                                    <span class="text-xs tracking-wide uppercase font-semibold">Contenido para tu Negocio</span>
                                </div>
                                <h1 class="text-3xl md:text-4xl font-extrabold leading-tight tracking-tight">
                                    <span class="text-[var(--color-highlight)]">Imágenes</span> Para Negocios
                                    <span class="block text-white/90 text-2xl md:text-4xl mt-1">De Limpieza Profesional</span>
                                </h1>
                                <p class="text-white/80 mt-4 max-w-2xl text-base md:text-lg">
                                    Ahorra tiempo y encuentra imágenes profesionales listas para usar en tus anuncios y redes sociales. Haz que tu negocio de limpieza destaque.
                                </p>
                                <div class="mt-6 flex flex-wrap gap-3">
                                    <a href="#image-grid" class="inline-flex items-center gap-2 text-sm font-bold px-4 py-2 rounded-lg bg-[var(--color-highlight)] text-slate-900 hover:opacity-90 transition-all transform hover:scale-105">
                                        <i data-lucide="image" class="w-5 h-5"></i> EXPLORAR IMÁGENES
                                    </a>
                                </div>
                            </div>
                            <div class="hidden lg:block">
                                <div class="hero-image-overlay" style="background-image: url('/ia-stock/videos/thumbnails/limpieza-stock-01.jpg');">
                                    <div class="overlay-text text-center text-white p-4">
                                        <div class="flex items-center justify-center space-x-2">
                                            <i data-lucide="gem" class="w-12 h-12 text-white drop-shadow-lg"></i>
                                            <p class="text-6xl md:text-7xl font-extrabold drop-shadow-lg text-white"><?php echo $totalImages; ?></p>
                                        </div>
                                        <p class="text-sm uppercase font-semibold tracking-wider" style="color: var(--color-highlight);">Imágenes Disponibles</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            
            <section id="filter-section" class="mt-8">
                <div class="filter-controls">
                    <div class="search-wrapper">
                         <i data-lucide="search" class="icon w-5 h-5"></i>
                         <input type="search" id="search-input" placeholder="Buscar Por ID (ej: LMP005)">
                    </div>
                    <div id="orientation-filter-buttons" class="orientation-filters">
                        <button type="button" data-filter="all" class="active">TODOS</button>
                        <button type="button" data-filter="horizontal">HORIZONTALES</button>
                        <button type="button" data-filter="vertical">VERTICALES</button>
                    </div>
                </div>
            </section>

            <section id="image-grid-container">
                <div id="image-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <?php foreach ($imagenesIniciales as $img): ?>
                        <?php
                            $imagePath = 'ia-stock/images/' . htmlspecialchars($img['filename']);
                            $category = htmlspecialchars($img['category']);
                            $orientation = htmlspecialchars($img['orientation']);
                            $id = htmlspecialchars($img['id']); // ID añadido
                        ?>
                        <article class="image-card" data-full-image="<?php echo $imagePath; ?>" data-category="<?php echo $category; ?>" data-filename="<?php echo htmlspecialchars($img['filename']); ?>" data-id="<?php echo $id; ?>">
                            <div class="image-card__thumbnail">
                                <div class="thumb-skeleton" aria-hidden="true"></div>
                                <img src="<?php echo $imagePath; ?>" alt="Imagen de <?php echo $category; ?>" loading="lazy"
                                     onerror="this.onerror=null;this.src='https://placehold.co/640x480/eef2f7/9aa4b2?text=Imagen'; this.style.objectFit='contain';">
                            </div>
                            <div class="image-card__content">
                                <span class="info-pill pill--category"><i data-lucide="asterisk"></i><?php echo $id; ?></span>
                                <span class="info-pill pill--orientation">
                                    <?php if ($orientation === 'vertical'): ?> <i data-lucide="rectangle-vertical"></i> Vertical
                                    <?php else: ?> <i data-lucide="rectangle-horizontal"></i> Horizontal
                                    <?php endif; ?>
                                </span>
                            </div>
                            <div class="image-card__actions">
                                <button type="button" class="image-card__btn image-card__btn--view"><i data-lucide="eye" class="w-4 h-4"></i> VER</button>
                                <a href="<?php echo $imagePath; ?>" download class="image-card__btn image-card__btn--download"><i data-lucide="download" class="w-4 h-4"></i> DESCARGAR</a>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
                <div id="no-results-message" class="hidden mt-8">
                    <h3 class="text-xl font-bold text-gray-700">NO SE ENCONTRARON RESULTADOS</h3>
                    <p class="text-gray-500 mt-2">Intenta Ajustar Tu Búsqueda O Filtros</p>
                </div>
                <div id="load-more-container" class="flex justify-center mt-12">
                    <button id="load-more-btn" class="bg-[var(--color-highlight)] text-[var(--color-primary)] font-extrabold py-3 px-8 rounded-lg hover:opacity-90 transition flex items-center justify-center gap-2">
                        <i data-lucide="plus-circle" class="w-5 h-5"></i>
                        <span>CARGAR MÁS IMAGENES</span>
                    </button>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="modal" class="fixed inset-0 z-50 flex justify-center items-center p-4">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-title font-bold text-lg" id="modal-title"></div>
            <div class="modal-actions">
                <a id="modal-download" href="#" download class="bg-white text-slate-900 hover:bg-gray-200 px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 transition-colors">
                    <i data-lucide="download" class="w-4 h-4"></i> DESCARGAR
                </a>
                <button class="modal-close-btn p-2 text-white hover:text-gray-300">
                    <i data-lucide="x" class="w-6 h-6"></i>
                </button>
            </div>
        </div>
        <div class="modal-image-container">
            <img id="modal-img" src="" alt="Vista previa de la imagen">
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();

    // --- ELEMENTOS DEL DOM ---
    const modal = document.getElementById('modal');
    const modalImg = document.getElementById('modal-img');
    const modalTitle = document.getElementById('modal-title');
    const modalDownload = document.getElementById('modal-download');
    const closeModalBtn = modal.querySelector('.modal-close-btn');
    const imageGrid = document.getElementById('image-grid');
    const searchInput = document.getElementById('search-input');
    const filterButtons = document.getElementById('orientation-filter-buttons');
    const noResultsMessage = document.getElementById('no-results-message');
    const loadMoreContainer = document.getElementById('load-more-container');

    // --- DATOS Y ESTADO ---
    const allImagesData = <?php echo json_encode($imagenesProcesadas, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    let filtersAreActive = false;

    // --- FUNCIÓN PARA CREAR TARJETAS HTML ---
    const createCardHTML = (image) => {
        const imagePath = `ia-stock/images/${image.filename}`;
        const orientationPill = image.orientation === 'vertical'
            ? `<span class="info-pill pill--orientation"><i data-lucide="rectangle-vertical"></i> Vertical</span>`
            : `<span class="info-pill pill--orientation"><i data-lucide="rectangle-horizontal"></i> Horizontal</span>`;

        return `
        <article class="image-card" data-full-image="${imagePath}" data-category="${image.category}" data-filename="${image.filename}" data-id="${image.id}">
            <div class="image-card__thumbnail">
                <div class="thumb-skeleton"></div>
                <img src="${imagePath}" alt="Imagen de ${image.category}" loading="lazy" onerror="this.onerror=null;this.src='https://placehold.co/640x480/eef2f7/9aa4b2?text=Error';">
            </div>
            <div class="image-card__content">
                <span class="info-pill pill--category"><i data-lucide="asterisk"></i>${image.id}</span>
                ${orientationPill}
            </div>
            <div class="image-card__actions">
                <button type="button" class="image-card__btn image-card__btn--view"><i data-lucide="eye" class="w-4 h-4"></i> VER</button>
                <a href="${imagePath}" download class="image-card__btn image-card__btn--download"><i data-lucide="download" class="w-4 h-4"></i> DESCARGAR</a>
            </div>
        </article>`;
    };

    // --- INTERSECTION OBSERVER PARA LAZY LOADING ---
    const io = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (!entry.isIntersecting) return;
            const card = entry.target;
            const img = card.querySelector('img');
            const done = () => { card.classList.add('loaded'); const sk = card.querySelector('.thumb-skeleton'); if (sk) sk.remove(); };
            if (img.complete) { done(); } else { img.addEventListener('load', done, { once:true }); }
            io.unobserve(card);
        });
    }, { rootMargin: '200px 0px' });

    // Observar las imágenes iniciales cargadas por PHP
    document.querySelectorAll('.image-card').forEach(card => io.observe(card));
    
    // --- LÓGICA DE FILTRADO Y RENDERIZADO ---
    const applyFiltersAndRender = () => {
        const searchTerm = searchInput.value.toLowerCase();
        const orientation = filterButtons.querySelector('.active').dataset.filter;

        if (!filtersAreActive && searchTerm === '' && orientation === 'all') return;
        filtersAreActive = true;
        
        loadMoreContainer.style.display = 'none'; // Ocultar "Cargar Más" al filtrar

        const filteredImages = allImagesData.filter(image => {
            const matchesId = image.id.toLowerCase().includes(searchTerm);
            const matchesOrientation = (orientation === 'all' || image.orientation === orientation);
            return matchesId && matchesOrientation;
        });

        imageGrid.innerHTML = filteredImages.map(createCardHTML).join('');
        
        if (filteredImages.length === 0) {
            noResultsMessage.style.display = 'block';
        } else {
            noResultsMessage.style.display = 'none';
        }
        
        imageGrid.querySelectorAll('.image-card').forEach(card => io.observe(card));
        lucide.createIcons();
    };

    // --- EVENT LISTENERS PARA FILTROS ---
    searchInput.addEventListener('input', applyFiltersAndRender);
    filterButtons.addEventListener('click', (e) => {
        const button = e.target.closest('button');
        if (!button) return;
        filterButtons.querySelector('.active').classList.remove('active');
        button.classList.add('active');
        applyFiltersAndRender();
    });

    // --- LÓGICA DEL MODAL (SIN CAMBIOS) ---
    const openModal = (imageUrl, filename) => {
        modalImg.src = imageUrl;
        modalTitle.textContent = filename.split('/').pop();
        modalDownload.href = imageUrl;
        modal.classList.add('show');
    };
    const closeModal = () => {
        modal.classList.remove('show');
        modalImg.src = "";
    };
    closeModalBtn.addEventListener('click', closeModal);
    modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });
    imageGrid.addEventListener('click', (e) => {
        const isViewBtn = e.target.closest('.image-card__btn--view');
        if (!isViewBtn) return;
        const card = isViewBtn.closest('.image-card');
        openModal(card.dataset.fullImage, card.dataset.filename);
    });

    // --- LÓGICA ORIGINAL DE "CARGAR MÁS" (adaptada) ---
    // Esta lógica solo se ejecutará si nunca se usan los filtros.
    let currentPage = 1;
    const itemsPerPage = 8;
    const loadMoreBtn = document.getElementById('load-more-btn');

    loadMoreBtn.addEventListener('click', () => {
        if (filtersAreActive) return; // No hacer nada si los filtros están activos

        const start = currentPage * itemsPerPage;
        const end = start + itemsPerPage;
        const newImages = allImagesData.slice(start, end);

        if (newImages.length > 0) {
            const newCardsHTML = newImages.map(createCardHTML).join('');
            imageGrid.insertAdjacentHTML('beforeend', newCardsHTML);
            
            // Observar solo las nuevas tarjetas
            const addedCards = Array.from(imageGrid.children).slice(start);
            addedCards.forEach(card => io.observe(card));

            currentPage++;
            lucide.createIcons();
        }

        if (end >= allImagesData.length) {
            loadMoreContainer.style.display = 'none';
        }
    });

    if (allImagesData.length <= initialImagesToShow) {
        loadMoreContainer.style.display = 'none';
    }
});
</script>
</body>
</html>