<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

include_once 'db/db_connection.php';

$user_id = $_SESSION['user_id'] ?? null;
$user_profile = null;
$db_config = ['company_name' => '', 'contact_name' => '', 'phone_primary' => '', 'phone_secondary' => '', 'email' => '', 'website_url' => ''];
$db_logo = ['logo_url' => 'https://placehold.co/150x150/e2e8f0/333333?text=Logo'];
$db_error_message = null;

if ($user_id) {
    try {
        $stmt_user = $pdo->prepare("SELECT full_name, email, profile_photo_url, plan_version, plan_renewal_date, next_invoice_date FROM users WHERE user_id = ?");
        $stmt_user->execute([$user_id]);
        $user_profile = $stmt_user->fetch(PDO::FETCH_ASSOC);

        $stmt_config = $pdo->query("SELECT company_name, contact_name, phone_primary, phone_secondary, email, website_url FROM website_config WHERE id = 1 LIMIT 1");
        $db_config = $stmt_config->fetch(PDO::FETCH_ASSOC);

        $stmt_logo = $pdo->query("SELECT logo_url FROM website_logo WHERE website_config_id = 1 LIMIT 1");
        $db_logo = $stmt_logo->fetch(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        $db_error_message = 'Error al cargar los datos de la base de datos: ' . $e->getMessage();
        error_log($db_error_message);
    }
}

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>FlowCRM™ Tu Centro De Control Empresarial Powered By OrozCO</title>
  <meta name="description" content="La Plataforma Todo En Uno Para Impulsar Tu Negocio">
  <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="style.css"> 
    <script src="files/header-manager.js"></script>
    
    <style>
        .custom-file-input { width: 100%; }
        .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; }

        /* Estilos para el botón de mostrar/ocultar contraseña */
        .toggle-password-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 2rem;
            height: 2rem;
            /* Color del ícono. Un color oscuro para que contraste con el fondo claro del input. */
            color: #4b5563; 
        }

        /* Estilo al pasar el ratón por encima, para dar feedback visual */
        .toggle-password-btn:hover {
            opacity: 0.85;
        }
    </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>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'cms-menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

            <div id="content-area" class="p-4 md:p-8 space-y-8">
                <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-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="<?php echo htmlspecialchars($user_profile['profile_photo_url'] ?? '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-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" class="w-full p-3 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                            <button type="button"
                                                    class="toggle-password-btn absolute top-1/2 right-3 -translate-y-1/2 text-gray-400"
                                                    data-target="current-password"
                                                    aria-label="Mostrar u ocultar contraseña">
                                                <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" class="w-full p-3 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                            <button type="button"
                                                    class="toggle-password-btn absolute top-1/2 right-3 -translate-y-1/2 text-gray-400"
                                                    data-target="new-password"
                                                    aria-label="Mostrar u ocultar contraseña">
                                                <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" class="w-full p-3 pr-12 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                            <button type="button"
                                                    class="toggle-password-btn absolute top-1/2 right-3 -translate-y-1/2 text-gray-400"
                                                    data-target="confirm-password"
                                                    aria-label="Mostrar u ocultar contraseña">
                                                <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 flex items-center justify-center gap-2">
                                            <i data-lucide="lock" class="w-4 h-4"></i> ACTUALIZAR CONTRASEÑA
                                        </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-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)]" value="<?php echo htmlspecialchars($user_profile['full_name'] ?? ''); ?>">
                                    </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 value="<?php echo htmlspecialchars($user_profile['email'] ?? ''); ?>">
                                    </div>
                                    <div class="pt-4 text-right">
                                        <button type="submit" class="btn-primary font-bold py-2 px-6 rounded-lg uppercase flex items-center justify-center gap-2">
                                            <i data-lucide="save" class="w-4 h-4"></i> 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="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-green-600 bg-green-100 py-1 px-3 rounded-full uppercase"><?php echo htmlspecialchars($user_profile['plan_version'] ?? 'N/A'); ?></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"><?php echo htmlspecialchars($user_profile['plan_renewal_date'] ? date('d/m/Y', strtotime($user_profile['plan_renewal_date'])) : 'N/A'); ?></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"><?php echo htmlspecialchars($user_profile['next_invoice_date'] ? date('d/m/Y', strtotime($user_profile['next_invoice_date'])) : 'N/A'); ?></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>
                </section>
            </div>
        </main>
    </div>

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

    // =================================================================
    // VARIABLES Y CACHÉ DE ELEMENTOS DEL DOM
    // =================================================================
    let currentUserProfile = null;
    let uploadedPhotoUrl = "<?php echo htmlspecialchars($user_profile['profile_photo_url'] ?? 'https://placehold.co/128x128/cccccc/333333?text=U'); ?>";
    let logoFile = null;
    let logoUrl = "<?php echo htmlspecialchars($db_logo['logo_url'] ?? 'https://placehold.co/150x150/e2e8f0/333333?text=Logo'); ?>";

    // 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 planVersionSpan = document.getElementById('plan-version');
    const planRenewalDateSpan = document.getElementById('plan-renewal-date');
    const nextInvoiceDateSpan = document.getElementById('next-invoice-date');
    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');
    const phonePrimaryInput = document.getElementById('phone-primary');
    const phoneSecondaryInput = document.getElementById('phone-secondary');
    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 updateLogoButton = document.getElementById('update-logo-button');

    // =================================================================
    // UTILIDADES
    // =================================================================
    const showToast = (message, type = 'info') => {
        const toastContainer = document.getElementById('toast-container');
        if (!toastContainer) return;

        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        toast.textContent = message;
        toastContainer.appendChild(toast);

        setTimeout(() => {
            toast.classList.add('toast-fade-out');
            toast.addEventListener('animationend', () => toast.remove(), { once: true });
        }, 4000);
    };

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

// ====== TOGGLE PASSWORD (Lucide seguro, sin perder listeners) ======
function setupPasswordToggles() {
    const buttons = document.querySelectorAll('.toggle-password-btn');

    buttons.forEach(btn => {
        const iconSpan = btn.querySelector('.icon');
        const targetId = btn.getAttribute('data-target');
        const input = document.getElementById(targetId);

        if (!input || !iconSpan) return;

        // Limpiar cualquier contenido previo y crear el ícono inicial (ojo)
        iconSpan.innerHTML = '';
        const initialIcon = document.createElement('i');
        initialIcon.setAttribute('data-lucide', 'eye');
        initialIcon.className = 'w-5 h-5 pointer-events-none';
        iconSpan.appendChild(initialIcon);
        lucide.createIcons(); // Vuelve a renderizar los íconos Lucide

        // Evento de clic para alternar
        btn.addEventListener('click', () => {
            const isHidden = input.type === 'password';
            input.type = isHidden ? 'text' : 'password';

            // Alternar el ícono
            const newIconName = isHidden ? 'eye-off' : 'eye';
            iconSpan.innerHTML = ''; // Limpiar el ícono anterior
            const newIcon = document.createElement('i');
            newIcon.setAttribute('data-lucide', newIconName);
            newIcon.className = 'w-5 h-5 pointer-events-none';
            iconSpan.appendChild(newIcon);
            lucide.createIcons(); // Vuelve a renderizar el ícono actualizado

            // Accesibilidad
            btn.setAttribute('aria-pressed', String(isHidden));
            btn.setAttribute('title', isHidden ? 'Ocultar contraseña' : 'Mostrar contraseña');
        });
    });
}

    // =================================================================
    // LÓGICA DE LA CUENTA DE USUARIO Y CONFIGURACIÓN WEB
    // =================================================================
    const updatePersonalInfo = async (fullName, photoUrl) => {
        if (!fullName) {
            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();
            showToast(result.message, result.success ? 'success' : 'error');
            if (result.success) { location.reload(); }
        } catch (error) {
            showToast('Error de conexión al guardar los cambios.', 'error');
        }
    };

    const handleSecurityFormSubmit = async (e) => {
        e.preventDefault();
        if (newPasswordInput.value !== confirmPasswordInput.value) {
            showToast('La nueva contraseña y su confirmación no coinciden.', 'warning');
            return;
        }
        try {
            const response = await fetch('db/user-password-update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    current_password: currentPasswordInput.value,
                    new_password: newPasswordInput.value
                })
            });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
            if (result.success) { location.reload(); }
        } catch (error) {
            showToast('Error de conexión al cambiar la contraseña.', 'error');
        }
    };

    const handleProfilePhotoUpload = async (event) => {
        const file = event.target.files[0];
        if (!file) return;
        const formData = new FormData();
        formData.append('profile_photo', file);
        try {
            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. Presiona "GUARDAR CAMBIOS" para confirmar.', 'info');
            } else {
                showToast(result.message || 'Error al subir la foto.', 'error');
            }
        } catch (error) {
            showToast('Error de conexión al subir la foto.', 'error');
        }
    };

    const handleCompanyInfoSubmit = async (e) => {
        e.preventDefault();
        const formData = new FormData(companyInfoForm);
        const data = Object.fromEntries(formData.entries());

        try {
            const response = await fetch('db/website-config-update.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
        } catch (error) {
            showToast('Error de conexión al guardar la información del negocio.', 'error');
        }
    };

    const handleLogoUpload = async () => {
        if (!logoFile) {
            showToast('Selecciona un archivo de logotipo.', 'warning');
            return;
        }
        const formData = new FormData();
        formData.append('logo', logoFile);

        try {
            const response = await fetch('db/website-logo-update.php', { method: 'POST', body: formData });
            const result = await response.json();
            showToast(result.message, result.success ? 'success' : 'error');
            if (result.success) {
                logoUrl = result.logo_url;
                logoPreview.src = logoUrl;
                logoFile = null;
                logoFileNameDisplay.textContent = "Ningún archivo seleccionado";
                updateLogoButton.classList.add('disabled-button');
            }
        } catch (error) {
            showToast('Error de conexión al subir el logotipo.', 'error');
        }
    };

    // =================================================================
    // INICIALIZACIÓN DE EVENTOS
    // =================================================================
    const init = () => {
        if (mobileMenuButton) mobileMenuButton.addEventListener('click', toggleSidebar);
        if (sidebarOverlay) sidebarOverlay.addEventListener('click', toggleSidebar);

        if (personalInfoForm) {
            personalInfoForm.addEventListener('submit', (e) => {
                e.preventDefault();
                const newName = userFullNameInput.value.trim();
                const photoToSave = uploadedPhotoUrl || "<?php echo htmlspecialchars($user_profile['profile_photo_url'] ?? ''); ?>";
                updatePersonalInfo(newName, photoToSave);
            });
        }

        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();
                    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');
                }
            });
        }

        // Formateo telefónico
        if (phonePrimaryInput) { IMask(phonePrimaryInput, { mask: '(000) 000-0000' }); }
        if (phoneSecondaryInput) { IMask(phoneSecondaryInput, { mask: '(000) 000-0000' }); }

        // Set up del toggle de contraseñas (nuevo, sin usar <i data-lucide> directos)
        setupPasswordToggles();

        // Notificaciones por querystring
        const urlParams = new URLSearchParams(window.location.search);
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');
        if (notificationType && notificationMessage && typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        }
    };

    init();

    // Pintar el resto de iconos Lucide basados en <i data-lucide="...">
    lucide.createIcons();
});


</script>
</body>
</html>