<?php
// Mínimo PHP necesario: Configuración de errores, sesión, guardián.
// ¡YA NO CARGAMOS DATOS AQUÍ!
ini_set('display_errors', 0); 
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log'); 
error_reporting(E_ALL);

ob_start(); // Iniciar buffer por si guardiankey imprime algo

try {
    session_start(); 
    require_once(__DIR__ . '/files/guardiankey.php'); 
    // Ya no necesitamos db_connection.php aquí para la carga inicial
    
    // Solo cargamos datos básicos del usuario desde la sesión si es necesario para el HTML inicial
    $user_id_session = $_SESSION['user_id'] ?? null; 
    // Podrías cargar el email/nombre del usuario aquí si lo muestras en el header, etc.
    // Ejemplo (requiere db_connection.php si haces esto):
    /*
    $user_display_name = 'Usuario';
    if ($user_id_session) {
        require_once(__DIR__ . '/db/db_connection.php');
        $stmt_simple_user = $pdo->prepare("SELECT full_name FROM users WHERE user_id = ?");
        $stmt_simple_user->execute([$user_id_session]);
        $simple_user = $stmt_simple_user->fetch(PDO::FETCH_ASSOC);
        if ($simple_user) $user_display_name = $simple_user['full_name'];
    }
    */

} catch (Exception $e) {
     error_log("Error inicial en account.php (sesión/guardián): " . $e->getMessage());
     // Manejar error si es necesario (ej. redirigir a login)
}

ob_end_clean(); // Limpiar cualquier salida de guardiankey
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Tu Cuenta De FlowCRM™ De OrozDesign Powered By OrozCO</title>
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
    <style>
        .custom-file-input { width: 100%; }
        /* ... el resto de tus estilos ... */
        .file-upload-container { display: flex; align-items: center; gap: 1rem; }
        .file-upload-container input[type="file"] { display: none; }
        .file-upload-label { cursor: pointer; background-color: var(--color-primary); color: white; padding: 0.5rem 1rem; border-radius: 0.5rem; font-weight: bold; display: inline-flex; align-items: center; gap: 0.5rem; transition: background-color 0.3s; }
        .file-upload-label:hover { background-color: #1a2b42; }
        .file-name-display { font-size: 0.875rem; color: #4b5563; }
        .toggle-password-btn { display: inline-flex; align-items: center; justify-content: center; width: 2rem; height: 2rem; color: #4b5563; }
        .toggle-password-btn:hover { opacity: 0.85; }
        .disabled-button { opacity: 0.5; cursor: not-allowed; } 
    </style>
</head>
<body data-page-title="Panel De Configuración De Tu Cuenta" 
      data-page-subtitle="Administra Tu Perfil, Suscripción Y Seguridad De Acceso" 
      data-page-icon="user-cog">
    
    <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">
                <?php if (!empty($db_error_message)): ?>
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
                        <strong class="font-bold">¡Error!</strong> <span class="block sm:inline"><?php echo htmlspecialchars($db_error_message); ?></span>
                    </div>
                <?php endif; ?>

                <section id="cuenta" class="dashboard-section">
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                        <div class="lg:col-span-1 space-y-8">
                            <div class="bg-white p-6 rounded-xl shadow-md text-center">
                                <h3 class="text-xl font-extrabold text-gray-800 mb-4 uppercase flex items-center justify-center gap-2"><i data-lucide="user-circle-2" class="w-6 h-6 text-[var(--color-primary)]"></i> FOTO DE PERFIL</h3>
                                <div class="relative w-32 h-32 mx-auto mb-4 group">
                                    <img id="profile-photo-preview" class="w-full h-full rounded-full border-4 border-[var(--color-highlight)]" src="https://placehold.co/128x128/cccccc/333333?text=U" alt="Avatar de usuario">
                                    <label for="profile-photo-upload" class="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center rounded-full opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"><i data-lucide="camera" class="w-8 h-8 text-white"></i><input type="file" id="profile-photo-upload" accept="image/*" class="hidden"></label>
                                </div>
                                </div>
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <h3 class="text-xl font-extrabold text-gray-800 mb-6 uppercase flex items-center gap-2"><i data-lucide="lock" class="w-6 h-6 text-[var(--color-primary)]"></i> SEGURIDAD</h3>
                                <form id="security-form" class="space-y-4">
                                     <div><label for="current-password" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CONTRASEÑA ACTUAL</label><div class="relative"><input type="password" id="current-password" name="current_password" class="w-full p-3 pr-12 border border-gray-300 rounded-lg"><button type="button" class="toggle-password-btn absolute top-1/2 right-3 -translate-y-1/2 text-gray-400" data-target="current-password"><span class="icon"></span></button></div></div>
                                     <div><label for="new-password" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NUEVA CONTRASEÑA</label><div class="relative"><input type="password" id="new-password" name="new_password" class="w-full p-3 pr-12 border border-gray-300 rounded-lg"><button type="button" class="toggle-password-btn absolute top-1/2 right-3 -translate-y-1/2 text-gray-400" data-target="new-password"><span class="icon"></span></button></div></div>
                                     <div><label for="confirm-password" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CONFIRMAR NUEVA CONTRASEÑA</label><div class="relative"><input type="password" id="confirm-password" name="confirm_password" class="w-full p-3 pr-12 border border-gray-300 rounded-lg"><button type="button" class="toggle-password-btn absolute top-1/2 right-3 -translate-y-1/2 text-gray-400" data-target="confirm-password"><span class="icon"></span></button></div></div>
                                     <div class="pt-4 text-right"><button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase">ACTUALIZAR CONTRASEÑA</button></div>
                                </form>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <h3 class="text-xl font-extrabold text-gray-800 mb-4 uppercase flex items-center gap-2"><i data-lucide="gem" class="w-6 h-6 text-[var(--color-primary)]"></i> DETALLES DEL PLAN</h3>
                                <ul class="space-y-4 text-sm">
                                    <li class="flex justify-between items-center"><span class="font-semibold text-gray-500 uppercase">Versión Actual:</span><span id="plan-version" class="font-bold text-gray-700 bg-gray-100 py-1 px-3 rounded-full uppercase">Cargando...</span></li>
                                    <li class="flex justify-between items-center"><span class="font-semibold text-gray-500 uppercase">Renovación:</span><span id="plan-renewal-date" class="font-bold text-gray-700 uppercase">Cargando...</span></li>
                                    <li class="flex justify-between items-center"><span class="font-semibold text-gray-500 uppercase">Próxima Factura:</span><span id="next-invoice-date" class="font-bold text-gray-700 uppercase">Cargando...</span></li>
                                </ul>
                                <button id="manage-payment-button" class="w-full mt-6 btn-secondary font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase text-sm"><i data-lucide="credit-card" class="w-4 h-4 mr-2"></i> GESTIONAR PAGO</button>
                            </div>
                        </div>

                        <div class="lg:col-span-2 space-y-8">
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <h3 class="text-xl font-extrabold text-gray-800 mb-6 uppercase flex items-center gap-2"><i data-lucide="contact" class="w-6 h-6 text-[var(--color-primary)]"></i> INFORMACIÓN DE ACCESO</h3>
                                <form id="personal-info-form" class="space-y-4">
                                    <div><label for="user-full-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NOMBRE COMPLETO</label><input type="text" id="user-full-name" name="full_name" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                                    <div><label for="user-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CORREO ELECTRÓNICO (NO MODIFICABLE)</label><input type="email" id="user-email" name="email" class="w-full p-3 border border-gray-300 rounded-lg bg-gray-100 cursor-not-allowed" disabled></div>
                                    <div class="pt-4 text-right"><button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase">GUARDAR CAMBIOS</button></div>
                                </form>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <h3 class="text-xl font-extrabold text-gray-800 mb-6 uppercase 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 flex-col items-center">
                                    <img id="logo-preview" class="w-48 h-auto mb-4" src="https://placehold.co/150x150/e2e8f0/333333?text=Logo" alt="Logo del negocio">
                                    <form id="logo-form" class="w-full">
                                        <div class="file-upload-container"><input type="file" id="logo-upload" name="logo_upload" accept="image/*" class="custom-file-input"><label for="logo-upload" class="file-upload-label"><i data-lucide="upload" class="w-5 h-5"></i><span>Seleccionar Archivo</span></label><span id="logo-file-name" class="file-name-display">Ningún archivo seleccionado</span></div>
                                    </form>
                                    <button id="update-logo-button" class="mt-4 w-full btn-primary font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase text-sm disabled-button"><i data-lucide="save" class="w-4 h-4 mr-2"></i> GUARDAR LOGOTIPO</button>
                                </div>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow-md">
                                <h3 class="text-xl font-extrabold text-gray-800 mb-6 uppercase 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>
                                <form id="company-info-form" class="space-y-4">
                                    <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" name="company_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" name="full_name" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                                        <div><label for="company-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CORREO ELECTRÓNICO</label><input type="email" id="company-email" name="site_email" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                                        <div><label for="website-url" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PÁGINA WEB</label><input type="url" id="website-url" name="website_url" 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="text" id="phone-primary" name="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="text" id="phone-secondary" name="phone_secondary" 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" name="license_number" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                                        <div><label for="whatsapp" class="block text-gray-700 text-sm font-bold mb-2 uppercase">WHATSAPP</label><input type="text" id="whatsapp" name="whatsapp" class="w-full p-3 border border-gray-300 rounded-lg"></div>
                                    </div>
                                    <div class="pt-4 text-right"><button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase">GUARDAR CAMBIOS</button></div>
                                </form>
                            </div>
                        </div>
                    </div>
                </section>
            </div>
        </main>
    </div>

<script type="module">
document.addEventListener('DOMContentLoaded', () => {

    // --- CACHÉ DE ELEMENTOS ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const personalInfoForm = document.getElementById('personal-info-form');
    const userFullNameInput = document.getElementById('user-full-name');
    const userEmailInput = document.getElementById('user-email'); // ID del email
    const profilePhotoUpload = document.getElementById('profile-photo-upload');
    const profilePhotoImg = document.getElementById('profile-photo-preview');
    const securityForm = document.getElementById('security-form');
    const newPasswordInput = document.getElementById('new-password');
    const confirmPasswordInput = document.getElementById('confirm-password');
    const companyInfoForm = document.getElementById('company-info-form');
    const logoPreview = document.getElementById('logo-preview');
    const logoUpload = document.getElementById('logo-upload');
    const logoFileNameDisplay = document.getElementById('logo-file-name');
    const logoForm = document.getElementById('logo-form');
    const updateLogoButton = document.getElementById('update-logo-button');
    // IDs para Plan Details
    const planVersionSpan = document.getElementById('plan-version');
    const planRenewalDateSpan = document.getElementById('plan-renewal-date');
    const nextInvoiceDateSpan = document.getElementById('next-invoice-date');

    let uploadedPhotoUrl = 'https://placehold.co/128x128/cccccc/333333?text=U'; // Default
    let logoFile = null;

    // --- UTILIDADES (showToast, toggleSidebar, setupPasswordToggles) ---
    const showToast = (message, type = 'info') => { /* ... tu código showToast ... */ 
        // ... (mismo código showToast que tenías antes) ...
        const toastContainer = document.getElementById('toast-container');
        if (!toastContainer) return;
        const toast = document.createElement('div');
        let iconHtml = '';
        let bgColor = 'bg-gray-800'; // Default info color
        if (type === 'success') { iconHtml = '<i data-lucide="check-circle" class="w-5 h-5"></i>'; bgColor = 'bg-green-600'; } 
        else if (type === 'error') { iconHtml = '<i data-lucide="alert-triangle" class="w-5 h-5"></i>'; bgColor = 'bg-red-600'; } 
        else if (type === 'warning') { iconHtml = '<i data-lucide="alert-circle" class="w-5 h-5"></i>'; bgColor = 'bg-yellow-500'; } 
        else { iconHtml = '<i data-lucide="info" class="w-5 h-5"></i>'; }
        toast.className = `fixed top-5 right-5 p-4 rounded-lg shadow-xl ${bgColor} text-white flex items-center gap-3 transform translate-x-full transition-transform duration-300 ease-in-out z-[100]`;
        toast.innerHTML = `${iconHtml}<p class="font-semibold">${message}</p>`;
        document.body.appendChild(toast); 
        lucide.createIcons(); 
        setTimeout(() => toast.classList.remove('translate-x-full'), 50); 
        setTimeout(() => { toast.classList.add('translate-x-full'); setTimeout(() => toast.remove(), 300); }, 3500); 
    };
    const toggleSidebar = () => { /* ... tu código toggleSidebar ... */ 
         sidebar?.classList.toggle('-translate-x-full');
         sidebarOverlay?.classList.toggle('hidden');
    };
    function setupPasswordToggles() { /* ... tu código setupPasswordToggles ... */ 
        // ... (mismo código setupPasswordToggles que tenías antes) ...
        document.querySelectorAll('.toggle-password-btn').forEach(btn => {
            const iconSpan = btn.querySelector('.icon');
            const targetId = btn.getAttribute('data-target');
            const input = document.getElementById(targetId);
            if (!input || !iconSpan) return;
            iconSpan.innerHTML = '<i data-lucide="eye" class="w-5 h-5 pointer-events-none"></i>';
            lucide.createIcons();
            btn.addEventListener('click', () => {
                const isHidden = input.type === 'password';
                input.type = isHidden ? 'text' : 'password';
                const newIconName = isHidden ? 'eye-off' : 'eye';
                iconSpan.innerHTML = `<i data-lucide="${newIconName}" class="w-5 h-5 pointer-events-none"></i>`;
                lucide.createIcons();
            });
        });
    }

    // --- FUNCIÓN PARA CARGAR TODOS LOS DATOS CON JS ---
    const loadAccountData = async () => {
        try {
            // 1. Cargar Info Empresa y Logo (usa el endpoint que ya funciona en cms-business-info)
            const bizInfoResponse = await fetch('db/business-info-read.php');
            const bizInfoResult = await bizInfoResponse.json();

            if (bizInfoResult.success && bizInfoResult.data && bizInfoResult.data.general) {
                const data = bizInfoResult.data.general;
                // Rellenar formulario Empresa
                document.getElementById('company-name').value = data.company_name || '';
                document.getElementById('contact-name').value = data.full_name || '';
                document.getElementById('company-email').value = data.site_email || '';
                document.getElementById('website-url').value = data.website_url || '';
                document.getElementById('license-number').value = data.license_number || '';
                
                // Aplicar máscaras (IMask.instances debe existir)
                const phonePrimaryMask = IMask.instances.find(inst => inst.el.input === document.getElementById('phone-primary'));
                if (phonePrimaryMask) phonePrimaryMask.value = data.phone_primary || ''; else document.getElementById('phone-primary').value = data.phone_primary || '';
                const phoneSecondaryMask = IMask.instances.find(inst => inst.el.input === document.getElementById('phone-secondary'));
                if (phoneSecondaryMask) phoneSecondaryMask.value = data.phone_secondary || ''; else document.getElementById('phone-secondary').value = data.phone_secondary || '';
                const whatsappMask = IMask.instances.find(inst => inst.el.input === document.getElementById('whatsapp'));
                if (whatsappMask) whatsappMask.value = data.whatsapp || ''; else document.getElementById('whatsapp').value = data.whatsapp || '';

                // Actualizar Logo Preview
                if (data.logo_url) {
                    let logoUrl = data.logo_url;
                    if (!logoUrl.startsWith('http') && !logoUrl.startsWith('https')) {
                        logoUrl = '/' + logoUrl.replace(/^\.\.\//g, '').replace(/^\//g, '');
                    }
                    logoPreview.src = logoUrl;
                } else {
                    logoPreview.src = 'https://placehold.co/150x150/e2e8f0/333333?text=Logo';
                }
            } else {
                showToast(bizInfoResult.message || 'Error cargando datos de empresa.', 'error');
            }

            // 2. Cargar Info Perfil Usuario (usa el endpoint user-profile-read.php)
            const profileResponse = await fetch('db/user-profile-read.php');
            const profileResult = await profileResponse.json();

            if (profileResult.success && profileResult.data) {
                const profileData = profileResult.data;
                // Rellenar formulario Info Acceso
                userFullNameInput.value = profileData.full_name || '';
                userEmailInput.value = profileData.email || ''; // Email (ya está disabled)

                // Actualizar Foto Perfil Preview y URL global
                if (profileData.profile_photo_url) {
                    let photoUrl = profileData.profile_photo_url;
                     if (!photoUrl.startsWith('http') && !photoUrl.startsWith('https')) {
                          photoUrl = '/' + photoUrl.replace(/^\.\.\//g, '').replace(/^\//g, '');
                     }
                    profilePhotoImg.src = photoUrl;
                    uploadedPhotoUrl = photoUrl; // Actualiza la variable global
                } else {
                     profilePhotoImg.src = 'https://placehold.co/128x128/cccccc/333333?text=U';
                     uploadedPhotoUrl = 'https://placehold.co/128x128/cccccc/333333?text=U';
                }

                // Rellenar Detalles del Plan
                planVersionSpan.textContent = profileData.plan_version || 'N/A';
                planVersionSpan.className = `font-bold ${profileData.plan_version ? 'text-green-600 bg-green-100' : 'text-gray-700 bg-gray-100'} py-1 px-3 rounded-full uppercase`; // Estilo dinámico
                
                planRenewalDateSpan.textContent = profileData.plan_renewal_date ? new Date(profileData.plan_renewal_date + 'T00:00:00').toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric'}) : 'N/A';
                
                nextInvoiceDateSpan.textContent = profileData.next_invoice_date ? new Date(profileData.next_invoice_date + 'T00:00:00').toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric'}) : 'N/A';

            } else {
                showToast(profileResult.message || 'Error cargando datos del perfil.', 'error');
            }

        } catch (error) {
            console.error('Error general al cargar datos de la cuenta:', error);
            showToast('Error de red al cargar datos. Intenta recargar.', 'error');
        }
    };

    // --- LÓGICA DE ACTUALIZACIÓN (sin cambios) ---
    const updatePersonalInfo = async (e) => { /* ... tu código ... */ 
        if (e) e.preventDefault();
        const full_name = userFullNameInput.value.trim();
        if (full_name === '') { showToast('El Nombre Completo no puede estar vacío.', 'error'); return; }
        // Usa la URL global actualizada por handleProfilePhotoUpload o loadAccountData
        const dataToSend = { full_name: full_name, profile_photo_url: uploadedPhotoUrl }; 
        try {
            const response = await fetch('db/user-profile-update.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(dataToSend) });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
        } catch (error) { showToast('Error de red o comunicación.', 'error'); console.error('Error:', error); }
    };
    const handleSecurityFormSubmit = async (e) => { /* ... tu código ... */ 
        e.preventDefault();
        const currentPassword = document.getElementById('current-password').value;
        const newPassword = newPasswordInput.value;
        const confirmPassword = confirmPasswordInput.value;
        if (!currentPassword || !newPassword || !confirmPassword) { showToast('Todos los campos de contraseña son obligatorios.', 'warning'); return; }
        if (newPassword !== confirmPassword) { showToast('La nueva contraseña y la confirmación no coinciden.', 'error'); return; }
        if (newPassword.length < 8) { showToast('La nueva contraseña debe tener al menos 8 caracteres.', 'error'); return; }
        const formData = new FormData();
        formData.append('current_password', currentPassword);
        formData.append('new_password', newPassword);
        try {
            const response = await fetch('db/user-password-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
            if (result.success) securityForm.reset();
        } catch (error) { showToast('Error de conexión al actualizar la contraseña.', 'error'); }    
    };
    const handleProfilePhotoUpload = async (event) => { /* ... tu código ... */ 
        const file = event.target.files[0];
        if (!file) return;
        const reader = new FileReader();
        // Mostrar preview local inmediatamente
        reader.onload = (e) => { profilePhotoImg.src = e.target.result; }; 
        reader.readAsDataURL(file);
        
        const formData = new FormData();
        formData.append('profile_photo_upload', file);
        try {
            const response = await fetch('db/profile-photo-upload.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
            if (result.success) {
                 // CORRECCIÓN: Aplicar lógica de ruta relativa a raíz a la URL devuelta
                 let finalPhotoUrl = result.photo_url;
                 if (!finalPhotoUrl.startsWith('http') && !finalPhotoUrl.startsWith('https')) {
                     finalPhotoUrl = '/' + finalPhotoUrl.replace(/^\.\.\//g, '').replace(/^\//g, '');
                 }
                 uploadedPhotoUrl = finalPhotoUrl; // Actualiza URL global
                 profilePhotoImg.src = finalPhotoUrl + '?t=' + new Date().getTime(); // Muestra la URL final + timestamp
            } else {
                 profilePhotoImg.src = uploadedPhotoUrl; // Revertir si falla la subida
            }
        } catch (error) { 
            showToast('Error de conexión al subir la foto.', 'error'); 
            profilePhotoImg.src = uploadedPhotoUrl; // Revertir si hay error de red
        }    
    };
    const handleCompanyInfoSubmit = async (e) => { /* ... tu código ... */ 
        e.preventDefault();
        const formData = new FormData(companyInfoForm);
        // Desmascarar teléfonos antes de enviar
        const phonePrimaryMask = IMask.instances.find(inst => inst.el.input === document.getElementById('phone-primary'));
        if (phonePrimaryMask) formData.set('phone_primary', phonePrimaryMask.unmaskedValue);
        const phoneSecondaryMask = IMask.instances.find(inst => inst.el.input === document.getElementById('phone-secondary'));
        if (phoneSecondaryMask) formData.set('phone_secondary', phoneSecondaryMask.unmaskedValue);
        const whatsappMask = IMask.instances.find(inst => inst.el.input === document.getElementById('whatsapp'));
        if (whatsappMask) formData.set('whatsapp', whatsappMask.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');
            // No recargar automáticamente
        } catch (error) { showToast('Error de conexión al guardar info empresa.', 'error'); }    
    };
    const handleLogoUpload = async (e) => { /* ... tu código ... */ 
        e.preventDefault();
        if (!logoFile) { showToast('Selecciona un archivo de logotipo.', 'warning'); return; }
        const formData = new FormData(logoForm); 
        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) {
                 // CORRECCIÓN: Aplicar lógica de ruta relativa a raíz a la URL devuelta
                 let finalLogoUrl = result.logo_url;
                 if (!finalLogoUrl.startsWith('http') && !finalLogoUrl.startsWith('https')) {
                     finalLogoUrl = '/' + finalLogoUrl.replace(/^\.\.\//g, '').replace(/^\//g, '');
                 }
                 logoPreview.src = finalLogoUrl + '?t=' + new Date().getTime(); // Muestra la URL final + timestamp
                 logoFile = null;
                 logoFileNameDisplay.textContent = "Ningún archivo seleccionado";
                 updateLogoButton.classList.add('disabled-button');
                 logoForm.reset(); 
            }
        } catch (error) { showToast('Error de conexión al subir el logotipo.', 'error'); console.error('Error:', error); }    
    };
    
    // --- INICIALIZACIÓN ---
    const init = () => {
        if (mobileMenuButton) mobileMenuButton.addEventListener('click', toggleSidebar);
        if (sidebarOverlay) sidebarOverlay.addEventListener('click', toggleSidebar);
        if (personalInfoForm) personalInfoForm.addEventListener('submit', updatePersonalInfo);
        if (securityForm) securityForm.addEventListener('submit', handleSecurityFormSubmit);
        if (profilePhotoUpload) profilePhotoUpload.addEventListener('change', handleProfilePhotoUpload);
        if (companyInfoForm) companyInfoForm.addEventListener('submit', handleCompanyInfoSubmit);
        if (updateLogoButton) updateLogoButton.addEventListener('click', handleLogoUpload);

        if (logoUpload) {
             logoUpload.addEventListener('change', (e) => { 
                const file = e.target.files[0];
                if (file) {
                    logoFile = file;
                    logoFileNameDisplay.textContent = file.name;
                    updateLogoButton.classList.remove('disabled-button');
                    const reader = new FileReader();
                    // Mostrar preview local al seleccionar
                    reader.onload = (ev) => { logoPreview.src = ev.target.result; }; 
                    reader.readAsDataURL(file);
                } else {
                    logoFile = null;
                    logoFileNameDisplay.textContent = "Ningún archivo seleccionado";
                    updateLogoButton.classList.add('disabled-button');
                    // Revertir preview al logo cargado por loadAccountData si se deselecciona
                     loadAccountData(); // Llama a recargar para obtener la URL correcta de la DB
                }
             });
        }

        // Aplicar máscaras (IMask debe estar cargado)
        IMask.instances = IMask.instances || []; // Crear array si no existe
        ['phone-primary', 'phone-secondary', 'whatsapp'].forEach(id => {
            const el = document.getElementById(id);
            if(el && typeof IMask !== 'undefined') {
                 IMask.instances.push(IMask(el, { mask: '(000) 000-0000' }));
            }
        });

        setupPasswordToggles();

        // --- LLAMAR A LA FUNCIÓN DE CARGA ---
        loadAccountData(); 

        // Notificaciones (sin cambios)
        const urlParams = new URLSearchParams(window.location.search);
        // ... (tu código de notificaciones) ...
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');
        if (notificationType && notificationMessage) {
            showToast(notificationMessage, notificationType);
        }
    };

    init();
    lucide.createIcons();
});
</script>
</body>
</html>