<?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);
ob_end_clean();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Sección Hero FlowCMS™ 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>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
    <style>
    body {
    --brand-primary: #07162d; 
    --brand-secondary: #ffc857;
    --brand-accent: #9e1428; 
    --brand-light: #f5f5f5;
    --brand-dark: #040d1a; 
    }
        .toast-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .toast {
            background-color: #333;
            color: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            opacity: 0;
            transform: translateY(20px);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
            min-width: 250px;
        }
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
        .file-upload-preview {
            width: 100%;
            height: 150px;
            border: 2px dashed #d1d5db;
            border-radius: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            background-size: cover;
            background-position: center;
            position: relative;
            color: #6b7280;
            font-weight: 600;
            background-image: url('img/default-preview-bg.webp'); 
        }
        .file-upload-preview.has-image::before {
            content: '';
            position: absolute;
            inset: 0;
            background-color: rgba(0,0,0,0.5);
            border-radius: 0.5rem;
        }
        .file-upload-preview .upload-text { z-index: 10; }
        .file-upload-preview input[type="file"] { display: none; }
        
        #preview-wrapper {
            border: 1px solid #e5e7eb;
            box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            overflow: hidden;
            width: 100%;
        }
        #preview-wrapper .hero-section-bg { background-size: cover; background-position: center; }
        #preview-wrapper h1, #preview-wrapper p { font-size: clamp(0.5rem, 1.5vw, 0.8rem); line-height: 1.2; }
        #preview-wrapper h1 span:first-child { font-size: clamp(0.6rem, 2vw, 1rem); }
        #preview-wrapper h1 span:last-child { font-size: clamp(0.7rem, 2.5vw, 1.2rem); }
        #preview-wrapper a[href="#quote-form"] { padding: 0.5rem 0.75rem; font-size: 0.7rem; }

    </style>
</head>
<body data-page-title="SiteFlow® Presentación Del Problema"
      data-page-subtitle="Modifica Los Elementos Visuales Y De Texto De La Sección"
      data-page-icon="home">

    <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 'cms-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="editor-hero" class="dashboard-section">
                <form id="hero-editor-form" action="cms/hero-update.php" method="POST" enctype="multipart/form-data">
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                        
                        <div class="lg:col-span-1 bg-white p-6 rounded-xl shadow-md space-y-6">
                            
                            <div>
                                <h4 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="text" class="w-6 h-6 text-[var(--color-primary)]"></i> CONTENIDO DE TEXTO</h4>
                                <div class="space-y-4">
                                    <div>
                                        <label for="hero-title-1" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 1)</label>
                                        <input type="text" id="hero-title-1" name="hero_title_1" class="w-full p-3 border border-gray-300 rounded-lg">
                                    </div>
                                    <div>
                                        <label for="hero-title-2" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Título (Línea 2)</label>
                                        <input type="text" id="hero-title-2" name="hero_title_2" class="w-full p-3 border border-gray-300 rounded-lg">
                                    </div>
                                    <div>
                                        <label for="hero-description" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Texto (Descripción)</label>
                                        <textarea id="hero-description" name="hero_description" rows="4" class="w-full p-3 border border-gray-300 rounded-lg"></textarea>
                                    </div>
                                </div>
                            </div>

                            <div class="border-t border-gray-200 pt-6">
                                <h4 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="image" class="w-6 h-6 text-[var(--color-primary)]"></i> CONTENIDO MULTIMEDIA</h4>
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div>
                                        <label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Imagen de Fondo</label>
                                        <label for="hero-bg-image-upload" class="file-upload-preview cursor-pointer has-image" id="hero-bg-image-preview">
                                            <span class="upload-text bg-white/80 px-4 py-2 rounded-md">Cambiar Imagen</span>
                                            <input type="file" id="hero-bg-image-upload" name="hero_bg_image" accept="image/*">
                                            <input type="hidden" id="current-bg-image" name="current_bg_image" value=""> 
                                        </label>
                                    </div>
                                    <div>
                                        <label class="block text-gray-700 text-sm font-bold mb-2 uppercase">Imagen Principal</label>
                                        <label for="hero-main-image-upload" class="file-upload-preview cursor-pointer has-image" id="hero-main-image-preview">
                                            <span class="upload-text bg-white/80 px-4 py-2 rounded-md">Cambiar Imagen</span>
                                            <input type="file" id="hero-main-image-upload" name="hero_main_image" accept="image/*">
                                            <input type="hidden" id="current-main-image" name="current_main_image" value="">
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="border-t border-gray-200 pt-6 flex justify-end gap-4">
                                <button type="submit" class="btn-primary font-bold py-3 px-8 rounded-lg uppercase text-sm flex items-center justify-center gap-2">
                                    <i data-lucide="save" class="w-5 h-5"></i>
                                    <span>Guardar Cambios</span>
                                </button>
                            </div>
                        </div>
                        
                        <div class="lg:col-span-1 space-y-8">
                            <div class="space-y-4">
                                <div id="preview-wrapper" class="rounded-lg">
                                    <section id="preview-hero" class="relative hero-section-bg h-full w-full" style="background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('img/default-bg.webp');">
                                        <div class="relative max-w-7xl mx-auto flex items-center gap-4 p-4 md:p-6 h-full">
                                            <div class="w-1/2 text-left text-white flex flex-col justify-center">
                                                <div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-white/10 text-brand-secondary font-semibold tracking-widest ring-1 ring-white/20">
                                                    <script type="text/javascript">
                                                         var day = new Date();
                                                         var currentHour = day.getHours();
                                                         var greetingText;
                                                         var iconName;
                                                         var styleClass = 'text-xl sm:text-2xl font-extrabold tracking-wider text-brand-secondary'; 
                                                         if (currentHour >= 0 && currentHour < 12) {
                                                             greetingText = "Hello, Good Morning!";
                                                             iconName = "sun";
                                                         } else if (currentHour >= 12 && currentHour <= 17) {
                                                             greetingText = "Hello, Good Afternoon!";
                                                             iconName = "cloud-sun";
                                                         } else {
                                                             greetingText = "Hello, Good Evening!";
                                                             iconName = "moon";
                                                         }
                                                         document.write(`<span class="inline-flex items-center gap-3 ${styleClass}"><i data-lucide="${iconName}" class="w-7 h-7"></i><span>${greetingText}</span></span>`);
                                                         if (window.lucide && typeof window.lucide.createIcons === 'function') {
                                                             setTimeout(window.lucide.createIcons, 100);
                                                         }
                                                    </script>
                                                </div>
                                                <h1 class="font-extrabold leading-tight mt-1">
                                                    <span id="preview-title-1" class="block text-white">DUST, CLUTTER & MESS</span>
                                                    <span id="preview-title-2" class="block text-[var(--color-highlight)]">ARE TAKING OVER YOUR LIFE</span>
                                                </h1>
                                                <p id="preview-description" class="mt-2 text-xs text-white/90">A dirty home or office doesn’t just look bad — it drains your energy, causes stress, and makes every day harder than it should be. No one should feel uncomfortable in their own space.</p>
                                                <div class="mt-4">
                                                    <a href="#quote-form" class="bg-[var(--color-secondary)] text-white font-bold rounded-md inline-flex items-center gap-1">Request A Free Quote <i data-lucide="arrow-big-right-dash" class="w-3 h-3"></i></a>
                                                </div>
                                            </div>
                                            <div class="w-1/2 flex justify-center items-center">
                                                <img id="preview-main-image" src="img/default-main-image.webp" alt="Preview" class="w-full rounded-md shadow-lg object-cover h-auto max-h-[200px]">
                                            </div>
                                        </div>
                                    </section>
                                </div>
                            </div>
                            
                        <div id="video-instrucciones" class="space-y-6">
                            <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" id="videoPlayer" controls controlslist="nodownload fullscreen" 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 Tutorial
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2–3 min
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <div class="text-center md:text-left mb-6">
                                    <h4 class="text-2xl font-black uppercase text-black flex items-center justify-center md:justify-start">
                                        <i data-lucide="book-open" class="mr-3 text-[var(--color-highlight)] w-7 h-7"></i>
                                        INSTRUCCIONES IMPORTANTES
                                    </h4>
                                    <p class="step-subtitle uppercase text-sm mt-1 text-gray-500">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                                </div>

                                <div class="space-y-4">
                                    <div class="flex items-start gap-3">
                                        <i data-lucide="play-circle" class="w-5 h-5 mt-0.5" style="color: var(--color-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">REVISA EL VIDEO DE INSTRUCCIONES</h5>
                                            <p class="text-sm text-gray-600">Comprende cómo utilizar la plataforma y sácale el máximo provecho a todas sus herramientas.</p>
                                        </div>
                                    </div>

                                    <div class="flex items-start gap-3">
                                        <i data-lucide="target" class="w-5 h-5 mt-0.5" style="color: var(--color-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">DEFINE BIEN LOS OBJETIVOS</h5>
                                            <p class="text-sm text-gray-600">Identifica qué quieres lograr con esta sección de la página web para una estrategia más efectiva.</p>
                                        </div>
                                    </div>

                                    <div class="flex items-start gap-3">
                                        <i data-lucide="file-text" class="w-5 h-5 mt-0.5" style="color: var(--color-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">SÉ PRECISO Y CONCISO</h5>
                                            <p class="text-sm text-gray-600">Redacta textos persuasivos y enfocados en el valor que ofreces para impulsar tus ventas.</p>
                                        </div>
                                    </div>

                                    <div class="flex items-start gap-3">
                                        <i data-lucide="refresh-cw" class="w-5 h-5 mt-0.5" style="color: var(--color-secondary);"></i>
                                        <div>
                                            <h5 class="font-black text-gray-800">MANTÉN LA INFORMACIÓN ACTUALIZADA</h5>
                                            <p class="text-sm text-gray-600">Actualiza la información regularmente (al menos cada 3 meses) para mantener tu contenido relevante y dinámico.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </section>
        </div>
    </main>
</div>

<div id="toast-container" class="toast-container"></div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // --- SETUP BÁSICO ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    if (mobileMenuButton && sidebar && sidebarOverlay) {
        mobileMenuButton.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('hidden');
        });
        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.add('-translate-x-full');
            sidebarOverlay.classList.add('hidden');
        });
    }
    lucide.createIcons();
    
    // --- ELEMENTOS PRINCIPALES ---
    const form = document.getElementById('hero-editor-form');
    const heroBgImagePreview = document.getElementById('hero-bg-image-preview');
    const heroMainImagePreview = document.getElementById('hero-main-image-preview');
    const currentBgImage = document.getElementById('current-bg-image');
    const currentMainImage = document.getElementById('current-main-image');
    const previewHeroSection = document.getElementById('preview-hero');
    const previewMainImage = document.getElementById('preview-main-image');
    
    // Asignación de elementos para el enlace rápido de eventos
    const bindings = {
        'hero-title-1': { element: document.getElementById('preview-title-1'), type: 'text' },
        'hero-title-2': { element: document.getElementById('preview-title-2'), type: 'text' },
        'hero-description': { element: document.getElementById('preview-description'), type: 'text' },
    };
    
    // Función para mostrar toasts de notificación
    const showToast = (message, isSuccess) => {
        const toastContainer = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast ${isSuccess ? 'bg-green-500' : 'bg-red-500'}`;
        toast.textContent = message;
        toastContainer.appendChild(toast);
        setTimeout(() => toast.classList.add('show'), 10);
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    };

    // Función auxiliar para construir la ruta correcta (ruta relativa vs absoluta)
    const getFinalPath = (dbPath) => {
        if (!dbPath) return '';
        // Si ya es una URL absoluta (http), la devuelve. Si no, antepone '../' 
        // para ir del directorio CMS al directorio raíz (donde están 'uploads/' o 'img/').
        return dbPath.startsWith('http') ? dbPath : `../${dbPath}`;
    };
    
    // --- LÓGICA DE CARGA DE DATOS (Recuperación de paths) ---
    const loadData = async () => {
        try {
            const response = await fetch('cms/hero-read.php');
            const result = await response.json();
            
            // Asumiendo que el JSON devuelto es { success: true, data: { hero_title_1: ..., hero_bg_image: 'uploads/hero/...' } }
            // Se ajusta para manejar la estructura de datos que vi en otras secciones (directamente 'data')
            const heroData = result.success && result.data && result.data.hero ? result.data.hero : (result.success && result.data ? result.data : {});
            const safeValue = (value) => value ?? '';
            
            if (result.success && heroData) {
                // 1. Cargar Textos
                document.getElementById('hero-title-1').value = safeValue(heroData.hero_title_1);
                document.getElementById('preview-title-1').textContent = safeValue(heroData.hero_title_1);
                
                document.getElementById('hero-title-2').value = safeValue(heroData.hero_title_2);
                document.getElementById('preview-title-2').textContent = safeValue(heroData.hero_title_2);
                
                document.getElementById('hero-description').value = safeValue(heroData.hero_description);
                document.getElementById('preview-description').textContent = safeValue(heroData.hero_description);
                
                // 2. Cargar Imagen de Fondo (CORRECCIÓN APLICADA)
                const bgImagePath = safeValue(heroData.hero_bg_image);
                if (bgImagePath) {
                    const finalBgPath = getFinalPath(bgImagePath);
                    
                    // Preview del editor
                    heroBgImagePreview.style.backgroundImage = `url('${finalBgPath}')`;
                    heroBgImagePreview.classList.add('has-image');
                    
                    // Preview de la sección (Asegura el gradiente)
                    previewHeroSection.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('${finalBgPath}')`;
                    
                    // Campo oculto para el POST de actualización (Guarda la ruta limpia)
                    currentBgImage.value = bgImagePath;
                } else {
                     heroBgImagePreview.style.backgroundImage = '';
                     heroBgImagePreview.classList.remove('has-image');
                     currentBgImage.value = ''; // Limpiar el valor si no hay imagen
                }

                // 3. Cargar Imagen Principal (CORRECCIÓN APLICADA)
                const mainImagePath = safeValue(heroData.hero_main_image);
                if (mainImagePath) {
                    const finalMainPath = getFinalPath(mainImagePath);

                    // Preview del editor
                    heroMainImagePreview.style.backgroundImage = `url('${finalMainPath}')`;
                    heroMainImagePreview.classList.add('has-image');

                    // Preview de la sección
                    previewMainImage.src = finalMainPath;

                    // Campo oculto para el POST de actualización
                    currentMainImage.value = mainImagePath;
                } else {
                    heroMainImagePreview.style.backgroundImage = '';
                    heroMainImagePreview.classList.remove('has-image');
                    previewMainImage.src = 'img/default-main-image.webp'; // Mostrar fallback
                    currentMainImage.value = ''; // Limpiar el valor
                }
            } else if (result.success) {
                 console.warn("Carga exitosa, pero datos de hero vacíos o mal formados.");
            } else {
                 showToast(result.message || 'Error desconocido al cargar datos.', false);
            }
        } catch (error) {
             console.error('Error al cargar los datos:', error);
             showToast('Error de conexión o JSON al cargar datos del Hero.', false);
        }
    };
    
    // --- LÓGICA DE ACTUALIZACIÓN DE PREVIEW DE IMÁGENES AL SUBIR UN ARCHIVO ---
    
    // Función que maneja la previsualización de imágenes locales
    const handleLocalImagePreview = (fileInputId, previewElementId, previewTargetId, isBackground) => {
        const fileInput = document.getElementById(fileInputId);
        const previewElement = document.getElementById(previewElementId);
        
        if (!fileInput || !previewElement) return;

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const imageUrl = event.target.result;

                    // 1. Actualizar preview del editor
                    previewElement.style.backgroundImage = `url('${imageUrl}')`;
                    previewElement.classList.add('has-image');

                    // 2. Actualizar preview del sitio
                    if (isBackground) {
                        const targetElement = document.getElementById(previewTargetId);
                        if (targetElement) {
                            targetElement.style.backgroundImage = `linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5)), url('${imageUrl}')`;
                        }
                    } else {
                        const targetElement = document.getElementById(previewTargetId);
                        if (targetElement) {
                            targetElement.src = imageUrl;
                        }
                    }
                };
                reader.readAsDataURL(file);
            }
        });
    };
    
    // Aplicar la función a las dos imágenes
    handleLocalImagePreview('hero-bg-image-upload', 'hero-bg-image-preview', 'preview-hero', true);
    handleLocalImagePreview('hero-main-image-upload', 'hero-main-image-preview', 'preview-main-image', false);


    // --- BINDING DE TEXTOS ---
    document.getElementById('hero-editor-form').addEventListener('input', (e) => {
        const inputId = e.target.id;
        const binding = bindings[inputId];
        if (binding && binding.type === 'text') {
            binding.element.textContent = e.target.value;
        }
    });

    // --- LÓGICA DE SUBMIT (AJAX) ---
    document.getElementById('hero-editor-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        const saveButton = form.querySelector('button[type="submit"]');
        const originalButtonText = saveButton.innerHTML;

        saveButton.disabled = true;
        saveButton.innerHTML = '<i data-lucide="loader" class="w-5 h-5 animate-spin"></i><span>Guardando...</span>';
        lucide.createIcons();

        try {
            const response = await fetch(form.action, {
                method: form.method,
                body: formData
            });
            const responseText = await response.text();
            
            let result;
            try {
                result = JSON.parse(responseText);
            } catch (jsonError) {
                showToast(`Error de servidor: Respuesta inesperada.<br><br>Respuesta: ${responseText}`, false);
                console.error("Error al parsear JSON:", jsonError, "Respuesta del servidor:", responseText);
                return;
            }
            
            showToast(result.message, result.success);

            if (result.success) {
                // Si el backend devuelve las nuevas rutas (como tu otro update), recargamos
                // si no devuelve rutas, loadData() recargará las rutas de la DB.
                loadData(); 
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar los cambios.', false);
        } finally {
            saveButton.disabled = false;
            saveButton.innerHTML = originalButtonText;
            lucide.createIcons();
        }
    });

    // Iniciar carga de datos
    loadData();
});
</script>

</body>
</html>