<?php
// Incluir el archivo de conexión a la base de datos con la ruta correcta.
include_once 'db/db_connection.php'; // Ruta corregida

ob_start();
error_reporting(E_ALL); // Habilitado para depuración
ini_set('display_errors', 1); // Habilitado para depuración

$db_error_message = null; // Variable para capturar errores de DB en PHP

try {
    // Intentar leer la única fila de configuración (con ID 1)
    $stmt = $pdo->query("SELECT * FROM website_config WHERE id = 1"); //
    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        // Decodificar los campos JSON
        $config['gallery_images'] = json_decode($config['gallery_images'] ?? '[]', true);
        $config['cities_operated'] = json_decode($config['cities_operated'] ?? '[]', true);
        $config['weekly_schedule'] = json_decode($config['weekly_schedule'] ?? '[]', true); // Se asume un array de objetos para el horario semanal
        $config['blocked_dates'] = json_decode($config['blocked_dates'] ?? '[]', true);
        $config['enable_booking'] = (bool)$config['enable_booking']; // Convertir a booleano

        // Asignar variables PHP para usar en el HTML del estimado
        $company_logo_url = htmlspecialchars($config['logo_url'] ?? 'img/placeholder-logo.png'); // Placeholder si no hay logo
        $company_name_from_db = htmlspecialchars($config['company_name'] ?? 'Nombre de la Empresa');
        $contact_name_from_db = htmlspecialchars($config['contact_name'] ?? 'Nombre de Contacto');
        $contact_email_from_db = htmlspecialchars($config['email'] ?? 'correo@ejemplo.com');
        $contact_phone_from_db = htmlspecialchars($config['phone_primary'] ?? 'N/A');

    } else {
        // Si no existe la fila, usar valores por defecto
        $company_logo_url = 'img/placeholder-logo.png';
        $company_name_from_db = 'Nombre de la Empresa';
        $contact_name_from_db = 'Nombre de Contacto';
        $contact_email_from_db = 'correo@ejemplo.com';
        $contact_phone_from_db = 'N/A';
        $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_logo_url = 'img/placeholder-logo.png';
    $company_name_from_db = 'Nombre de la Empresa';
    $contact_name_from_db = 'Nombre de Contacto';
    $contact_email_from_db = 'correo@ejemplo.com';
    $contact_phone_from_db = 'N/A';
    $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_logo_url = 'img/placeholder-logo.png';
    $company_name_from_db = 'Nombre de la Empresa';
    $contact_name_from_db = 'Nombre de Contacto';
    $contact_email_from_db = 'correo@ejemplo.com';
    $contact_phone_from_db = 'N/A';
    $db_error_message = 'Error inesperado al cargar configuración: ' . $e->getMessage();
}

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>LocalCRM ToolKit Dashboard | Tu Página Web | Tu Negocio Todo En Uno | OrozDesign Multiemdia</title>
    <meta name="description" content="Gestiona los datos de tu sitio web en LocalCRM: edita logo, título, descripción, enlaces y configuración general de forma fácil y rápida">
    <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="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script> <style>
        .toggle-checkbox:checked { right: 0; border-color: var(--color-primary); }
        .toggle-checkbox:checked + .toggle-label { background-color: var(--color-primary); }
        /* Estilos para el resumen del negocio en la sección de contenido */
        .business-summary-section-header {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        .business-summary-section-header .logo-mini {
            width: 48px; /* Tamaño del logo en el resumen */
            height: 48px;
            object-fit: contain;
            border-radius: 4px;
        }
        .business-summary-section-header .details p {
            font-size: 0.75rem; /* Texto más pequeño para el resumen */
            color: #4b5563;
            line-height: 1.2;
        }
    </style>
</head>
<body data-page-title="TU PÁGINA WEB CORPORATIVA" 
      data-page-subtitle="ADMINISTRA Y ACTUALIZA TU SITIO WEB" 
      data-page-icon="globe">
    
    <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>

    <?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>
        </header>

        <div id="content-area" class="p-4 md:p-8 space-y-8">
            <section id="pagina-web" 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="monitor" class="w-7 h-7 text-[var(--color-primary)]"></i> CONFIGURACIÓN DE TU WEB
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">AJUSTA LA INFORMACIÓN PRINCIPAL DE TU PÁGINA DE VENTAS.</p>
                        </div>
                        <div id="business-summary-section-header" class="business-summary-section-header hidden md:flex">
                            <img id="summary-logo" src="https://placehold.co/48x48/cccccc/333333?text=Logo" alt="Logo Empresa" class="logo-mini">
                            <div class="details text-right">
                                <p id="summary-company-name" class="font-extrabold text-gray-800 text-lg leading-tight"></p>
                                <p id="summary-contact-name" class="font-medium"></p>
                                <p id="summary-phone"></p>
                                <p id="summary-email"></p>
                                <p id="summary-website"></p>
                            </div>
                        </div>
                    </div>
                    
                    <form id="website-config-form" class="space-y-6">
                        <div class="pb-6">
                            <h4 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2 uppercase">
                                <i data-lucide="image" class="w-5 h-5 text-[var(--color-secondary)]"></i> Logotipo de la Empresa
                            </h4>
                            <div class="flex items-center space-x-4">
                                <div class="relative w-24 h-24 bg-gray-100 rounded-lg overflow-hidden flex items-center justify-center border border-gray-300">
                                    <img id="logo-preview" src="https://placehold.co/96x96/cccccc/333333?text=Logo" alt="Previsualización del logo" class="w-full h-full object-contain">
                                </div>
                                <label class="block">
                                    <span class="sr-only">Elegir archivo de logotipo</span>
                                    <input type="file" id="logo-upload" accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 cursor-pointer"/>
                                </label>
                                <input type="hidden" id="logo-url-hidden"> </div>
                        </div>

                        <div class="border-b border-gray-200 pb-6">
                            <h4 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2 uppercase">
                                <i data-lucide="building-2" class="w-5 h-5 text-[var(--color-secondary)]"></i> Información de la Empresa y Contacto
                            </h4>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="company-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre del Negocio</label>
                                    <input type="text" id="company-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Mi Empresa Digital" required>
                                </div>
                                <div>
                                    <label for="contact-person-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre del Contacto Principal</label>
                                    <input type="text" id="contact-person-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Juan Pérez">
                                </div>
                                <div>
                                    <label for="email-contact" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Correo Electrónico</label>
                                    <input type="email" id="email-contact" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="correo@tuempresa.com" required>
                                </div>
                                <div>
                                    <label for="website-url" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Dirección de tu Página Web</label>
                                    <input type="url" id="website-url" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="https://tupaginaweb.com">
                                </div>
                                
                                <div>
                                    <label for="phone-primary" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Teléfono Principal</label>
                                    <input type="tel" id="phone-primary" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. +1 (123) 456-7890" required>
                                </div>
                                <div>
                                    <label for="phone-secondary" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Teléfono Secundario (Opcional)</label>
                                    <input type="tel" id="phone-secondary" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. +1 (987) 654-3210">
                                </div>
                            </div>
                        </div>

                        <div class="border-b border-gray-200 pb-6">
                            <h4 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2 uppercase">
                                <i data-lucide="map-pin" class="w-5 h-5 text-[var(--color-secondary)]"></i> Ciudades en las que Operas
                            </h4>
                            <div id="cities-container" class="space-y-3"></div>
                            <button type="button" id="add-city-button" class="btn-primary mt-4 py-2 px-4 rounded-lg flex items-center justify-center uppercase text-sm">
                                <i data-lucide="plus" class="w-5 h-5 mr-2"></i> Añadir Ciudad
                            </button>
                        </div>

                        <div class="border-b border-gray-200 pb-6">
                            <h4 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2 uppercase">
                                <i data-lucide="calendar-clock" class="w-5 h-5 text-[var(--color-secondary)]"></i> Configuración de Agenda
                            </h4>
                            <div class="flex items-center justify-between bg-slate-50 p-4 rounded-lg border">
                                <label for="enable-booking" class="font-bold text-gray-700 text-base">Activar agenda en la página web</label>
                                <div class="relative inline-block w-10 mr-2 align-middle select-none">
                                    <input type="checkbox" name="enable-booking" id="enable-booking" class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer"/>
                                    <label for="enable-booking" class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer"></label>
                                </div>
                            </div>
                            
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
                                <div>
                                    <label for="slot-duration" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Duración de Cita (min)</label>
                                    <select id="slot-duration" class="w-full p-3 border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                        <option value="30">30 minutos</option>
                                        <option value="45">45 minutos</option>
                                        <option value="60" selected>60 minutos</option>
                                        <option value="90">90 minutos</option>
                                        <option value="120">120 minutos</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="buffer-time" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Descanso entre Citas (min)</label>
                                    <select id="buffer-time" class="w-full p-3 border border-gray-300 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                        <option value="0">Sin descanso</option>
                                        <option value="15" selected>15 minutos</option>
                                        <option value="30">30 minutos</option>
                                        <option value="45">45 minutos</option>
                                        <option value="60">60 minutos</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="available-spots" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Espacios por Horario</label>
                                    <input type="number" id="available-spots" value="1" min="1" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                </div>
                            </div>
                            <p class="text-xs text-gray-500 mt-2">El descanso es el tiempo de preparación que se bloqueará después de cada cita.</p>

                            <div class="mt-6">
                                    <h4 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2 uppercase">
                                    <i data-lucide="calendar-days" class="w-5 h-5 text-[var(--color-secondary)]"></i> Horario Semanal
                                </h4>
                                
                                <div class="space-y-2" id="weekly-schedule-container"></div>
                            </div>
                            
                            <div class="mt-6">
                                <h5 class="text-lg font-bold text-gray-800 mb-3 uppercase">Bloquear Fechas Específicas</h5>
                                <div class="flex items-center gap-2">
                                    <input type="date" id="block-date-picker" class="p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                    <button type="button" id="add-blocked-date" class="btn-primary py-3 px-4 rounded-lg text-sm">Añadir</button>
                                </div>
                                <div id="blocked-dates-list" class="mt-3 flex flex-wrap gap-2"></div>
                            </div>
                        </div>
                        <div>
                            <h4 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2 uppercase">
                                <i data-lucide="image-plus" class="w-5 h-5 text-[var(--color-secondary)]"></i> Galería de Imágenes (Máx. 10)
                            </h4>
                            <label class="block mb-4">
                                <span class="sr-only">Elegir archivo de logotipo</span>
                                <input type="file" id="gallery-upload" multiple accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 cursor-pointer"/>
                            </label>
                            <div id="gallery-preview-container" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4"></div>
                            <p class="text-sm text-gray-500 mt-2">Sube hasta 10 imágenes. Se recomienda un tamaño uniforme.</p>
                        </div>
                        
                        <div class="text-right pt-6">
                            <button type="submit" class="btn-secondary font-bold py-3 px-8 rounded-lg uppercase flex items-center justify-end ml-auto">
                                ACTUALIZAR PÁGINA WEB <i data-lucide="arrow-right" class="w-5 h-5 ml-2"></i>
                            </button>
                        </div>
                    </form>
                </div>
            </section>
        </div>
    </main>
</div>

<script>
    // Variable global para almacenar la configuración del sitio web después de cargarla
    let currentWebsiteConfig = null;

    document.addEventListener('DOMContentLoaded', function() {
        // Inicialización del Toast desde URL parámetros (solo aquí, no en header-manager.js)
        const urlParams = new URLSearchParams(window.location.search);
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');

        if (notificationType && notificationMessage) {
            if (typeof showToast === 'function') {
                showToast(notificationMessage, notificationType);
            } else {
                console.error("showToast function is not defined. Toast notification might not display.");
            }
        }

        // Show PHP errors as toast if they exist
        <?php if (isset($db_error_message) && $db_error_message): ?>
            showToast('<?php echo addslashes($db_error_message); ?>', 'error');
        <?php endif; ?>

        // --- ELEMENTOS DEL DOM ---
        const websiteConfigForm = document.getElementById('website-config-form');

        const companyNameInput = document.getElementById('company-name');
        const contactPersonNameInput = document.getElementById('contact-person-name');
        const websiteUrlInput = document.getElementById('website-url');
        const phonePrimaryInput = document.getElementById('phone-primary');
        const phoneSecondaryInput = document.getElementById('phone-secondary');
        const emailContactInput = document.getElementById('email-contact');

        const logoUpload = document.getElementById('logo-upload');
        const logoPreview = document.getElementById('logo-preview');
        const logoUrlHidden = document.getElementById('logo-url-hidden');
        
        const citiesContainer = document.getElementById('cities-container');
        const addCityButton = document.getElementById('add-city-button');
        const galleryUpload = document.getElementById('gallery-upload');
        const galleryPreviewContainer = document.getElementById('gallery-preview-container');
        const weeklyScheduleContainer = document.getElementById('weekly-schedule-container');
        const enableBookingCheckbox = document.getElementById('enable-booking');
        const slotDurationSelect = document.getElementById('slot-duration');
        const bufferTimeSelect = document.getElementById('buffer-time');
        const availableSpotsInput = document.getElementById('available-spots');

        const blockDatePicker = document.getElementById('block-date-picker');
        const addBlockedDateBtn = document.getElementById('add-blocked-date');
        const blockedDatesList = document.getElementById('blocked-dates-list');

        // Referencias para el resumen del negocio en el header de la SECCIÓN
        const businessSummarySectionHeader = document.getElementById('business-summary-section-header'); // Renombrado
        const summaryLogo = document.getElementById('summary-logo');
        const summaryCompanyName = document.getElementById('summary-company-name');
        const summaryContactName = document.getElementById('summary-contact-name');
        const summaryPhone = document.getElementById('summary-phone');
        const summaryEmail = document.getElementById('summary-email');
        const summaryWebsite = document.getElementById('summary-website');
        
        let uploadedImages = [];
        let currentLogoUrl = '';
        let blockedDates = new Set();
        let currentCities = [];
        let currentSchedule = [];

        function formatPhoneNumber(value) {
            if (!value) return '';
            const cleaned = ('' + value).replace(/\D/g, '');
            const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
            if (match) {
                return `(${match[1]}) ${match[2]}-${match[3]}`;
            }
            return cleaned;
        }

        function applyInputPhoneFormat(inputElement) {
            if (!inputElement) return;
            inputElement.value = formatPhoneNumber(inputElement.value);
            inputElement.addEventListener('input', (e) => {
                let value = e.target.value.replace(/\D/g, '');
                e.target.value = formatPhoneNumber(value);
            });
            inputElement.addEventListener('blur', (e) => {
                e.target.value = formatPhoneNumber(e.target.value);
            });
        }

        applyInputPhoneFormat(phonePrimaryInput);
        applyInputPhoneFormat(phoneSecondaryInput);

        if (logoUpload) {
            logoUpload.addEventListener('change', async function(event) {
                const file = event.target.files[0];
                if (!file) return;

                // Mostrar vista previa temporal de la imagen seleccionada localmente
                logoPreview.src = URL.createObjectURL(file);

                const formData = new FormData();
                formData.append('logo_file', file); // 'logo_file' es el nombre del campo que espera upload-logo.php

                try {
                    // Envía el archivo al nuevo script de subida de logo
                    const response = await fetch('db/upload-logo.php', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();

                    if (result.success) {
                        const uploadedLogoUrl = result.file_url; // Guarda la URL real devuelta por el servidor
                        logoUrlHidden.value = uploadedLogoUrl; // Actualiza el campo oculto
                        currentLogoUrl = uploadedLogoUrl; // Actualiza la variable de control
                        showToast('Logo subido al servidor. Haz clic en "ACTUALIZAR PÁGINA WEB" para guardar los cambios.', 'info');
                        updateSectionHeaderSummary(); // Actualizar el resumen del header de la sección con la nueva URL
                    } else {
                        showToast('Error al subir el logo: ' + (result.message || 'Error desconocido.'), 'error');
                        // Revertir a la URL del logo actual si la subida falla
                        logoPreview.src = currentWebsiteConfig?.logo_url || "https://placehold.co/96x96/999999/ffffff?text=Logo"; // Usar un placeholder distinto si no hay logo previo
                        logoUrlHidden.value = currentWebsiteConfig?.logo_url || "";
                        currentLogoUrl = currentWebsiteConfig?.logo_url || "";
                    }
                } catch (error) {
                    console.error('Error de conexión al subir el logo:', error);
                    showToast('Error de conexión al subir el logo.', 'error');
                    // Revertir a la URL del logo actual si hay error de conexión
                    logoPreview.src = currentWebsiteConfig?.logo_url || "https://placehold.co/96x96/999999/ffffff?text=Logo";
                    logoUrlHidden.value = currentWebsiteConfig?.logo_url || "";
                    currentLogoUrl = currentWebsiteConfig?.logo_url || "";
                }
            });
        }
        
        const addCityField = (cityName = '') => {
            const newField = document.createElement('div');
            newField.className = 'flex items-center space-x-2';
            newField.innerHTML = `
                <input type="text" class="flex-grow p-3 border border-gray-300 rounded-lg city-input" placeholder="Nombre de la ciudad" value="${cityName}">
                <button type="button" class="text-red-500 hover:text-red-700 p-2 remove-city-btn"><i data-lucide="x-circle"></i></button>`;
            citiesContainer.appendChild(newField);
            lucide.createIcons();
            newField.querySelector('.remove-city-btn').onclick = (e) => e.target.closest('.flex').remove();
        };

        if (addCityButton) {
            addCityButton.addEventListener('click', () => addCityField());
        }
        
        const renderGalleryPreviews = () => {
            galleryPreviewContainer.innerHTML = '';
            uploadedImages.forEach((imgObj, index) => {
                const wrapper = document.createElement('div');
                wrapper.className = 'relative w-full h-32 bg-gray-100 rounded-lg border';
                wrapper.innerHTML = `
                    <img src="${imgObj.url}" class="w-full h-full object-cover">
                    <button type="button" data-index="${index}" class="absolute top-1 right-1 bg-red-600 text-white rounded-full p-0.5 remove-gallery-img"><i data-lucide="x" class="w-4 h-4"></i></button>`;
                galleryPreviewContainer.appendChild(wrapper);
            });
            lucide.createIcons();
            document.querySelectorAll('.remove-gallery-img').forEach(button => {
                button.onclick = (e) => removeGalleryImage(parseInt(e.target.dataset.index || e.target.closest('button').dataset.index));
            });
        };

        if (galleryUpload) {
            galleryUpload.addEventListener('change', function(event) {
                const files = Array.from(event.target.files);
                if (files.length + uploadedImages.length > 10) {
                    showToast('Solo puedes subir un máximo de 10 imágenes en total.', 'warning');
                    event.target.value = '';
                    return;
                }
                
                files.forEach(file => {
                    if (!file.type.startsWith('image/')) return;
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        uploadedImages.push({ name: file.name, url: e.target.result });
                        renderGalleryPreviews();
                    }
                    reader.readAsDataURL(file);
                });
            });
        }
        
        const removeGalleryImage = (index) => {
            uploadedImages.splice(index, 1);
            renderGalleryPreviews();
        };

        function renderWeeklySchedule() {
            const days = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo'];
            weeklyScheduleContainer.innerHTML = '';
            if (currentSchedule.length === 0) {
                days.forEach((day, index) => {
                    currentSchedule.push({
                        day: day,
                        active: index < 5,
                        start: '09:00',
                        end: '17:00'
                    });
                });
            }

            currentSchedule.forEach((dayData, index) => {
                const dayId = `day-${index}`;
                const dayElement = document.createElement('div');
                dayElement.className = 'grid grid-cols-[auto_1fr] md:grid-cols-[auto_120px_1fr_1fr] gap-4 items-center p-3 rounded-lg border bg-white';
                dayElement.innerHTML = `
                    <input type="checkbox" id="${dayId}-active" class="h-5 w-5 accent-[var(--color-primary)]" ${dayData.active ? 'checked' : ''}>
                    <label for="${dayId}-active" class="font-bold uppercase text-sm cursor-pointer">${dayData.day}</label>
                    <div class="flex items-center gap-2">
                        <label for="${dayId}-start" class="text-sm">De:</label>
                        <input type="time" id="${dayId}-start" value="${dayData.start}" step="1800" class="w-full p-2 border border-gray-300 rounded-lg text-sm">
                    </div>
                    <div class="flex items-center gap-2">
                        <label for="${dayId}-end" class="text-sm">A:</label>
                        <input type="time" id="${dayId}-end" value="${dayData.end}" step="1800" class="w-full p-2 border border-gray-300 rounded-lg text-sm">
                    </div>
                `;
                weeklyScheduleContainer.appendChild(dayElement);

                dayElement.querySelector(`#${dayId}-active`).addEventListener('change', (e) => currentSchedule[index].active = e.target.checked);
                dayElement.querySelector(`#${dayId}-start`).addEventListener('change', (e) => currentSchedule[index].start = e.target.value);
                dayElement.querySelector(`#${dayId}-end`).addEventListener('change', (e) => currentSchedule[index].end = e.target.value);
            });
        }
        
        function renderBlockedDates() {
            blockedDatesList.innerHTML = '';
            const sortedDates = Array.from(blockedDates).sort();
            sortedDates.forEach(date => {
                const dateElement = document.createElement('div');
                dateElement.className = 'flex items-center gap-2 bg-gray-200 text-gray-700 text-sm font-medium px-3 py-1 rounded-full';
                const formattedDate = new Date(date + 'T00:00:00').toLocaleDateString('es-ES', { year: 'numeric', month: 'long', day: 'numeric' });
                dateElement.innerHTML = `
                    <span>${formattedDate}</span>
                    <button type="button" class="text-red-500 hover:text-red-700 remove-blocked-date-btn" data-date="${date}"><i data-lucide="x-circle" class="w-4 h-4"></i></button>
                `;
                blockedDatesList.appendChild(dateElement);
            });
            lucide.createIcons();
            document.querySelectorAll('.remove-blocked-date-btn').forEach(button => {
                button.onclick = (e) => removeBlockedDate(e.target.dataset.date || e.target.closest('button').dataset.date);
            });
        }

        if (addBlockedDateBtn) {
            addBlockedDateBtn.addEventListener('click', () => {
                const dateValue = blockDatePicker.value;
                if (dateValue && !blockedDates.has(dateValue)) {
                    blockedDates.add(dateValue);
                    renderBlockedDates();
                    blockDatePicker.value = '';
                } else if (dateValue) {
                    showToast('Esa fecha ya está bloqueada.', 'warning');
                }
            });
        }
        
        const removeBlockedDate = (date) => {
            blockedDates.delete(date);
            renderBlockedDates();
        };

        const loadWebsiteConfig = async () => {
            try {
                const response = await fetch('db/website-config-read.php');
                const result = await response.json();

                if (result.success && result.data) {
                    currentWebsiteConfig = result.data;
                    companyNameInput.value = currentWebsiteConfig.company_name || '';
                    contactPersonNameInput.value = currentWebsiteConfig.contact_name || '';
                    phonePrimaryInput.value = formatPhoneNumber(currentWebsiteConfig.phone_primary || '');
                    phoneSecondaryInput.value = formatPhoneNumber(currentWebsiteConfig.phone_secondary || '');
                    emailContactInput.value = currentWebsiteConfig.email || '';
                    websiteUrlInput.value = currentWebsiteConfig.website_url || '';
                    
                    if (currentWebsiteConfig.logo_url) {
                        logoPreview.src = currentWebsiteConfig.logo_url;
                        logoUrlHidden.value = currentWebsiteConfig.logo_url;
                        currentLogoUrl = currentWebsiteConfig.logo_url;
                    } else {
                        logoPreview.src = "https://placehold.co/96x96/cccccc/333333?text=Logo";
                        logoUrlHidden.value = "";
                        currentLogoUrl = "";
                    }

                    currentCities = currentWebsiteConfig.cities_operated || [];
                    citiesContainer.innerHTML = '';
                    currentCities.forEach(city => addCityField(city));
                    if (currentCities.length === 0) addCityField();

                    uploadedImages = (currentWebsiteConfig.gallery_images || []).map(url => ({ name: url.substring(url.lastIndexOf('/') + 1), url: url }));
                    renderGalleryPreviews();

                    enableBookingCheckbox.checked = currentWebsiteConfig.enable_booking;
                    slotDurationSelect.value = currentWebsiteConfig.slot_duration;
                    bufferTimeSelect.value = currentWebsiteConfig.buffer_time;
                    availableSpotsInput.value = currentWebsiteConfig.available_spots;
                    currentSchedule = currentWebsiteConfig.weekly_schedule || [];
                    renderWeeklySchedule();

                    blockedDates = new Set(currentWebsiteConfig.blocked_dates || []);
                    renderBlockedDates();

                    updateSectionHeaderSummary();

                } else {
                    showToast('No se pudo cargar la configuración de la web. Se iniciará con valores por defecto.', 'error');
                    // alert('No se pudo cargar la configuración de la web. Se iniciará con valores por defecto.'); // Replaced
                    addCityField();
                    renderWeeklySchedule();
                }
                applyInputPhoneFormat(phonePrimaryInput);
                applyInputPhoneFormat(phoneSecondaryInput);
            } catch (error) {
                console.error('Error de conexión al cargar la configuración de la web:', error);
                showToast('Error de conexión al cargar la configuración de la web.', 'error');
                // alert('Error de conexión al cargar la configuración de la web.'); // Replaced
                addCityField();
                renderWeeklySchedule();
            }
        };

        const updateSectionHeaderSummary = () => {
            if (currentWebsiteConfig) {
                summaryLogo.src = currentWebsiteConfig.logo_url || "https://placehold.co/48x48/cccccc/333333?text=Logo";
                summaryCompanyName.textContent = currentWebsiteConfig.company_name || '';
                summaryCompanyName.style.fontWeight = '900'; // Set bold 900
                summaryCompanyName.style.fontSize = '1.25rem'; // Larger size
                summaryContactName.textContent = currentWebsiteConfig.contact_name || '';
                summaryPhone.textContent = formatPhoneNumber(currentWebsiteConfig.phone_primary || '');
                summaryEmail.textContent = currentWebsiteConfig.email || '';
                summaryWebsite.textContent = currentWebsiteConfig.website_url ? currentWebsiteConfig.website_url.replace(/^(https?:\/\/)?(www\.)?/,'').split('/')[0] : '';
                businessSummarySectionHeader.classList.remove('hidden');
            } else {
                businessSummarySectionHeader.classList.add('hidden');
            }
        };

        websiteConfigForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            const cities = Array.from(citiesContainer.querySelectorAll('.city-input'))
                                .map(input => input.value.trim())
                                .filter(value => value !== '');

            const galleryUrlsToSend = uploadedImages.map(img => img.url);


            const configData = {
                company_name: companyNameInput.value.trim(),
                contact_name: contactPersonNameInput.value.trim(),
                phone_primary: phonePrimaryInput.value.replace(/\D/g, ''),
                phone_secondary: phoneSecondaryInput.value.replace(/\D/g, ''),
                email: emailContactInput.value.trim(),
                website_url: websiteUrlInput.value.trim(),
                logo_url: logoUrlHidden.value,
                gallery_images: galleryUrlsToSend,
                cities_operated: cities,
                weekly_schedule: currentSchedule,
                enable_booking: enableBookingCheckbox.checked,
                slot_duration: parseInt(slotDurationSelect.value),
                buffer_time: parseInt(bufferTimeSelect.value),
                available_spots: parseInt(availableSpotsInput.value),
                blocked_dates: Array.from(blockedDates)
            };

            try {
                const response = await fetch('db/website-config-update.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(configData)
                });
                const result = await response.json();

                if (result.success) {
                    showToast('Configuración de la web actualizada con éxito.', 'success');
                    // alert('Configuración de la web actualizada con éxito.'); // Replaced
                    loadWebsiteConfig(); 
                } else {
                    showToast(`Error al actualizar configuración: ${result.message}`, 'error');
                    // alert(`Error al actualizar configuración: ${result.message}`); // Replaced
                }
            } catch (error) {
                console.error('Error de conexión al actualizar la configuración de la web:', error);
                showToast('Error de conexión al actualizar la configuración de la web.', 'error');
                // alert('Error de conexión al actualizar la configuración de la web.'); // Replaced
            }
        });


        // --- INICIALIZACIÓN ---
        loadWebsiteConfig();
        lucide.createIcons();
    });
</script>
</body>
</html>