<?php include 'files/guardiankey.php'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit Dashboard | Mi Cuenta | OrozDesign Multiemdia</title>
    <meta name="description" content="Administra tu cuenta en LocalCRM: actualiza tus datos personales, contraseña y preferencias de forma segura y sencilla">
    <meta name="robots" content="noindex, nofollow">

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

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <script src="files/header-manager.js"></script>

    <link rel="stylesheet" href="style.css">
</head>
<body data-page-title="CONFIGURACIÓN DE LA CUENTA" 
      data-page-subtitle="ADMINISTRA TU PERFIL, SUSCRIPCIÓN Y SEGURIDAD." 
      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">
            <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>
                            <button id="change-photo-button" class="w-full btn-primary font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase text-sm">
                                <i data-lucide="upload" class="w-4 h-4 mr-2"></i> CAMBIAR FOTO
                            </button>
                        </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="target" class="w-6 h-6 text-[var(--color-primary)]"></i> META MENSUAL
                            </h3>
                            <div class="space-y-4">
                                <div>
                                    <label for="monthly-billing-goal" class="block text-gray-700 text-sm font-bold mb-2 uppercase">META DE FACTURACIÓN ($)</label>
                                    <input type="number" step="0.01" id="monthly-billing-goal" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="5000.00">
                                </div>
                                <button id="save-goal-button" class="w-full btn-primary font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase text-sm">
                                    <i data-lucide="save" class="w-4 h-4 mr-2"></i> GUARDAR META
                                </button>
                            </div>
                        </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 PERSONAL
                            </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" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                </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" 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="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>
                                    <input type="password" id="current-password" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                </div>
                                <div>
                                    <label for="new-password" class="block text-gray-700 text-sm font-bold mb-2 uppercase">NUEVA CONTRASEÑA</label>
                                    <input type="password" id="new-password" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                </div>
                                <div>
                                    <label for="confirm-password" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CONFIRMAR NUEVA CONTRASEÑA</label>
                                    <input type="password" id="confirm-password" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                </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>
                </div>
            </section>
        </div>
    </main>
</div>

<script>
    // Variable global para almacenar los datos del perfil del administrador
    let currentAdminProfile = null; // Renombrado de currentUserProfile a currentAdminProfile
    let uploadedPhotoUrl = null; // Para almacenar la URL de la foto recién subida

    document.addEventListener('DOMContentLoaded', function() {
        // --- TOAST NOTIFICATION INITIALIZATION ---
        const urlParams = new URLSearchParams(window.location.search);
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');

        if (notificationType && notificationMessage) {
            if (typeof showToast === 'function') {
                showToast(notificationMessage, notificationType);
            } else {
                console.error("showToast function is not defined globally. Check header-manager.js.");
            }
        }

        // --- ELEMENTOS DEL DOM ---
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebar-overlay');
        
        const profilePhotoUpload = document.getElementById('profile-photo-upload');
        const profilePhotoImg = document.getElementById('profile-photo-preview');
        const changePhotoButton = document.getElementById('change-photo-button');

        const monthlyBillingGoalInput = document.getElementById('monthly-billing-goal');
        const saveGoalButton = document.getElementById('save-goal-button');

        const personalInfoForm = document.getElementById('personal-info-form');
        const userFullNameInput = document.getElementById('user-full-name');
        const userEmailInput = document.getElementById('user-email');

        const securityForm = document.getElementById('security-form');
        const currentPasswordInput = document.getElementById('current-password');
        const newPasswordInput = document.getElementById('new-password');
        const confirmPasswordInput = document.getElementById('confirm-password');

        // --- FUNCIONES ---
        function toggleSidebar() {
            if (sidebar) sidebar.classList.toggle('-translate-x-full');
            if (sidebarOverlay) sidebarOverlay.classList.toggle('hidden');
        }

        const fetchAdminProfile = async () => { // Renombrado de fetchUserProfile a fetchAdminProfile
            try {
                const response = await fetch('db/user-profile-read.php?' + new Date().getTime());
                const result = await response.json();

                if (result.success && result.data) {
                    currentAdminProfile = result.data;

                    if (userFullNameInput) userFullNameInput.value = currentAdminProfile.full_name || '';
                    if (userEmailInput) userEmailInput.value = currentAdminProfile.email || '';
                    if (profilePhotoImg) {
                        profilePhotoImg.src = currentAdminProfile.profile_photo_url || "https://placehold.co/128x128/cccccc/333333?text=U";
                    }
                    uploadedPhotoUrl = currentAdminProfile.profile_photo_url;

                    if (monthlyBillingGoalInput) {
                        monthlyBillingGoalInput.value = currentAdminProfile.monthly_billing_goal !== undefined ? parseFloat(currentAdminProfile.monthly_billing_goal).toFixed(2) : '5000.00';
                    }

                } else {
                    showToast(result.message || 'Error al cargar la información del perfil del administrador.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al cargar la información del perfil del administrador.', 'error');
            }
        };

        // Manejo de la subida de foto de perfil (al seleccionar un archivo)
        if (profilePhotoUpload) {
            profilePhotoUpload.addEventListener('change', async function(event) {
                const file = event.target.files[0];
                if (!file) return;

                if (profilePhotoImg) profilePhotoImg.src = URL.createObjectURL(file);

                const formData = new FormData();
                formData.append('profile_photo', file);

                try {
                    if (changePhotoButton) {
                        changePhotoButton.disabled = true;
                        changePhotoButton.innerHTML = '<i data-lucide="loader" class="w-4 h-4 mr-2 animate-spin"></i> Subiendo...';
                        lucide.createIcons();
                    }

                    const response = await fetch('db/upload-profile-photo.php', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();

                    if (result.success) {
                        uploadedPhotoUrl = result.file_url;
                        if (profilePhotoImg) profilePhotoImg.src = uploadedPhotoUrl;
                        showToast('Foto subida con éxito. Haz clic en "GUARDAR CAMBIOS" para confirmar los cambios de perfil.', 'info');
                        fetchAdminProfile();
                    } else {
                        showToast(result.message || 'Error al subir foto.', 'error');
                        if (profilePhotoImg && currentAdminProfile) {
                            profilePhotoImg.src = currentAdminProfile.profile_photo_url || "https://placehold.co/128x128/cccccc/333333?text=U";
                        }
                        uploadedPhotoUrl = currentAdminProfile ? currentAdminProfile.profile_photo_url : null;
                    }
                } catch (error) {
                    showToast('Error de conexión al subir la foto.', 'error');
                    if (profilePhotoImg && currentAdminProfile) {
                        profilePhotoImg.src = currentAdminProfile.profile_photo_url || "https://placehold.co/128x128/cccccc/333333?text=U";
                    }
                    uploadedPhotoUrl = currentAdminProfile ? currentAdminProfile.profile_photo_url : null;
                } finally {
                    if (changePhotoButton) {
                        changePhotoButton.disabled = false;
                        changePhotoButton.innerHTML = '<i data-lucide="upload" class="w-4 h-4 mr-2"></i> CAMBIAR FOTO';
                        lucide.createIcons();
                    }
                }
            });
        }

        if (changePhotoButton) {
            changePhotoButton.addEventListener('click', (e) => {
                e.preventDefault();
                profilePhotoUpload.click();
            });
        }

        const updatePersonalInfo = async (fullName, photoUrl) => {
            if (!currentAdminProfile) {
                showToast('Error: No se ha cargado el perfil del administrador.', 'error');
                return;
            }
            if (fullName.trim() === '') {
                showToast('El nombre completo es obligatorio.', 'warning');
                return;
            }

            try {
                const response = await fetch('db/user-profile-update.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        full_name: fullName,
                        profile_photo_url: photoUrl
                    })
                });
                const result = await response.json();

                if (result.success) {
                    showToast(result.message, 'success');
                    fetchAdminProfile();
                } else {
                    showToast(result.message || 'Error al actualizar información personal.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al actualizar información personal.', 'error');
            }
        };

        const updateMonthlyGoal = async (goalAmount) => {
            if (isNaN(goalAmount) || goalAmount < 0) {
                showToast('Por favor, ingresa una cantidad válida para la meta.', 'warning');
                return;
            }

            try {
                const response = await fetch('db/user-monthly-goal-update.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        monthly_billing_goal: goalAmount
                    })
                });
                const result = await response.json();

                if (result.success) {
                    showToast(result.message, 'success');
                    fetchAdminProfile();
                } else {
                    showToast(result.message || 'Error al actualizar la meta mensual.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al actualizar la meta mensual.', 'error');
            }
        };

        if (personalInfoForm) {
            personalInfoForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                await updatePersonalInfo(userFullNameInput.value.trim(), uploadedPhotoUrl || (currentAdminProfile ? currentAdminProfile.profile_photo_url : null));
            });
        }

        if (saveGoalButton) {
            saveGoalButton.addEventListener('click', async (e) => {
                e.preventDefault();
                const goal = parseFloat(monthlyBillingGoalInput.value);
                await updateMonthlyGoal(goal);
            });
        }

        if (securityForm) {
            securityForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const currentPassword = currentPasswordInput.value;
                const newPassword = newPasswordInput.value;
                const confirmPassword = confirmPasswordInput.value;

                if (newPassword !== confirmPassword) {
                    showToast('La nueva contraseña y su confirmación no coinciden.', 'warning');
                    return;
                }
                if (newPassword.length < 6) {
                    showToast('La nueva contraseña debe tener al menos 6 caracteres.', 'warning');
                    return;
                }

                try {
                    const response = await fetch('db/user-password-update.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            current_password: currentPassword,
                            new_password: newPassword
                        })
                    });
                    const result = await response.json();

                    if (result.success) {
                        showToast(result.message, 'success');
                        currentPasswordInput.value = '';
                        newPasswordInput.value = '';
                        confirmPasswordInput.value = '';
                    } else {
                        showToast(result.message || 'Error al actualizar contraseña.', 'error');
                    }
                } catch (error) {
                    showToast('Error de conexión al actualizar contraseña.', 'error');
                }
            });
        }

        if (mobileMenuButton) {
            mobileMenuButton.addEventListener('click', toggleSidebar);
        }
        if (sidebarOverlay) {
            sidebarOverlay.addEventListener('click', toggleSidebar);
        }
        
        // Simulación de gestión de pagos (mantengo el elemento HTML en account.php, pero lo comento en JS si ya no es relevante)
        // const managePaymentButton = document.getElementById('manage-payment-button'); // No está definido en el HTML actual, si lo vuelves a añadir, descomenta esta línea.
        // if (managePaymentButton) {
        //     managePaymentButton.addEventListener('click', (e) => {
        //         e.preventDefault();
        //         showToast('Redireccionando a portal de pagos (requiere integración real).', 'info');
        //     });
        // }

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