<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');

// Fixed Portal Variables (Para QRs)
$url_booking = $client_info['urls']['booking'] ?? PORTAL_PATHS['booking'];
$url_client_portal = $client_info['urls']['client_portal'] ?? PORTAL_PATHS['client_portal'];
$url_member_portal = $client_info['urls']['member_portal'] ?? PORTAL_PATHS['member_portal'];

if (ob_get_level() > 0) { 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 Del Negocio <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
</head>

<body data-page-title="Información Estratégica Del Negocio" 
      data-page-subtitle="Actualiza todos los datos importante de tu negocio" 
      data-page-icon="briefcase">
    
    <div id="toast-container" class="toast-container"></div>

    <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="negocio" class="dashboard-section">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                
                <div class="lg:col-span-1 space-y-8">
                    <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-primary)]">
                        <h3 class="text-2xl font-black text-gray-800 mb-6 uppercase flex items-center gap-2">
                            <i data-lucide="info" class="w-6 h-6 text-[var(--color-secondary)]"></i> INFORMACIÓN DE TU EMPRESA
                        </h3>
                        <form id="company-info-form" class="space-y-4">
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">NOMBRE DEL NEGOCIO <span class="text-red-500">*</span></label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="building-2" class="w-4 h-4"></i></span><input type="text" id="company-name" name="company_name" required class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">NOMBRE DEL CONTACTO <span class="text-red-500">*</span></label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="user" class="w-4 h-4"></i></span><input type="text" id="contact-name" name="full_name" required class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">CORREO ELECTRÓNICO <span class="text-red-500">*</span></label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="mail" class="w-4 h-4"></i></span><input type="email" id="company-email" name="site_email" required class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">PÁGINA WEB <span class="text-red-500">*</span></label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="globe" class="w-4 h-4"></i></span><input type="text" id="website-url" name="website_url" required class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800 placeholder-gray-400" placeholder="ejemplo.com"></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">TELÉFONO PRINCIPAL <span class="text-red-500">*</span></label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="phone" class="w-4 h-4"></i></span><input type="text" id="phone-primary" name="phone_primary" required class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">TELÉFONO SECUNDARIO</label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="smartphone" class="w-4 h-4"></i></span><input type="text" id="phone-secondary" name="phone_secondary" class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">NÚMERO DE LICENCIA</label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="badge-check" class="w-4 h-4"></i></span><input type="text" id="license-number" name="license_number" class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">WHATSAPP</label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="message-circle" class="w-4 h-4"></i></span><input type="text" id="whatsapp" name="whatsapp" class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></div></div>
                            
                            <div class="pt-4 text-right">
                                <button type="submit" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                                    <i data-lucide="save" class="w-4 h-4"></i> ACTUALIZAR INFORMACIÓN
                                </button>
                            </div>
                        </form>
                    </div>

                    <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-primary)]">
                        <h3 class="text-2xl font-black text-gray-800 mb-6 uppercase flex items-center gap-2">
                            <i data-lucide="activity" class="w-6 h-6 text-[var(--color-secondary)]"></i> CÓDIGOS DE TRACKING
                        </h3>
                        <form id="tracking-codes-form" class="space-y-4">
                            <div>
                                <label class="block text-gray-600 text-xs font-bold mb-1 uppercase">CÓDIGO (HEAD)</label>
                                <textarea id="tracking_codes_head" name="tracking_codes_head" rows="4" class="w-full p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></textarea>
                            </div>
                            <div>
                                <label class="block text-gray-600 text-xs font-bold mb-1 uppercase">CÓDIGO (BODY)</label>
                                <textarea id="tracking_codes_body" name="tracking_codes_body" rows="4" class="w-full p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800"></textarea>
                            </div>
                            <div class="pt-4 text-right">
                                <button type="submit" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                                    <i data-lucide="save" class="w-4 h-4"></i> GUARDAR TRACKING
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="lg:col-span-1 space-y-8">
                    <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-secondary)]">
                        <h3 class="text-lg font-extrabold text-gray-800 mb-6 uppercase flex items-center gap-2">
                             <i data-lucide="image" class="w-5 h-5 text-[var(--color-secondary)]"></i> ACTUALIZAR LOGOTIPO
                        </h3>
                        <form id="logo-form" class="w-full" action="db/logo-update.php" method="POST" enctype="multipart/form-data">
                            <div class="flex items-center gap-4 flex-col md:flex-row">
                                <input type="file" id="logo-upload" name="logo_upload" accept="image/*" class="w-full hidden">
                                <label for="logo-upload" class="cursor-pointer w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                                    <i data-lucide="upload" class="w-5 h-5"></i><span>Seleccionar Archivo</span>
                                </label>
                                <span id="logo-file-name" class="text-sm text-gray-600 text-center md:text-left truncate w-full md:w-auto">Ningún archivo seleccionado</span>
                            </div>
                            <button id="update-logo-button" type="submit" class="mt-6 w-full bg-[var(--color-primary)] text-white hover:bg-[var(--color-primary-dark)] font-bold py-3 px-4 rounded-lg flex items-center justify-center uppercase text-sm shadow-md transition-all disabled-button">
                                <i data-lucide="check" class="w-4 h-4 mr-2"></i> CONFIRMAR LOGO
                            </button>
                        </form>
                    </div>
                    
                    <div id="vip-card-preview" class="p-6 rounded-xl shadow-2xl overflow-hidden relative border-b-8 border-[var(--color-secondary)] transition-all duration-300 bg-[var(--color-primary)] text-white">
                        <div class="relative z-10 space-y-6">
                            <div class="flex items-center gap-5">
                                <div class="bg-white p-1.5 rounded-full shadow-lg">
                                    <img id="vip-logo-preview" class="w-20 h-20 object-contain rounded-full" src="img/default-logo.png" alt="Logo">
                                </div>
                                <div>
                                    <h3 id="vip-company-name" class="text-2xl font-extrabold leading-tight">Nombre del Negocio</h3>
                                    <p id="vip-contact-name" class="text-sm font-bold text-[var(--color-highlight)] uppercase tracking-wider mt-1 opacity-90">Nombre Contacto</p>
                                </div>
                            </div>
                            <hr class="border-white/20">
                            <div class="space-y-3 text-sm font-bold tracking-wide">
                                <p class="flex items-center gap-3 opacity-90"><i data-lucide="mail" class="w-4 h-4 text-[var(--color-highlight)]"></i> <span id="vip-email">correo@ejemplo.com</span></p>
                                <p class="flex items-center gap-3 opacity-90"><i data-lucide="phone" class="w-4 h-4 text-[var(--color-highlight)]"></i> <span id="vip-phone-primary">(000) 000-0000</span></p>
                                <p class="flex items-center gap-3 opacity-90"><i data-lucide="globe" class="w-4 h-4 text-[var(--color-highlight)]"></i> <a id="vip-website" href="#" target="_blank" class="text-[var(--color-accent-light)] hover:text-white hover:underline transition-colors">www.sitio.com</a></p>
                                <p id="vip-license-container" class="flex items-center gap-3 opacity-80 hidden"><i data-lucide="award" class="w-4 h-4 text-[var(--color-highlight)]"></i> Licencia: <span id="vip-license-number"></span></p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-2xl font-black text-[var(--color-text-dark)] mb-4 uppercase flex items-center gap-2"><i data-lucide="gem" class="w-6 h-6 text-[var(--color-primary)]"></i> MEMBRESÍA</h3> 
                        <ul class="space-y-4 text-sm border-t border-gray-100 pt-4">
                            <li class="flex justify-between items-center"><span class="font-black text-[var(--color-text-dark)] opacity-60 uppercase text-md">Versión:</span><span id="plan-version" class="font-black bg-[var(--color-background)] text-[var(--color-success)] py-1 px-3 rounded-full uppercase text-xs border border-gray-200">-</span></li>
                            <li class="flex justify-between items-center"><span class="font-black text-[var(--color-text-dark)] opacity-60 uppercase text-md">Renovación:</span><span id="plan-renewal-date" class="font-bold text-[var(--color-text-dark)] uppercase">-</span></li>
                            <li class="flex justify-between items-center"><span class="font-black text-[var(--color-text-dark)] opacity-60 uppercase text-md">Próxima Factura:</span><span id="next-invoice-date" class="font-bold text-[var(--color-text-dark)] uppercase">-</span></li>
                        </ul>
                        <a href="pay.php?type=monthly" class="w-full mt-6 btn bg-[var(--color-success)] hover:opacity-90 text-[var(--color-text-light)] font-bold py-3 px-4 rounded-lg flex items-center justify-center uppercase shadow-md transition-colors"><i data-lucide="zap" class="w-5 h-5 mr-2"></i> RENOVAR AHORA</a>
                        <button id="manage-payment-button" class="w-full mt-2 btn bg-[var(--color-primary)] hover:opacity-90 text-[var(--color-text-light)] font-bold py-3 px-4 rounded-lg flex items-center justify-center uppercase shadow-md transition-colors"><i data-lucide="credit-card" class="w-4 h-4 mr-2"></i> GESTIONAR</button>
                    </div>

                    <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-secondary)]">
                        <h3 class="text-2xl font-black text-gray-800 mb-6 uppercase flex items-center gap-2"><i data-lucide="star" class="w-6 h-6 text-[var(--color-secondary)]"></i> LINKS REVIEWS</h3>
                        <form id="review-links-form" class="space-y-4">
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">Google Business Profile</label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="user-star" class="w-4 h-4"></i></span><input type="text" id="link_google" name="link_google" class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800" placeholder="https://..."></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">Yelp</label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="star" class="w-4 h-4"></i></span><input type="text" id="link_yelp" name="link_yelp" class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800" placeholder="https://..."></div></div>
                            <div><label class="block text-gray-600 text-xs font-bold mb-1 uppercase">Facebook Reviews</label><div class="relative"><span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-400 pointer-events-none"><i data-lucide="facebook" class="w-4 h-4"></i></span><input type="text" id="link_facebook" name="link_facebook" class="w-full pl-10 p-3 border border-gray-300 rounded-lg outline-none font-bold text-gray-800" placeholder="https://..."></div></div>
                            <div class="pt-4 text-right"><button type="submit" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2"><i data-lucide="save" class="w-4 h-4"></i> GUARDAR LINKS</button></div>
                        </form>
                    </div>
                </div>
            </div>
        </section>
        
        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-primary)]">
            <h3 class="text-2xl font-black text-gray-800 mb-6 uppercase flex items-center gap-2"><i data-lucide="link" class="w-6 h-6 text-[var(--color-secondary)]"></i> CÓDIGOS QR Y MARKETING</h3>
            <div id="portal-urls-container" class="space-y-4">
                <div class="flex flex-col md:grid md:grid-cols-3 gap-4">
                    <div class="url-input-group">
                        <label class="block text-[var(--color-secondary)] text-2xl font-black mb-1 uppercase">SISTEMA BOOKING</label>
                        <div class="relative mb-2">
                            <input type="text" value="<?php echo $url_booking; ?>" readonly class="w-full p-3 border border-gray-200 bg-gray-50 rounded-lg text-xs text-gray-500 outline-none" data-qr-target="url_booking">
                            <button type="button" onclick="copyToClipboard('url_booking')" class="absolute inset-y-0 right-0 pr-3 flex items-center"><i data-lucide="copy" class="w-5 h-5 text-gray-400"></i></button>
                        </div>
                        <div id="qr-container-url_booking" class="qr-container flex flex-col items-center justify-center p-2 border border-dashed border-gray-300 rounded-lg bg-gray-50">
                            <canvas class="qr-code-canvas mb-2" data-url="<?php echo $url_booking; ?>"></canvas>
                            <a href="#" download="QRBooking.png" class="w-full bg-[var(--color-secondary)] text-white font-black py-2 px-4 rounded text-center text-xs">Descargar QR</a>
                        </div>
                    </div>
                    <div class="url-input-group">
                        <label class="block text-[var(--color-secondary)] text-2xl font-black mb-1 uppercase">PORTAL CLIENTE</label>
                        <div class="relative mb-2">
                            <input type="text" value="<?php echo $url_client_portal; ?>" readonly class="w-full p-3 border border-gray-200 bg-gray-50 rounded-lg text-xs text-gray-500 outline-none" data-qr-target="url_client_portal">
                            <button type="button" onclick="copyToClipboard('url_client_portal')" class="absolute inset-y-0 right-0 pr-3 flex items-center"><i data-lucide="copy" class="w-5 h-5 text-gray-400"></i></button>
                        </div>
                        <div id="qr-container-url_client_portal" class="qr-container flex flex-col items-center justify-center p-2 border border-dashed border-gray-300 rounded-lg bg-gray-50">
                            <canvas class="qr-code-canvas mb-2" data-url="<?php echo $url_client_portal; ?>"></canvas>
                            <a href="#" download="QRPortalCliente.png" class="w-full bg-[var(--color-secondary)] text-white font-black py-2 px-4 rounded text-center text-xs">Descargar QR</a>
                        </div>
                    </div>
                    <div class="url-input-group">
                        <label class="block text-[var(--color-secondary)] text-2xl font-black mb-1 uppercase">PORTAL EMPLEADO</label>
                        <div class="relative mb-2">
                            <input type="text" value="<?php echo $url_member_portal; ?>" readonly class="w-full p-3 border border-gray-200 bg-gray-50 rounded-lg text-xs text-gray-500 outline-none" data-qr-target="url_member_portal">
                            <button type="button" onclick="copyToClipboard('url_member_portal')" class="absolute inset-y-0 right-0 pr-3 flex items-center"><i data-lucide="copy" class="w-5 h-5 text-gray-400"></i></button>
                        </div>
                        <div id="qr-container-url_member_portal" class="qr-container flex flex-col items-center justify-center p-2 border border-dashed border-gray-300 rounded-lg bg-gray-50">
                            <canvas class="qr-code-canvas mb-2" data-url="<?php echo $url_member_portal; ?>"></canvas>
                            <a href="#" download="QRPortalEmpleado.png" class="w-full bg-[var(--color-secondary)] text-white font-black py-2 px-4 rounded text-center text-xs">Descargar QR</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
<section id="horarios" class="dashboard-section">
    <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-primary)]">
        <h3 class="text-2xl font-black text-gray-800 mb-6 uppercase flex items-center gap-2">
            <i data-lucide="clock" class="w-6 h-6 text-[var(--color-secondary)]"></i> HORARIOS DE ATENCIÓN
        </h3>
        
        <form id="schedule-form" class="space-y-6">
            <p class="text-sm text-gray-600 mb-4">Configura la disponibilidad general, intervalos y días de apertura.</p>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 pb-6 border-b border-gray-100">
                <div class="flex flex-col space-y-2">
                    <label class="font-black text-gray-700 text-lg uppercase">Intervalo entre citas</label>
                    <div class="relative">
                        <select id="slot_duration" name="slot_duration" class="w-full p-3 border border-gray-300 rounded-lg text-sm text-gray-700 appearance-none bg-white focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent outline-none transition-all">
                            <option value="15">15 Minutos</option>
                            <option value="30" selected>30 Minutos</option>
                            <option value="45">45 Minutos</option>
                            <option value="60">1 Hora</option>
                            <option value="90">1 Hora 30 Min</option>
                            <option value="120">2 Horas</option>
                        </select>
                        <i data-lucide="chevron-down" class="absolute right-3 top-3.5 w-4 h-4 text-gray-400 pointer-events-none"></i>
                    </div>
                    <span class="text-xs text-gray-500">Duración base de cada servicio.</span>
                </div>

                <div class="flex flex-col space-y-2">
                    <label class="font-black text-gray-700 text-lg uppercase">Cupos por horario (Slots)</label>
                    <div class="relative">
                        <input type="number" id="capacity" name="capacity" min="1" max="20" value="1" class="w-full p-3 border border-gray-300 rounded-lg text-sm text-gray-700 focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent outline-none transition-all">
                        <i data-lucide="users" class="absolute right-3 top-3.5 w-4 h-4 text-gray-400 pointer-events-none"></i>
                    </div>
                    <span class="text-xs text-gray-500">Cuántos clientes puedes atender simultáneamente.</span>
                </div>
            </div>

            <div id="schedule-days-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                </div>

            <div class="pt-6 border-t border-gray-100">
                <h4 class="text-2xl font-black text-gray-800 uppercase mb-4 flex items-center gap-2">
                    <i data-lucide="calendar-off" class="w-5 h-5 text-red-600"></i> Bloquear Fechas Específicas
                </h4>
                <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                    <div class="flex flex-col md:flex-row gap-4 items-end">
                        <div class="w-full md:w-1/3">
                            <label class="block text-md font-black text-gray-600 mb-1 uppercase">Seleccionar Fecha</label>
                            <input type="date" id="block_date_input" class="w-full p-2 border border-gray-300 rounded-lg text-sm text-gray-700 focus:ring-2 focus:ring-red-100 outline-none">
                        </div>
                        <div class="w-full md:w-1/3">
                            <label class="block text-md font-black text-gray-600 mb-1 uppercase">Motivo (Opcional)</label>
                            <input type="text" id="block_reason_input" placeholder="Ej. Feriado Nacional" class="w-full p-2 border border-gray-300 rounded-lg text-sm text-gray-700 focus:ring-2 focus:ring-red-100 outline-none">
                        </div>
                        <button type="button" id="btn-add-blocked-date" class="bg-gray-800 text-white px-4 py-2 rounded-lg font-bold text-sm hover:bg-gray-700 transition-colors flex items-center gap-2 h-[38px]">
                            <i data-lucide="plus" class="w-4 h-4"></i> AGREGAR
                        </button>
                    </div>
                    
                    <div class="mt-4 flex flex-wrap gap-2" id="blocked-dates-list">
                    </div>
                </div>
            </div>

            <div class="pt-4 text-right">
                <button type="submit" class="w-full md:w-auto bg-[var(--color-secondary)] text-white hover:bg-[#991b1b] font-bold py-3 px-6 rounded-lg uppercase flex items-center justify-center md:ml-auto gap-2 shadow-md transition-transform active:scale-95">
                    <i data-lucide="save" class="w-4 h-4"></i> GUARDAR HORARIOS
                </button>
            </div>
        </form>
    </div>
</section>
        
    </div>
</main>
</div>

<div id="confirmUpdateModal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50"
     onclick="if(event.target === this) closeModal('confirmUpdateModal')">

    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center overflow-hidden">
    
        <div class="modal-header-container bg-[var(--color-primary)] p-6">
            <h3 class="modal-primary-title text-3xl font-black uppercase text-[var(--color-accent)] leading-none">CONFIRMAR</h3>
        </div>

        <div class="p-8">
            <div class="flex justify-center mb-6">
                <i data-lucide="alert-circle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
            </div>

            <p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                ¿SEGURO(A) DE LOS CAMBIOS?
                <span class="font-black text-[var(--color-secondary)] text-sm block mt-3 border-t border-gray-100 pt-3">CUALQUIER MODIFICACIÓN SE REFLEJARÁ EN TODO EL SISTEMA</span>
            </p>

            <div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4 mt-6">
                <button type="button" onclick="closeModal('confirmUpdateModal')" class="bg-[var(--color-primary)] text-white hover:bg-[var(--color-primary-dark)] font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-sm">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button type="button" onclick="executePendingAction()" class="bg-[var(--color-secondary)] text-white hover:bg-[var(--color-secondary-dark)] font-black py-2.5 px-6 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all" id="confirm-update-button">
                    <i data-lucide="save" class="w-5 h-5"></i> GUARDAR
                </button>
            </div>
            <p class="mt-6 uppercase text-xs font-black text-gray-400 tracking-wider"> 
                CONFIRMA PARA CONTINUAR
            </p>
        </div>
    </div>
</div>

<script type="module">
document.addEventListener('DOMContentLoaded', () => {
    let pendingAction = null; 
    let pendingFormData = null; 
    let blockedDates = []; 

    // ======================================================
    // 1. NUEVAS FUNCIONES: TOAST Y COPIAR (AGREGADO)
    // ======================================================

    // Función para mostrar notificación Toast (Visual)
    window.showToast = (message, type = 'success') => {
        const container = document.getElementById('toast-container');
        if(!container) return; // Seguridad por si no existe el div

        const toast = document.createElement('div');
        toast.className = `toast-message ${type}`;
        
        // Iconos usando Lucide (si está disponible) o emojis por defecto
        let iconHtml = '';
        if (type === 'success') {
            iconHtml = '<i data-lucide="check-circle" class="w-6 h-6 text-green-500"></i>';
        } else {
            iconHtml = '<i data-lucide="alert-triangle" class="w-6 h-6 text-red-500"></i>';
        }

        toast.innerHTML = `${iconHtml} <span class="font-medium">${message}</span>`;
        container.appendChild(toast);

        // Renderizar el icono insertado
        if(typeof lucide !== 'undefined') lucide.createIcons();

        // Animación de salida después de 3 segundos
        setTimeout(() => {
            toast.style.transition = 'all 0.5s ease';
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-10px)';
            setTimeout(() => toast.remove(), 500);
        }, 3000);
    };

    // Función para Copiar Links (Conectada a tus botones onclick)
    window.copyToClipboard = (targetId) => {
        const input = document.querySelector(`input[data-qr-target="${targetId}"]`);
        if (input) {
            navigator.clipboard.writeText(input.value)
                .then(() => {
                    window.showToast('¡Enlace copiado al portapapeles!', 'success');
                })
                .catch(err => {
                    console.error('Error al copiar', err);
                    window.showToast('Error al copiar el enlace', 'error');
                });
        }
    };

    // ======================================================
    // FIN NUEVAS FUNCIONES
    // ======================================================

    // --- CARGA DE DATOS (INTACTO) ---
    async function loadBusinessData() {
        try {
            const response = await fetch('db/business-info-read.php');
            const json = await response.json();
            
            if(!json.success || !json.data) return;
            const data = json.data;

            // 1. Llenar Info General
            if(data.general) {
                const g = data.general;
                setVal('company-name', g.company_name);
                setVal('contact-name', g.full_name);
                setVal('company-email', g.site_email);
                setVal('website-url', g.website_url);
                setVal('phone-primary', g.phone_primary);
                setVal('phone-secondary', g.phone_secondary);
                setVal('whatsapp', g.whatsapp);
                setVal('license-number', g.license_number);
                
                // Vista Previa VIP
                document.getElementById('vip-logo-preview').src = g.logo_url || 'img/default-logo.png';
                setText('vip-company-name', g.company_name);
                setText('vip-contact-name', g.full_name);
                setText('vip-email', g.site_email);
                setText('vip-phone-primary', g.phone_primary);
                document.getElementById('vip-website').href = g.website_url;
                document.getElementById('vip-website').innerText = g.website_url;
                if(g.license_number) {
                    document.getElementById('vip-license-container').classList.remove('hidden');
                    setText('vip-license-number', g.license_number);
                }
            }

            // 2. Tracking
            if(data.tracking_codes) {
                setVal('tracking_codes_head', data.tracking_codes.tracking_codes_head);
                setVal('tracking_codes_body', data.tracking_codes.tracking_codes_body);
            }

            // 3. Membresía
            if(data.membership) {
                setText('plan-version', data.membership.plan_version);
                setText('plan-renewal-date', data.membership.plan_renewal_date);
                setText('next-invoice-date', data.membership.next_invoice_date);
                const btn = document.getElementById('manage-payment-button');
                if(btn) btn.setAttribute('data-user-email', data.membership.email);
            }

            // 4. Review Links
            if(data.review_links && Array.isArray(data.review_links)) {
                data.review_links.forEach(link => {
                    const input = document.getElementById(`link_${link.platform_name}`);
                    if(input) input.value = link.link_url;
                });
            }

            // 5. Horarios
            if (data.schedule_config) {
                renderScheduleDays(data.schedule_config);
                // Cargar fechas bloqueadas si existen en la BD (asumiendo formato JSON)
                if (data.schedule_config.blocked_dates) {
                    try {
                        blockedDates = typeof data.schedule_config.blocked_dates === 'string' 
                            ? JSON.parse(data.schedule_config.blocked_dates) 
                            : data.schedule_config.blocked_dates;
                        renderBlockedDates();
                    } catch(e) { console.error('Error parse blocked dates', e); }
                }
            }

        } catch (e) {
            console.error("Error cargando datos:", e);
        }
    }

    // --- Lógica Fechas Bloqueadas (INTACTO) ---
    const btnAddBlocked = document.getElementById('btn-add-blocked-date');
    if(btnAddBlocked) {
        btnAddBlocked.addEventListener('click', () => {
            const dateInput = document.getElementById('block_date_input');
            const reasonInput = document.getElementById('block_reason_input');
            
            if(!dateInput.value) {
                window.showToast("Por favor seleccione una fecha", "error"); // Actualizado a Toast
                return;
            }

            // Agregar a la lista
            blockedDates.push({
                date: dateInput.value,
                reason: reasonInput.value || 'No especificado'
            });

            // Limpiar inputs
            dateInput.value = '';
            reasonInput.value = '';

            renderBlockedDates();
        });
    }

    function renderBlockedDates() {
        const container = document.getElementById('blocked-dates-list');
        container.innerHTML = '';

        blockedDates.forEach((item, index) => {
            const tag = document.createElement('div');
            tag.className = 'bg-gray-200 text-gray-700 px-3 py-1 rounded-full text-xs font-bold flex items-center gap-2 uppercase';
            tag.innerHTML = `
                <span>${item.date} ${item.reason ? '('+item.reason+')' : ''}</span>
                <button type="button" class="text-red-500 hover:text-red-700 font-black focus:outline-none remove-date-btn" data-index="${index}">
                    <i data-lucide="x" class="w-3 h-3"></i>
                </button>
            `;
            container.appendChild(tag);
        });

        // Re-asignar eventos de eliminar y lucide icons
        if(typeof lucide !== 'undefined') lucide.createIcons();
        document.querySelectorAll('.remove-date-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const idx = parseInt(e.currentTarget.getAttribute('data-index'));
                blockedDates.splice(idx, 1);
                renderBlockedDates();
            });
        });
    }


    // Función auxiliar para generar HTML de horarios con lógica JSON (INTACTO)
    function renderScheduleDays(config) {
        if(config.slot_duration) document.getElementById('slot_duration').value = config.slot_duration;
        if(config.capacity) document.getElementById('capacity').value = config.capacity;

        // Parsear JSON de horarios detallados si existe
        let dailyHours = {};
        try {
            if (config.daily_hours) {
                dailyHours = typeof config.daily_hours === 'string' ? JSON.parse(config.daily_hours) : config.daily_hours;
            }
        } catch (e) { console.error("Error parsing daily hours", e); }

        const days = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
        const dayOrder = [1, 2, 3, 4, 5, 6, 0];
        const activeDays = config.work_days ? config.work_days.split(',') : [];
        const globalStart = config.start_time ? config.start_time.substring(0,5) : '09:00';
        const globalEnd = config.end_time ? config.end_time.substring(0,5) : '17:00';

        const container = document.getElementById('schedule-days-container');
        container.innerHTML = ''; 

        dayOrder.forEach((dayValue) => {
            const dayName = days[dayValue];
            const isActive = activeDays.includes(dayValue.toString());
            
            let thisStart = globalStart;
            let thisEnd = globalEnd;

            if (dailyHours[dayValue]) {
                thisStart = dailyHours[dayValue].start || globalStart;
                thisEnd = dailyHours[dayValue].end || globalEnd;
            }

            const html = `
                <div class="p-3 border border-gray-200 rounded-lg flex flex-col space-y-2 hover:border-gray-300 transition-colors">
                    <div class="flex items-center justify-between">
                        <span class="font-black uppercase text-gray-800">${dayName}</span>
                        <label class="inline-flex items-center cursor-pointer">
                            <input type="checkbox" name="work_days[]" value="${dayValue}" class="sr-only peer toggle-day-switch" ${isActive ? 'checked' : ''}>
                            <div class="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[var(--color-highlight)] rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--color-primary)]"></div>
                        </label>
                    </div>
                    <div class="flex gap-2 time-slots-container ${isActive ? '' : 'opacity-50 pointer-events-none'}">
                        <input type="time" name="start_time_${dayValue}" value="${thisStart}" class="w-full p-2 border border-gray-300 rounded-lg text-sm text-gray-700 focus:border-[var(--color-primary)] outline-none">
                        <input type="time" name="end_time_${dayValue}" value="${thisEnd}" class="w-full p-2 border border-gray-300 rounded-lg text-sm text-gray-700 focus:border-[var(--color-primary)] outline-none">
                    </div>
                </div>
            `;
            container.innerHTML += html;
        });

        document.querySelectorAll('.toggle-day-switch').forEach(sw => {
            sw.addEventListener('change', (e) => {
                const slots = e.target.closest('.p-3').querySelector('.time-slots-container');
                if(e.target.checked) slots.classList.remove('opacity-50', 'pointer-events-none');
                else slots.classList.add('opacity-50', 'pointer-events-none');
            });
        });
    }

    // Helpers
    const setVal = (id, val) => { const el = document.getElementById(id); if(el) el.value = val || ''; };
    const setText = (id, val) => { const el = document.getElementById(id); if(el) el.innerText = val || ''; };

    // --- MANEJO DE MODAL Y ENVIO (INTACTO) ---
    window.openModal = (id) => {
        const modal = document.getElementById(id);
        const inner = modal.querySelector('div'); 
        modal.classList.remove('hidden');
        setTimeout(() => {
            inner.classList.remove('opacity-0', 'scale-95');
            inner.classList.add('opacity-100', 'scale-100');
        }, 10);
    };

    window.closeModal = (id) => {
        const modal = document.getElementById(id);
        const inner = modal.querySelector('div');
        inner.classList.remove('opacity-100', 'scale-100');
        inner.classList.add('opacity-0', 'scale-95');
        setTimeout(() => {
            modal.classList.add('hidden');
        }, 300);
    };
    
    // --- FUNCIÓN DE ACTUALIZACIÓN (MODIFICADA SOLO PARA TOAST) ---
    window.executePendingAction = async function() {
        window.closeModal('confirmUpdateModal');
        let endpoint = '';
        if(pendingAction === 'update_business_info') endpoint = 'db/business-info-update.php';
        else if(pendingAction === 'update_tracking') endpoint = 'db/tracking-codes-update.php';
        else if(pendingAction === 'update_schedule') endpoint = 'db/schedule-update.php';
        else if(pendingAction === 'update_reviews') endpoint = 'db/review-links-update.php';

        try {
            const res = await fetch(endpoint, { method: 'POST', body: pendingFormData });
            const result = await res.json();
            
            if(result.success) {
                // MODIFICACION: Usar Toast y esperar 1.5 seg antes de recargar
                window.showToast('¡Información actualizada correctamente!', 'success');
                setTimeout(() => {
                    location.reload(); 
                }, 1500);
            } else {
                // MODIFICACION: Usar Toast en lugar de alert
                window.showToast('Error: ' + result.message, 'error');
            }
        } catch(e) { 
            console.error(e);
            window.showToast('Error de conexión con el servidor', 'error');
        }
    };

    const confirmSubmit = (action) => (e) => {
        e.preventDefault();
        pendingAction = action;
        pendingFormData = new FormData(e.target);
        
        if(action === 'update_schedule') {
            const days = Array.from(document.querySelectorAll('input[name="work_days[]"]:checked')).map(cb => cb.value);
            pendingFormData.delete('work_days[]');
            pendingFormData.set('work_days', days.join(','));

            const dailySchedule = {};
            let firstStart = '09:00';
            let firstEnd = '17:00';
            let capturedFirst = false;

            document.querySelectorAll('input[name="work_days[]"]').forEach(cb => {
                const dayVal = cb.value;
                const isActive = cb.checked;
                const startInput = document.querySelector(`input[name="start_time_${dayVal}"]`);
                const endInput = document.querySelector(`input[name="end_time_${dayVal}"]`);
                
                dailySchedule[dayVal] = {
                    active: isActive,
                    start: startInput ? startInput.value : '09:00',
                    end: endInput ? endInput.value : '17:00'
                };

                if (isActive && !capturedFirst) {
                    firstStart = dailySchedule[dayVal].start;
                    firstEnd = dailySchedule[dayVal].end;
                    capturedFirst = true;
                }
            });

            pendingFormData.set('daily_hours', JSON.stringify(dailySchedule));
            pendingFormData.set('start_time', firstStart);
            pendingFormData.set('end_time', firstEnd);
            
            // ENVIAR FECHAS BLOQUEADAS
            pendingFormData.set('blocked_dates', JSON.stringify(blockedDates));
        }

        window.openModal('confirmUpdateModal');
    };

    const f1 = document.getElementById('company-info-form'); if(f1) f1.addEventListener('submit', confirmSubmit('update_business_info'));
    const f2 = document.getElementById('tracking-codes-form'); if(f2) f2.addEventListener('submit', confirmSubmit('update_tracking'));
    const f3 = document.getElementById('schedule-form'); if(f3) f3.addEventListener('submit', confirmSubmit('update_schedule'));
    const f4 = document.getElementById('review-links-form'); if(f4) f4.addEventListener('submit', confirmSubmit('update_reviews'));

    document.querySelectorAll('.qr-code-canvas').forEach(canvas => {
        const url = canvas.getAttribute('data-url');
        if(url && typeof QRCode !== 'undefined') QRCode.toCanvas(canvas, url, { width: 200 });
    });

    loadBusinessData();
    if(typeof lucide !== 'undefined') lucide.createIcons();
});
</script>
<script src="files/toast.js"></script>
</body>
</html>