<?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>Información Empresarial 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>
    <script src="https://unpkg.com/imask"></script>
    
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
    <style>
        /* Estilos para el interruptor (toggle) usando variables de color de la marca */
        .toggle-label { 
            background-color: var(--color-secondary); /* Rojo/Maroon para desactivado */
            transition: background-color .2s ease-in-out;
        }
        .toggle-checkbox:checked + .toggle-label { 
            background-color: var(--color-success); /* Verde para activado */
        }
        .toggle-circle { 
             transition: transform .2s ease-in-out;
        }
        .toggle-checkbox:checked + .toggle-label .toggle-circle { 
            transform: translateX(100%); 
        }

        /* Estilos para las notificaciones toast */
        #toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }
        .toast {
            background-color: #333;
            color: #fff;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            margin-bottom: 10px;
            opacity: 0;
            transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;
            transform: translateY(20px);
        }
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
        .toast.success { background-color: var(--color-success); }
        .toast.error { background-color: var(--color-danger); }
    </style>
</head>
<body data-page-title="Configuración General De Tu Negocio"
      data-page-subtitle="Gestiona el logo, datos de contacto, redes y códigos de seguimiento"
      data-page-icon="settings">

    <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">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                
                <div class="lg:col-span-1 space-y-8">
                    <form id="business-info-form" class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="info" class="w-6 h-6 text-[var(--color-primary)]"></i> INFORMACIÓN DE LA EMPRESA</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div><label for="business-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre del Negocio</label><input type="text" id="business-name" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                            <div><label for="contact-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre del Contacto</label><input type="text" id="contact-name" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                            <div><label for="business-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Correo Electrónico</label><input type="email" id="business-email" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                            <div><label for="business-website" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Página Web</label><input type="url" id="business-website" class="w-full p-3 border border-gray-300 rounded-lg"></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"></div>
                            <div><label for="phone-secondary" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Teléfono Secundario</label><input type="tel" id="phone-secondary" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                            <div><label for="business-whatsapp" class="block text-gray-700 text-sm font-bold mb-2 uppercase">WhatsApp</label><input type="tel" id="business-whatsapp" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                            <div><label for="license-number" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Número de Licencia</label><input type="text" id="license-number" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                        </div>
                        <div class="border-t border-gray-200 mt-6 pt-4 flex justify-end">
                            <button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase flex items-center justify-center gap-2">
                                <i data-lucide="save" class="w-5 h-5"></i>
                                <span>Guardar Cambios</span>
                            </button>
                        </div>
                    </form>

                    <div class="bg-white p-6 rounded-xl shadow-md text-center">
                        <h3 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center justify-center gap-2">
                            <i data-lucide="qr-code" class="w-6 h-6 text-[var(--color-primary)]"></i> CÓDIGO QR PROMOCIONAL
                        </h3>
                        <div id="qrcode-container" class="flex justify-center my-4">
                            <div id="qrcode-canvas" class="p-2 bg-white border rounded-lg inline-block"></div>
                        </div>
                        <p class="text-sm text-gray-600 mb-4">
                            Este código QR enlaza a tu página web. Descárgalo y úsalo en tarjetas de presentación, volantes o material promocional.
                        </p>
                        <a id="download-qr-btn" href="#" download="codigo-qr.png" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase inline-flex items-center justify-center gap-2 transition-opacity opacity-50 pointer-events-none">
                            <i data-lucide="download" class="w-5 h-5"></i>
                            <span>Descargar QR</span>
                        </a>
                    </div>
                    <form id="social-links-form" class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="share-2" class="w-6 h-6 text-[var(--color-primary)]"></i> REDES SOCIALES Y PLATAFORMAS</h3>
                        <div id="social-repeater" class="space-y-4"></div>
                        <button type="button" id="add-social-btn" class="mt-4 btn-secondary font-bold py-2 px-4 rounded-lg flex items-center justify-center gap-2 uppercase text-sm"><i data-lucide="plus" class="w-4 h-4"></i> Añadir Enlace</button>
                        <div class="border-t border-gray-200 mt-6 pt-4 flex justify-end">
                            <button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase flex items-center justify-center gap-2">
                                <i data-lucide="save" class="w-5 h-5"></i>
                                <span>Guardar Enlaces</span>
                            </button>
                        </div>
                    </form>
                    
                    <form id="tracking-codes-form" class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2"><i data-lucide="code-2" class="w-6 h-6 text-[var(--color-primary)]"></i> CÓDIGOS DE SEGUIMIENTO</h3>
                        <div class="space-y-4">
                            <div><label for="gtm-head" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Google Tag Manager (Head)</label><textarea id="gtm-head" rows="6" class="w-full p-3 border border-gray-300 rounded-lg font-mono text-xs" placeholder="Pega aquí el código <script>..."></textarea></div>
                            <div><label for="gtm-body" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Google Tag Manager (Body)</label><textarea id="gtm-body" rows="6" class="w-full p-3 border border-gray-300 rounded-lg font-mono text-xs" placeholder="Pega aquí el código <noscript>..."></textarea></div>
                        </div>
                        <div class="border-t border-gray-200 mt-6 pt-4 flex justify-end">
                            <button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase flex items-center justify-center gap-2">
                                <i data-lucide="save" class="w-5 h-5"></i>
                                <span>Guardar Códigos</span>
                            </button>
                        </div>
                    </form>
                </div>

                <div class="lg:col-span-1 space-y-8">
                    <form id="logo-form" class="bg-white p-6 rounded-xl shadow-md">
                        <h3 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> LOGOTIPO DE LA EMPRESA</h3>
                        <div class="flex items-center gap-4">
                            <label for="logo-upload" class="cursor-pointer bg-gray-600 text-white font-bold py-2 px-4 rounded-lg inline-flex items-center gap-2 hover:bg-gray-700 transition">
                                <i data-lucide="upload" class="w-4 h-4"></i>
                                <span>Seleccionar</span>
                            </label>
                            <input type="file" id="logo-upload" class="hidden" accept="image/*" name="logo_upload">
                            <span id="logo-file-name" class="text-sm text-gray-500">Archivo NO Seleccionado</span>
                        </div>
                        <div class="border-t border-gray-200 mt-6 pt-4 flex justify-end">
                            <button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase flex items-center justify-center gap-2">
                                <i data-lucide="save" class="w-5 h-5"></i>
                                <span>Guardar Logotipo</span>
                            </button>
                        </div>
                    </form>

<form id="branding-colors-form" class="bg-white p-6 rounded-xl shadow-md">
    <h3 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2">
        <i data-lucide="palette" class="w-6 h-6 text-[var(--color-primary)]"></i> COLORES DE MARCA
    </h3>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div>
            <label for="branding-color-primary" class="block text-gray-700 text-sm font-bold mb-2 uppercase">COLOR PRIMARIO</label>
            <div class="flex items-center gap-2 p-2 border border-gray-300 rounded-lg">
                <input type="color" id="branding-color-primary" value="#1E3A8A" class="w-10 h-10 p-0 border-none cursor-pointer">
                <input type="text" id="branding-color-text-primary" class="w-full font-mono text-center border-l border-gray-200 pl-2">
            </div>
        </div>
        <div>
            <label for="branding-color-secondary" class="block text-gray-700 text-sm font-bold mb-2 uppercase">COLOR SECUNDARIO</label>
            <div class="flex items-center gap-2 p-2 border border-gray-300 rounded-lg">
                <input type="color" id="branding-color-secondary" value="#991B1B" class="w-10 h-10 p-0 border-none cursor-pointer">
                <input type="text" id="branding-color-text-secondary" class="w-full font-mono text-center border-l border-gray-200 pl-2">
            </div>
        </div>
        <div>
            <label for="branding-color-accent" class="block text-gray-700 text-sm font-bold mb-2 uppercase">COLOR DE ACENTO</label>
            <div class="flex items-center gap-2 p-2 border border-gray-300 rounded-lg">
                <input type="color" id="branding-color-accent" value="#F59E0B" class="w-10 h-10 p-0 border-none cursor-pointer">
                <input type="text" id="branding-color-text-accent" class="w-full font-mono text-center border-l border-gray-200 pl-2">
            </div>
        </div>
    </div>
    <div class="border-t border-gray-200 mt-6 pt-4 flex justify-end">
        <button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase flex items-center justify-center gap-2">
            <i data-lucide="save" class="w-5 h-5"></i>
            <span>Guardar Colores</span>
        </button>
    </div>
</form>

                    <div>
                        <div class="bg-[var(--color-primary)] text-white p-6 rounded-xl shadow-lg space-y-4">
                            <div class="flex flex-col items-center text-center">
                                <img id="preview-logo" src="https://i.imgur.com/83D4Z58.png" class="h-24 w-auto mb-3 bg-white p-1 rounded-md border" alt="Vista previa del logo">
                                <h4 id="preview-business-name" class="text-xl font-bold text-white">FlowClean Cleaning Services LLC</h4>
                                <p id="preview-contact-name" class="text-sm text-white/70">Nestor Orozco</p>
                            </div>
                            
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-y-3 gap-x-6 text-sm">
                                <div class="flex items-center gap-3">
                                    <i data-lucide="phone" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                                    <span id="preview-phone1" class="font-semibold text-white/90">(425) 243-4577</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i data-lucide="smartphone" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                                    <span id="preview-phone2" class="font-semibold text-white/90">(425) 777-2109</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i data-lucide="mail" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                                    <span id="preview-email" class="truncate font-semibold text-white/90">info@flowclean.com</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i data-lucide="message-circle" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                                    <span id="preview-whatsapp" class="font-semibold text-white/90">(425) 123-4567</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i data-lucide="globe" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                                    <span id="preview-website" class="truncate font-semibold text-white/90">https://flowclean.com</span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <i data-lucide="credit-card" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                                    <span id="preview-license-number" class="truncate font-semibold text-white/90"></span>
                                </div>
                            </div>
                            
                            <div id="preview-social-links" class="flex items-center justify-center gap-4 border-t border-white/20 pt-4"></div>
                        </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 De Introducción A La Plataforma SiteFlowCMS
                                    </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>

                        <form id="sections-form" class="bg-white p-6 rounded-xl shadow-md">
                            <h3 class="text-xl font-extrabold text-gray-700 mb-4 flex items-center gap-2">
                                <i data-lucide="layout-list" class="w-6 h-6 text-[var(--color-primary)]"></i> GESTIÓN DE SECCIONES
                            </h3>
                            <div class="space-y-4">
                            </div>
                            <div class="border-t border-gray-200 mt-6 pt-4 flex justify-end">
                                <button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase flex items-center justify-center gap-2">
                                    <i data-lucide="save" class="w-5 h-5"></i>
                                    <span>Guardar Preferencias</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', () => {
    // --- NOTIFICACIONES TOAST ---
    const showToast = (message, type = 'success') => {
        const toastContainer = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.textContent = message;
        toastContainer.appendChild(toast);
        setTimeout(() => { toast.classList.add('show'); }, 100);
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => { toast.remove(); }, 300);
        }, 3000);
    };

    // --- 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'); });
    }
    
    // --- LÓGICA DEL LOGO Y TELÉFONOS ---
    const logoUpload = document.getElementById('logo-upload');
    const logoFileName = document.getElementById('logo-file-name');
    const previewLogo = document.getElementById('preview-logo');
    logoUpload.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if(file) {
            logoFileName.textContent = file.name;
        }
    });

    const masks = {
        phone1: IMask(document.getElementById('phone-primary'), { mask: '(000) 000-0000' }),
        phone2: IMask(document.getElementById('phone-secondary'), { mask: '(000) 000-0000' }),
        whatsapp: IMask(document.getElementById('business-whatsapp'), { mask: '(000) 000-0000' }),
        colorPrimary: null,
        colorSecondary: null,
        colorAccent: null
    };

    const setupColorPicker = (pickerId, textId, maskKey) => {
        const colorPicker = document.getElementById(pickerId);
        const colorText = document.getElementById(textId);
        const maskOptions = { mask: '#HHHHHH', definitions: { 'H': /[0-9a-fA-F]/, casing: 'upper' } };
        masks[maskKey] = IMask(colorText, maskOptions);
        colorPicker.addEventListener('input', (e) => { masks[maskKey].value = e.target.value.toUpperCase(); });
        colorText.addEventListener('input', (e) => {
            if (/^#[0-9A-F]{6}$/i.test(e.target.value)) { colorPicker.value = e.target.value; }
        });
    };
    setupColorPicker('branding-color-primary', 'branding-color-text-primary', 'colorPrimary');
    setupColorPicker('branding-color-secondary', 'branding-color-text-secondary', 'colorSecondary');
    setupColorPicker('branding-color-accent', 'branding-color-text-accent', 'colorAccent');

    // --- REPEATER DE ENLACES SOCIALES ---
    const socialRepeater = document.getElementById('social-repeater');
    const addSocialBtn = document.getElementById('add-social-btn');
    const previewSocialLinks = document.getElementById('preview-social-links');
    let socialCounter = 0;
    
    const createSocialItemHTML = (id, icon = 'facebook', url = '') => `
        <div class="social-item border border-gray-200 p-4 rounded-lg bg-gray-50" data-id="${id}">
            <div class="flex justify-between items-center mb-2"><label class="text-gray-700 text-sm font-bold uppercase">Enlace #${id}</label><button type="button" class="remove-item-btn text-red-500 hover:text-red-700"><i data-lucide="trash-2" class="w-4 h-4"></i></button></div>
            <div class="flex items-center gap-2"><select class="w-1/3 p-2 border border-gray-300 rounded-md social-icon bg-white"><option value="facebook" ${icon=='facebook'?'selected':''}>Facebook</option><option value="instagram" ${icon=='instagram'?'selected':''}>Instagram</option><option value="youtube" ${icon=='youtube'?'selected':''}>YouTube</option><option value="tiktok" ${icon=='tiktok'?'selected':''}>TikTok</option><option value="linkedin" ${icon=='linkedin'?'selected':''}>LinkedIn</option><option value="twitter" ${icon=='twitter'?'selected':''}>X (Twitter)</option><option value="link" ${icon=='link'?'selected':''}>Otro (Enlace)</option></select><input type="url" class="social-url w-2/3 p-2 border border-gray-300 rounded-md" placeholder="URL Completa (https://...)" value="${url}"></div>
        </div>`;

    const renderSocialPreview = () => {
        previewSocialLinks.innerHTML = '';
        socialRepeater.querySelectorAll('.social-item').forEach(item => {
            const icon = item.querySelector('.social-icon').value;
            const url = item.querySelector('.social-url').value;
            if (url) {
                previewSocialLinks.innerHTML += `<a href="${url}" target="_blank" class="text-white/80 hover:text-[var(--color-highlight)]"><i data-lucide="${icon}"></i></a>`;
            }
        });
        lucide.createIcons();
    };

    addSocialBtn.addEventListener('click', () => { socialCounter++; socialRepeater.insertAdjacentHTML('beforeend', createSocialItemHTML(socialCounter)); lucide.createIcons(); renderSocialPreview(); });
    socialRepeater.addEventListener('click', e => { if (e.target.closest('.remove-item-btn')) { e.target.closest('.social-item').remove(); renderSocialPreview(); } });
    socialRepeater.addEventListener('input', renderSocialPreview);
    socialRepeater.addEventListener('change', renderSocialPreview);
    
    // --- BINDING DE INFORMACIÓN DEL NEGOCIO ---
    const bindings = {'business-name': document.getElementById('preview-business-name'),'contact-name': document.getElementById('preview-contact-name'),'phone-primary': document.getElementById('preview-phone1'),'phone-secondary': document.getElementById('preview-phone2'),'business-whatsapp': document.getElementById('preview-whatsapp'),'business-email': document.getElementById('preview-email'),'business-website': document.getElementById('preview-website'), 'license-number': document.getElementById('preview-license-number')};
    const updatePreview = (input) => { if (bindings[input.id]) { bindings[input.id].textContent = input.value; } };
    document.getElementById('business-info-form').addEventListener('input', e => updatePreview(e.target));
    
    // --- LÓGICA DE INTERRUPTORES (TOGGLES) ---
    const sectionsForm = document.getElementById('sections-form');
    const sectionsContainer = sectionsForm.querySelector('.space-y-4');
    const sections = [{ id: 'differentiators', label: 'FACTOR DIFERENCIADOR', warning: true },{ id: 'process', label: 'EL PROCESO DE TRABAJO' },{ id: 'coverage', label: 'ÁREAS DE COBERTURA' },{ id: 'gallery', label: 'GALERÍA DE PROYECTOS', subtext: 'Si NO Aplica Al Negocio.' },{ id: 'reviews', label: 'PRUEBA DE RESULTADOS', warning: true },{ id: 'cta', label: 'CTA PERSUASIVO' },{ id: 'hours', label: 'HORARIOS DE ATENCIÓN', warning: true },{ id: 'exit-intent', label: 'POP-UP DE "EXIT INTENT"', checked: false }];
    const icons = { differentiators: 'gem', process: 'list-ordered', coverage: 'map', gallery: 'gallery-thumbnails', reviews: 'star', cta: 'mouse-pointer-click', hours: 'clock', 'exit-intent': 'log-out' };

    sectionsContainer.innerHTML = sections.map(section => {
        const warningHTML = section.warning ? `<div class="text-xs text-yellow-700 font-semibold flex items-center gap-1 mt-1"><i data-lucide="alert-triangle" class="w-3 h-3"></i> No Recomendable Desactivar</div>` : '';
        const subtextHTML = section.subtext ? `<p class="text-xs text-gray-500">${section.subtext}</p>` : '';
        const isChecked = section.checked !== false ? 'checked' : '';
        return `<div class="toggle-wrapper flex items-start justify-between p-3 bg-gray-50 rounded-lg border"><div class="flex items-start gap-3"><i data-lucide="${icons[section.id]}" class="w-5 h-5 text-gray-500 mt-1 flex-shrink-0"></i><div><label for="toggle-${section.id}" class="font-bold text-gray-700 cursor-pointer">${section.label}</label>${warningHTML}${subtextHTML}</div></div><div class="relative inline-flex items-center cursor-pointer mt-1"><input type="checkbox" id="toggle-${section.id}" class="sr-only peer toggle-checkbox" ${isChecked}><div class="w-11 h-5 rounded-full peer-checked:bg-[var(--color-success)] transition toggle-label"><div class="h-5 w-5 bg-white rounded-full shadow-md transform transition-transform peer-checked:translate-x-full toggle-circle"></div></div></div></div>`;
    }).join('');

    sectionsForm.addEventListener('click', e => {
        const wrapper = e.target.closest('.toggle-wrapper');
        if (wrapper) {
            const checkbox = wrapper.querySelector('.toggle-checkbox');
            if (checkbox && (e.target.tagName !== 'INPUT')) {
                e.preventDefault();
                checkbox.checked = !checkbox.checked;
            }
        }
    });

    // --- LÓGICA DEL CÓDIGO QR ---
    const qrcodeCanvas = document.getElementById('qrcode-canvas');
    const downloadQRBtn = document.getElementById('download-qr-btn');
    const websiteInput = document.getElementById('business-website');
    let qrCodeInstance = null;

    const generateQRCode = () => {
        const url = websiteInput.value.trim();
        qrcodeCanvas.innerHTML = ''; // Limpiar el contenedor
        
        if (url) {
            qrCodeInstance = new QRCode(qrcodeCanvas, {
                text: url,
                width: 160,
                height: 160,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });

            // Esperar un momento para que la librería genere el <img>
            setTimeout(() => {
                const img = qrcodeCanvas.querySelector('img');
                if (img) {
                    downloadQRBtn.href = img.src;
                    downloadQRBtn.classList.remove('opacity-50', 'pointer-events-none');
                }
            }, 100);

        } else {
            // Si no hay URL, deshabilitar el botón
            downloadQRBtn.classList.add('opacity-50', 'pointer-events-none');
            qrcodeCanvas.innerHTML = '<span class="text-xs text-gray-400">Ingresa una URL para generar el código</span>';
        }
    };

    // Generar QR al cambiar la URL
    websiteInput.addEventListener('input', generateQRCode);


    // --- CARGAR Y GUARDAR DATOS ---
    const loadBusinessInfo = async () => {
        try {
            const response = await fetch('db/business-info-read.php');
            const result = await response.json();
            if (result.success) {
                const data = result.data.general;
                const socialLinks = result.data.social_links;
                const tracking = result.data.tracking_codes;
                const sectionsData = result.data.sections_enabled;
                
                document.getElementById('business-name').value = data.company_name || '';
                document.getElementById('contact-name').value = data.full_name || '';
                document.getElementById('license-number').value = data.license_number || '';
                document.getElementById('business-email').value = data.site_email || '';
                document.getElementById('business-website').value = data.website_url || '';
                masks.phone1.value = data.phone_primary || '';
                masks.phone2.value = data.phone_secondary || '';
                masks.whatsapp.value = data.whatsapp || '';
                
                if (data.logo_url) {
                    document.getElementById('preview-logo').src = data.logo_url;
                }
                
                document.querySelectorAll('#business-info-form input').forEach(input => updatePreview(input));

                // Después de cargar la info, generar el QR inicial
                generateQRCode();

                if (socialLinks && socialLinks.length > 0) {
                    socialRepeater.innerHTML = ''; socialCounter = 0;
                    socialLinks.forEach(link => {
                        socialCounter++;
                        socialRepeater.insertAdjacentHTML('beforeend', createSocialItemHTML(socialCounter, link.link_icon, link.link_url));
                    });
                } else {
                    socialRepeater.innerHTML = '';
                }
                renderSocialPreview();

                if (tracking) {
                    document.getElementById('gtm-head').value = tracking.tracking_codes_head || '';
                    document.getElementById('gtm-body').value = tracking.tracking_codes_body || '';
                }
                
                if (sectionsData) {
                    sections.forEach(section => {
                        const checkbox = document.getElementById(`toggle-${section.id}`);
                        const dbKey = section.id === 'exit-intent' ? 'exit_intent_enabled' : `${section.id}_page_enabled`;
                        if (checkbox && sectionsData[dbKey] !== undefined) {
                            checkbox.checked = sectionsData[dbKey] == 1;
                        }
                    });
                }
            }
        } catch (error) {
            console.error('Error al cargar la información general:', error);
            showToast('Error al cargar la información general.', 'error');
        }
    };

    const loadColors = async () => {
        try {
            const response = await fetch('cms/colors-read.php');
            const result = await response.json();
            if (result.success && result.data) {
                const colors = result.data;
                const primaryColor = (colors.branding_color_primary || '#1E3A8A').toUpperCase();
                document.getElementById('branding-color-primary').value = primaryColor;
                masks.colorPrimary.value = primaryColor;
                
                const secondaryColor = (colors.branding_color_secondary || '#991B1B').toUpperCase();
                document.getElementById('branding-color-secondary').value = secondaryColor;
                masks.colorSecondary.value = secondaryColor;

                const accentColor = (colors.branding_color_accent || '#F59E0B').toUpperCase();
                document.getElementById('branding-color-accent').value = accentColor;
                masks.colorAccent.value = accentColor;
            }
        } catch (error) {
            console.error('Error al cargar colores:', error);
            showToast('Error al cargar los colores.', 'error');
        }
    };

    loadBusinessInfo();
    loadColors();
    lucide.createIcons();

    // --- EVENT LISTENERS PARA GUARDAR CADA FORMULARIO ---
    document.getElementById('business-info-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('company_name', document.getElementById('business-name').value);
        formData.append('full_name', document.getElementById('contact-name').value);
        formData.append('license_number', document.getElementById('license-number').value);
        formData.append('site_email', document.getElementById('business-email').value);
        formData.append('website_url', document.getElementById('business-website').value);
        formData.append('phone_primary', masks.phone1.unmaskedValue);
        formData.append('phone_secondary', masks.phone2.unmaskedValue);
        formData.append('whatsapp', masks.whatsapp.unmaskedValue);

        try {
            const response = await fetch('db/business-info-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar la información.', 'error');
        }
    });

    document.getElementById('branding-colors-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('branding_color_primary', masks.colorPrimary.value);
        formData.append('branding_color_secondary', masks.colorSecondary.value);
        formData.append('branding_color_accent', masks.colorAccent.value);
        try {
            const response = await fetch('cms/colors-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar los colores.', 'error');
        }
    });

    document.getElementById('social-links-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData();
        const socialLinks = [];
        socialRepeater.querySelectorAll('.social-item').forEach(item => {
            const icon = item.querySelector('.social-icon').value;
            const url = item.querySelector('.social-url').value;
            if (url) socialLinks.push({ icon, url });
        });
        formData.append('social_links_json', JSON.stringify(socialLinks));
        try {
            const response = await fetch('cms/social-links-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar los enlaces sociales.', 'error');
        }
    });

    document.getElementById('tracking-codes-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('tracking_codes_head', document.getElementById('gtm-head').value);
        formData.append('tracking_codes_body', document.getElementById('gtm-body').value);
        try {
            const response = await fetch('cms/tracking-codes-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar los códigos de seguimiento.', 'error');
        }
    });

    document.getElementById('logo-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const fileInput = document.getElementById('logo-upload');
        if (fileInput.files.length === 0) {
            showToast('Por favor, selecciona un archivo primero.', 'error');
            return;
        }
        const formData = new FormData(e.target);
        try {
            const response = await fetch('db/logo-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
            if (result.success) {
                 document.getElementById('preview-logo').src = result.logo_url + '?t=' + new Date().getTime();
            }
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar el logotipo.', 'error');
        }
    });

    document.getElementById('sections-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData();
        sections.forEach(section => {
            const checkbox = document.getElementById(`toggle-${section.id}`);
            if (checkbox) {
                formData.append(`${section.id}_page_enabled`, checkbox.checked ? '1' : '0');
            }
        });
        try {
            const response = await fetch('cms/sections-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
        } catch (error) {
            console.error('Error:', error);
            showToast('Ocurrió un error al guardar las preferencias de secciones.', 'error');
        }
    });
});
</script>

</body>
</html>