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

try {
    if (isset($user_id_session) && isset($pdo)) {
        
        $stmt = $pdo->prepare("SELECT full_name, email, profile_photo_url FROM users WHERE user_id = :id");
        $stmt->execute([':id' => $user_id_session]);
        $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt_biz = $pdo->prepare("SELECT company_name, logo_url FROM business_info WHERE user_id = :id LIMIT 1");
        $stmt_biz->execute([':id' => $user_id_session]);
        $biz_data = $stmt_biz->fetch(PDO::FETCH_ASSOC);

        if ($biz_data) {
            $business_name = $biz_data['company_name'] ?? ($business_name ?? 'Mi Negocio');
            $logo_url = !empty($biz_data['logo_url']) ? $biz_data['logo_url'] : ($logo_url ?? '');
        }

    } else {
        $user_data = ['full_name' => 'Visitante', 'email' => 'login@required.com'];
        // Fallbacks visuales por si falla init.php
        if (!isset($business_name)) $business_name = 'Panel CRM';
        if (!isset($branding)) $branding = ['full_title' => 'CRM', 'favicon' => 'favicon.ico'];
        if (!isset($logo_url)) $logo_url = '/brand/img/Placeholder.webp';
        if (!isset($google_font_url)) $google_font_url = '';
    }
} catch (Exception $e) {
    error_log("Error al cargar datos de usuario en vista: " . $e->getMessage());
}

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>Panel De Configuración <?php echo htmlspecialchars($branding['full_title'] ?? 'CRM'); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? 'favicon.ico'); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? 'favicon.ico'); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">
    
    <?php if(file_exists('files/gtm-head.php')) include 'files/gtm-head.php'; ?>

    <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>
</head>

<body data-page-title="Panel De Configuración De Membresía" 
      data-page-subtitle="Administra el acceso a tu centro de negocios" 
      data-page-icon="user-cog">
    
    <div id="toast-container" class="toast-container"></div>
    
    <?php if(file_exists('files/gtm-body.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="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></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">

    <div class="bg-white p-6 rounded-xl shadow-lg border-l-4 border-[var(--color-primary)] flex items-center gap-6">
        <div class="w-24 h-24 flex-shrink-0">
            <img src="<?php echo htmlspecialchars($logo_url); ?>" 
                 alt="Logo Negocio" 
                 class="w-full h-full object-contain rounded-lg border-2 border-[var(--color-background)] p-1">
        </div>
        <div>
            <p class="text-md font-black text-[var(--color-secondary)] uppercase">Membresía De Negocio Para:</p>
            <h2 class="text-5xl font-black text-[var(--color-primary)]"><?php echo htmlspecialchars($business_name); ?></h2>
        </div>
    </div>

    <section id="cuenta" 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 text-center">
                <h3 class="text-2xl font-black text-[var(--color-text-dark)] 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 object-cover rounded-full border-4 border-[var(--color-highlight)]" src="/brand/img/Placeholder.webp" alt="Avatar">
                    <label for="profile-photo-upload" class="absolute inset-0 bg-[var(--color-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>
                <p class="text-md text-[var(--color-text-dark)] uppercase opacity-60">Haz clic en la imagen para cambiarla</p>
            </div>
            
            <div class="bg-white p-6 rounded-xl shadow-md">
                <h3 class="text-2xl font-black text-[var(--color-text-dark)] 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-[var(--color-text-dark)] text-md font-black mb-1 uppercase">NOMBRE COMPLETO</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"><i data-lucide="user" class="w-5 h-5 text-gray-400"></i></div>
                            <input type="text" id="user-full-name" name="full_name" class="w-full pl-10 p-3 border border-gray-300 rounded-lg focus:border-[var(--color-primary)] focus:ring-1 focus:ring-[var(--color-primary)] outline-none transition-colors text-[var(--color-text-dark)]">
                        </div>
                    </div>

                    <div>
                        <label for="user-state" class="block text-[var(--color-text-dark)] text-md font-black mb-1 uppercase">ESTADO (UBICACIÓN)</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"><i data-lucide="map-pin" class="w-5 h-5 text-gray-400"></i></div>
                            <select id="user-state" name="state" class="w-full pl-10 p-3 border border-gray-300 font-bold rounded-lg focus:border-[var(--color-primary)] focus:ring-1 focus:ring-[var(--color-primary)] outline-none transition-colors bg-white appearance cursor-pointer text-[var(--color-text-dark)]">
                                <option value="" disabled selected>Selecciona Tu Estado...</option>
                            </select>
                            <div class="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none"><i data-lucide="chevron-down" class="w-4 h-4 text-gray-400"></i></div>
                        </div>
                        <p id="timezone-display" class="text-xs text-[var(--color-text-dark)] opacity-70 mt-1 font-bold uppercase text-right h-4"></p>
                        <input type="hidden" id="user-timezone" name="timezone">
                    </div>

                    <div>
                        <label for="user-email" class="block text-[var(--color-text-dark)] text-md font-black mb-1 uppercase">CORREO ELECTRÓNICO (NO MODIFICABLE)</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"><i data-lucide="mail" class="w-5 h-5 text-gray-400"></i></div>
                            <input type="email" id="user-email" name="email" class="w-full pl-10 p-3 border border-gray-300 rounded-lg bg-[var(--color-background)] cursor-not-allowed text-[var(--color-text-dark)] opacity-60" disabled>
                        </div>
                    </div>

                    <div class="pt-4 text-right">
                        <button type="submit" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-[var(--color-text-light)] font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all">
                            <i data-lucide="save" class="w-4 h-4"></i> GUARDAR CAMBIOS
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="lg:col-span-1 space-y-8">
            
            <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> DETALLES DE TU 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 Actual:</span>
                        <span id="plan-version" class="font-black py-1 px-4 rounded-full uppercase text-xs border shadow-sm tracking-wide">Cargando...</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 Realizada:</span><span id="plan-renewal-date" class="font-bold text-[var(--color-text-dark)] uppercase">Cargando...</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">Cargando...</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 MEMBRESÍA 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 MEMBRESÍA
                </button>
            </div>
            
            <div class="bg-white p-6 rounded-xl shadow-md">
                <h3 class="text-2xl font-black text-[var(--color-text-dark)] mb-6 uppercase flex items-center gap-2"><i data-lucide="lock" class="w-6 h-6 text-[var(--color-primary)]"></i> ACCESO Y SEGURIDAD</h3>
                <form id="security-form" class="space-y-4">
                    <div>
                        <label for="current-password" class="block text-[var(--color-text-dark)] text-xs font-bold mb-1 uppercase">CONTRASEÑA ACTUAL</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"><i data-lucide="key" class="w-5 h-5 text-gray-400"></i></div>
                            <input type="password" id="current-password" name="current_password" class="w-full pl-10 pr-10 p-3 border border-gray-300 rounded-lg focus:border-[var(--color-primary)] focus:ring-1 focus:ring-[var(--color-primary)] outline-none transition-colors">
                            <button type="button" class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer text-gray-400 hover:text-[var(--color-primary)] toggle-password-btn" data-target="current-password"><span class="icon"><i data-lucide="eye" class="w-5 h-5"></i></span></button>
                        </div>
                    </div>
                    <div>
                        <label for="new-password" class="block text-[var(--color-text-dark)] text-xs font-bold mb-1 uppercase">NUEVA CONTRASEÑA</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"><i data-lucide="lock" class="w-5 h-5 text-gray-400"></i></div>
                            <input type="password" id="new-password" name="new_password" class="w-full pl-10 pr-10 p-3 border border-gray-300 rounded-lg focus:border-[var(--color-primary)] focus:ring-1 focus:ring-[var(--color-primary)] outline-none transition-colors">
                            <button type="button" class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer text-gray-400 hover:text-[var(--color-primary)] toggle-password-btn" data-target="new-password"><span class="icon"><i data-lucide="eye" class="w-5 h-5"></i></span></button>
                        </div>
                    </div>
                    <div>
                        <label for="confirm-password" class="block text-[var(--color-text-dark)] text-xs font-bold mb-1 uppercase">CONFIRMAR NUEVA CONTRASEÑA</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"><i data-lucide="check-circle" class="w-5 h-5 text-gray-400"></i></div>
                            <input type="password" id="confirm-password" name="confirm_password" class="w-full pl-10 pr-10 p-3 border border-gray-300 rounded-lg focus:border-[var(--color-primary)] focus:ring-1 focus:ring-[var(--color-primary)] outline-none transition-colors">
                            <button type="button" class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer text-gray-400 hover:text-[var(--color-primary)] toggle-password-btn" data-target="confirm-password"><span class="icon"><i data-lucide="eye" class="w-5 h-5"></i></span></button>
                        </div>
                    </div>
                    <div class="pt-4 text-right">
                        <button type="submit" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-[var(--color-text-light)] font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2 transition-all"><i data-lucide="refresh-cw" class="w-4 h-4"></i> ACTUALIZAR CONTRASEÑA</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    </section>

    <?php include 'push.php'; ?>

</div>
</main>
</div>

<script type="module">
document.addEventListener('DOMContentLoaded', () => {
    
    // API ENDPOINTS
    const API_PROFILE_READ    = 'db/user-profile-read.php';
    const API_PROFILE_UPDATE  = 'db/user-profile-update.php';
    const API_PASSWORD_UPDATE = 'db/user-password-update.php';
    const API_PHOTO_UPLOAD    = 'db/profile-photo-upload.php';

    // ELEMENTOS DOM
    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');
    const userStateSelect = document.getElementById('user-state');
    const userTimezoneInput = document.getElementById('user-timezone');
    const timezoneDisplay = document.getElementById('timezone-display');
    const profilePhotoUpload = document.getElementById('profile-photo-upload');
    const profilePhotoImg = document.getElementById('profile-photo-preview');
    const securityForm = document.getElementById('security-form');
    const planVersionSpan = document.getElementById('plan-version');
    const planRenewalDateSpan = document.getElementById('plan-renewal-date');
    const nextInvoiceDateSpan = document.getElementById('next-invoice-date');
    const managePaymentButton = document.getElementById('manage-payment-button');

    let uploadedPhotoUrl = '/brand/img/Placeholder.webp';

    // DATOS ESTADOS USA
    const usStatesData = {
        'AL': { name: 'Alabama', tz: 'America/Chicago' }, 'AK': { name: 'Alaska', tz: 'America/Anchorage' },
        'AZ': { name: 'Arizona', tz: 'America/Phoenix' }, 'AR': { name: 'Arkansas', tz: 'America/Chicago' },
        'CA': { name: 'California', tz: 'America/Los_Angeles' }, 'CO': { name: 'Colorado', tz: 'America/Denver' },
        'CT': { name: 'Connecticut', tz: 'America/New_York' }, 'DE': { name: 'Delaware', tz: 'America/New_York' },
        'DC': { name: 'District of Columbia', tz: 'America/New_York' }, 'FL': { name: 'Florida', tz: 'America/New_York' },
        'GA': { name: 'Georgia', tz: 'America/New_York' }, 'HI': { name: 'Hawaii', tz: 'Pacific/Honolulu' },
        'ID': { name: 'Idaho', tz: 'America/Boise' }, 'IL': { name: 'Illinois', tz: 'America/Chicago' },
        'IN': { name: 'Indiana', tz: 'America/Indiana/Indianapolis' }, 'IA': { name: 'Iowa', tz: 'America/Chicago' },
        'KS': { name: 'Kansas', tz: 'America/Chicago' }, 'KY': { name: 'Kentucky', tz: 'America/New_York' },
        'LA': { name: 'Louisiana', tz: 'America/Chicago' }, 'ME': { name: 'Maine', tz: 'America/New_York' },
        'MD': { name: 'Maryland', tz: 'America/New_York' }, 'MA': { name: 'Massachusetts', tz: 'America/New_York' },
        'MI': { name: 'Michigan', tz: 'America/Detroit' }, 'MN': { name: 'Minnesota', tz: 'America/Chicago' },
        'MS': { name: 'Mississippi', tz: 'America/Chicago' }, 'MO': { name: 'Missouri', tz: 'America/Chicago' },
        'MT': { name: 'Montana', tz: 'America/Denver' }, 'NE': { name: 'Nebraska', tz: 'America/Chicago' },
        'NV': { name: 'Nevada', tz: 'America/Los_Angeles' }, 'NH': { name: 'New Hampshire', tz: 'America/New_York' },
        'NJ': { name: 'New Jersey', tz: 'America/New_York' }, 'NM': { name: 'New Mexico', tz: 'America/Denver' },
        'NY': { name: 'New York', tz: 'America/New_York' }, 'NC': { name: 'North Carolina', tz: 'America/New_York' },
        'ND': { name: 'North Dakota', tz: 'America/Chicago' }, 'OH': { name: 'Ohio', tz: 'America/New_York' },
        'OK': { name: 'Oklahoma', tz: 'America/Chicago' }, 'OR': { name: 'Oregon', tz: 'America/Los_Angeles' },
        'PA': { name: 'Pennsylvania', tz: 'America/New_York' }, 'RI': { name: 'Rhode Island', tz: 'America/New_York' },
        'SC': { name: 'South Carolina', tz: 'America/New_York' }, 'SD': { name: 'South Dakota', tz: 'America/Chicago' },
        'TN': { name: 'Tennessee', tz: 'America/Chicago' }, 'TX': { name: 'Texas', tz: 'America/Chicago' },
        'UT': { name: 'Utah', tz: 'America/Denver' }, 'VT': { name: 'Vermont', tz: 'America/New_York' },
        'VA': { name: 'Virginia', tz: 'America/New_York' }, 'WA': { name: 'Washington', tz: 'America/Los_Angeles' },
        'WV': { name: 'West Virginia', tz: 'America/New_York' }, 'WI': { name: 'Wisconsin', tz: 'America/Chicago' },
        'WY': { name: 'Wyoming', tz: 'America/Denver' }
    };

    // HELPERS
    const sanitizeText = (text) => {
        if (!text || typeof text !== 'string') return '';
        const tempDiv = document.createElement('div');
        tempDiv.textContent = text;
        return tempDiv.innerHTML;
    };
    
    const sanitizeURL = (url) => {
        if (!url || typeof url !== 'string') return '';
        const lowerUrl = url.toLowerCase();
        if (lowerUrl.startsWith('javascript:') || lowerUrl.startsWith('data:text/html')) return '';
        return url;
    };

    const toggleSidebar = () => { 
          sidebar?.classList.toggle('-translate-x-full');
          sidebarOverlay?.classList.toggle('hidden');
    };

    function setupPasswordToggles() { 
        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>';
            if(typeof lucide !== 'undefined') lucide.createIcons();
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                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>`;
                if(typeof lucide !== 'undefined') lucide.createIcons();
            });
        });
    }

    const populateStateDropdown = () => {
        const sortedCodes = Object.keys(usStatesData).sort();
        sortedCodes.forEach(code => {
            const info = usStatesData[code];
            const option = document.createElement('option');
            option.value = code;
            option.textContent = `${info.name} (${code})`;
            userStateSelect.appendChild(option);
        });
    };

    const handleStateChange = () => {
        const code = userStateSelect.value;
        if (code && usStatesData[code]) {
            const tz = usStatesData[code].tz;
            userTimezoneInput.value = tz;
            timezoneDisplay.textContent = `Zona Horaria: ${tz}`;
        } else {
            userTimezoneInput.value = '';
            timezoneDisplay.textContent = '';
        }
    };

    // CARGA DE DATOS
    const loadAccountData = async () => {
        try {
            const response = await fetch(API_PROFILE_READ);
            const text = await response.text(); 
            
            try {
                const result = JSON.parse(text);
                
                if (result.success && result.data) {
                    const data = result.data;
                    
                    userFullNameInput.value = sanitizeText(data.full_name) || '';
                    userEmailInput.value = sanitizeText(data.email) || '';
                    
                    if (data.timezone) {
                        userTimezoneInput.value = data.timezone;
                        timezoneDisplay.textContent = `Zona Horaria: ${sanitizeText(data.timezone)}`;
                    }

                    if (data.state) {
                        userStateSelect.value = data.state;
                        handleStateChange(); 
                    }
                    
                    if (data.profile_photo_url) {
                        let photoUrl = sanitizeURL(data.profile_photo_url);
                        if (photoUrl && !photoUrl.startsWith('http')) photoUrl = '/' + photoUrl.replace(/^\.\.\//g, '').replace(/^\//g, '');
                        uploadedPhotoUrl = photoUrl;
                        profilePhotoImg.src = uploadedPhotoUrl + '?t=' + new Date().getTime();
                    }

                    if (managePaymentButton && data.email) {
                        managePaymentButton.addEventListener('click', () => {
                            window.location.href = `customer-portal.php?email=${encodeURIComponent(data.email)}`;
                        });
                    }

                    // Plan details - ESTILOS LLAMATIVOS APLICADOS AQUÍ
                    const version = sanitizeText(data.plan_version) || 'N/A';
                    planVersionSpan.textContent = version;
                    
                    // Lógica para color de etiqueta (badge)
                    if (version !== 'N/A' && version !== 'Inactivo') {
                        // Estilo activo/verde llamativo (similar a la imagen)
                        // bg-green-100 texto-green-800 borde-green-200
                        planVersionSpan.className = `font-black bg-green-100 text-green-700 border border-green-200 py-1 px-4 rounded-full uppercase text-xs tracking-wide shadow-sm`;
                    } else {
                        // Estilo inactivo/gris
                        planVersionSpan.className = `font-black bg-gray-100 text-gray-600 border border-gray-200 py-1 px-4 rounded-full uppercase text-xs tracking-wide`;
                    }
                    
                    planRenewalDateSpan.textContent = data.plan_renewal_date ? new Date(data.plan_renewal_date + 'T00:00:00').toLocaleDateString('es-ES') : 'N/A';
                    nextInvoiceDateSpan.textContent = data.next_invoice_date ? new Date(data.next_invoice_date + 'T00:00:00').toLocaleDateString('es-ES') : 'N/A';

                } else {
                    showToast(result.message || 'Error cargando datos.', 'error');
                }
            } catch (jsonErr) {
                console.error("Respuesta no válida del servidor:", text);
                showToast("Error de servidor. Revisa la consola.", 'error');
            }
        } catch (error) {
            console.error(error);
            showToast('Error de conexión.', 'error');
        }
    };

    // ACCIONES
    const updatePersonalInfo = async (e) => { 
    if (e) e.preventDefault();
    
    const full_name = userFullNameInput.value.trim();
    const state = userStateSelect.value;
    const timezone = userTimezoneInput.value;
    
    if (full_name === '') { showToast('Nombre requerido.', 'error'); return; }
    if (state === '') { showToast('Selecciona un estado.', 'error'); return; }
    if (timezone === '') { showToast('Zona Horaria requerida.', 'error'); return; }

    const payload = { full_name, profile_photo_url: uploadedPhotoUrl, state, timezone }; 
    
    try {
        const response = await fetch(API_PROFILE_UPDATE, { 
            method: 'POST', 
            headers: { 'Content-Type': 'application/json' }, 
            body: JSON.stringify(payload) 
        });
            const result = await response.json();
            
            if(result.success) {
                showToast(result.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showToast(result.message, 'error');
            }
        } catch (error) { showToast('Error de red.', 'error'); }
    };
    
    const handleSecurityFormSubmit = async (e) => { 
        e.preventDefault();
        const formData = new FormData(securityForm);
        const object = {};
        formData.forEach((value, key) => object[key] = value);
        
        try {
            const response = await fetch(API_PASSWORD_UPDATE, { 
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(object) 
            });
            const result = await response.json();
            if (result.success) {
                showToast(result.message, 'success');
                securityForm.reset();
                setTimeout(() => location.reload(), 1500); 
            } else {
                showToast(result.message, 'error');
            }
        } catch (error) { showToast('Error de conexión.', 'error'); }      
    };
    
    const handleProfilePhotoUpload = async (event) => { 
        const file = event.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        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(API_PHOTO_UPLOAD, { method: 'POST', body: formData });
            const text = await response.text();
            
            try {
                const result = JSON.parse(text);
                if (result.success) {
                    showToast(result.message, 'success');
                    let finalPhotoUrl = sanitizeURL(result.photo_url);
                    if (finalPhotoUrl && !finalPhotoUrl.startsWith('http')) finalPhotoUrl = '/' + finalPhotoUrl.replace(/^\.\.\//g, '').replace(/^\//g, '');
                    uploadedPhotoUrl = finalPhotoUrl;
                    
                    setTimeout(() => location.reload(), 1500); 
                } else {
                    profilePhotoImg.src = uploadedPhotoUrl; 
                    showToast(result.message, 'error');
                }
            } catch (e) {
                console.error("Server Error:", text);
                showToast("Error al procesar la imagen.", 'error');
            }
        } catch (error) { 
            profilePhotoImg.src = uploadedPhotoUrl; 
            showToast('Error de subida.', 'error'); 
        }        
    };

    // INIT
    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 (userStateSelect) userStateSelect.addEventListener('change', handleStateChange);
        
        setupPasswordToggles();
        populateStateDropdown();
        loadAccountData(); 
    };

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