<?php
// ====================================================================
// 1. SEGURIDAD Y CONFIGURACIÓN INICIAL
// ====================================================================

if (!isset($branding) || !is_array($branding)) {
    $rutaInit = __DIR__ . '/core/init.php';
    if (file_exists($rutaInit)) {
        require_once($rutaInit);
    }
}

// LÓGICA DE CAMBIO DE IDIOMA
if (isset($_GET['lang_switch'])) {
    $new_lang = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['lang_switch']);
    $_SESSION['lang'] = $new_lang;
    $clean_url = strtok($_SERVER["REQUEST_URI"], '?');
    header("Location: " . $clean_url);
    exit;
}

// 2. Traer globales
global $branding, $client_info, $user_data;

// 3. Variables de seguridad
$logoUrl = $branding['flow-logo'] ?? 'img/logo.png'; 
$logoTitle = $branding['full_title'] ?? 'CRM';
$version = $branding['version'] ?? '2.0';
$crmName = $branding['crm_name'] ?? 'CRM';

// 4. Lógica de página
if (!isset($paginaActual)) {
    $paginaActual = pathinfo(basename($_SERVER['PHP_SELF']), PATHINFO_FILENAME);
}

// 5. Assets del menú
echo '<link rel="stylesheet" href="files/menu-styles.css">';
echo '<script src="files/menu-scripts.js" defer></script>';

// 6. Array de Categorías
$menuCategories = [
    // --- FASE 1: GESTIÓN DE CLIENTES ---
    'CLIENTS_MENU' => ['is_title' => true, 'label' => __('menu_phase_1_label')],
    'INICIO'       => ['icon' => 'layout-dashboard', 'link' => 'dashboard', 'text' => __('menu_dashboard'), 'module' => 'dashboard'],
    'ASISTENTE'    => ['icon' => 'handshake', 'link' => 'assistant', 'text' => __('menu_assistant'), 'module' => 'assistant'],
    'AGENDA'       => ['icon' => 'calendar-check', 'link' => 'agenda', 'text' => __('menu_agenda'), 'module' => 'agenda'],
    'CLIENTES'     => ['icon' => 'users', 'link' => 'clients', 'text' => __('menu_clients'), 'module' => 'clients'],
    'FACTURAS'     => ['icon' => 'wallet', 'link' => 'invoices', 'text' => __('menu_invoices'), 'module' => 'invoices'],
    'PROYECTOS'    => ['icon' => 'construction', 'link' => 'projects', 'text' => __('menu_projects'), 'module' => 'projects'],
    'RECURRENTES'  => ['icon' => 'shield-user', 'link' => 'recurring', 'text' => __('menu_recurring'), 'module' => 'recurring'],
    'RUTAS'        => ['icon' => 'git-compare-arrows', 'link' => 'routes', 'text' => __('menu_routes'), 'module' => 'routes'],

    // --- FASE 2: OPERACIÓN DEL NEGOCIO ---
    'BUSINESS_MENU' => ['is_title' => true, 'label' => __('menu_phase_2_label')],
    'SERVICIOS'     => ['icon' => 'briefcase-business', 'link' => 'services', 'text' => __('menu_services'), 'module' => 'services'],
    'FINANZAS'      => ['icon' => 'chart-no-axes-combined', 'link' => 'finances', 'text' => __('menu_finances'), 'module' => 'finances'],
    'EQUIPO'        => ['icon' => 'contact', 'link' => 'staff', 'text' => __('menu_staff'), 'module' => 'staff'],
    'RECLAMOS'      => ['icon' => 'triangle-alert', 'link' => 'complaints', 'text' => __('menu_complaints'), 'module' => 'complaints'],
    'RENDIMIENTO'   => ['icon' => 'chart-column-big', 'link' => 'performance', 'text' => __('menu_performance'), 'module' => 'performance'],

    // --- FASE 3: PROSPECTOS Y VENTAS ---
    'PROSPECTS_MENU' => ['is_title' => true, 'label' => __('menu_phase_3_label')],
    'PROSPECTOS'     => ['icon' => 'user-plus', 'link' => 'leads', 'text' => __('menu_leads'), 'module' => 'leads'],
    'FUNNEL_LEADS'   => ['icon' => 'shuffle', 'link' => 'lead-funnel', 'text' => __('menu_lead_funnel'), 'module' => 'lead_funnel'],
    'COTIZACIONES'   => ['icon' => 'file-text', 'link' => 'quotes', 'text' => __('menu_quotes'), 'module' => 'quotes'],
    'SEGUIMIENTO'    => ['icon' => 'combine', 'link' => 'quotes-funnel', 'text' => __('menu_quotes_funnel'), 'module' => 'quotes_funnel'],
    'DESCARTADOS'    => ['icon' => 'archive', 'link' => 'discarded-leads', 'text' => __('menu_discarded_leads'), 'module' => 'discarded_leads'],

    // --- HERRAMIENTAS Y RECURSOS ---
    'TOOLS_MENU'   => ['is_title' => true, 'label' => __('menu_tools_label')],
    'INFO_NEGOCIO' => ['icon' => 'building-2', 'link' => 'business-config', 'text' => __('menu_business_info'), 'module' => 'business_config'],
    'ADMINISTRACIÓN' => ['icon' => 'settings', 'link' => 'account', 'text' => __('menu_account'), 'module' => 'account'],
    'FORMACIÓN'    => ['icon' => 'tv-minimal-play', 'link' => 'academy', 'text' => __('menu_academy'), 'module' => 'academy'],
];
?>

<header class="md:hidden fixed top-0 inset-x-0 z-40 bg-[var(--color-primary)] border-b border-gray-900/20" style="padding-top: max(env(safe-area-inset-top), 10px);">
    <div class="h-14 flex items-center justify-between px-3 text-white">
        <button id="open-sidebar" type="button" aria-label="Abrir menú" class="p-3 -ml-2 rounded-md hover:bg-white/10"><i data-lucide="menu" class="w-7 h-7"></i></button>
        <div class="flex items-center gap-2"><img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="<?php echo htmlspecialchars($logoTitle); ?>" class="h-12 w-auto" onerror="this.style.display='none'"></div>
        <button id="open-help-top" type="button" aria-label="Abrir ayuda" class="bg-[var(--color-highlight)] text-black font-black p-1 -mr-2 rounded-md hover:bg-white"><i data-lucide="life-buoy" class="w-7 h-7"></i></button>
    </div>
    <div class="w-full h-[2px] bg-[var(--color-highlight)]"></div>
</header>

<div id="nav-overlay" class="md:hidden inset-0 bg-black/50 opacity-0 pointer-events-none transition-opacity duration-300 z-40"></div>

<aside id="sidebar" class="bg-[var(--color-primary)] text-white w-full md:w-72 fixed md:relative inset-0 md:inset-y-0 md:left-0 transform -translate-x-full md:translate-x-0 transition-transform duration-300 ease-in-out z-50 md:z-40 flex flex-col shadow-2xl md:rounded-r-xl overflow-y-auto">
    
    <?php include 'profile.php'; ?>
    
    <div class="md:hidden flex items-center justify-between px-7 py-3 border-b border-white/10 bg-[var(--color-primary)]" style="padding-top: max(env(safe-area-inset-top), 0px);">
        <div class="flex flex-col items-center justify-center gap-1">
            <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="<?php echo htmlspecialchars($logoTitle); ?>" class="h-18 w-auto object-contain">
            <div class="inline-flex items-center px-3 py-1 text-xs font-bold text-yellow-900 bg-[var(--color-background)] rounded-full border border-gray-200/50 shadow-sm">
                <span class="font-normal text-sm text-black flex items-center justify-center gap-1.5">
                    Versión <i data-lucide="shield-check" class="w-4 h-4 text-[var(--color-secondary)]"></i>
                    <span class="font-black text-black tracking-wide"><?php echo htmlspecialchars($version); ?>™ 2.1</span>
                </span>
            </div>
        </div>
        <button id="close-sidebar" type="button" aria-label="Cerrar Menú" class="p-2 rounded-md hover:bg-white/10">
            <i data-lucide="x" class="w-5 h-5 text-white"></i>
        </button>
    </div>

    <nav id="main-nav">
        <div class="hidden md:block text-center pt-5 pb-5 px-4 border-b border-white/10 sticky top-0 z-10 bg-[var(--color-primary)]">
            <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="<?php echo htmlspecialchars($logoTitle); ?>" class="h-12 w-auto mx-auto">
            <span class="inline-block mt-3 px-3 py-1 text-xs font-bold leading-none text-yellow-900 bg-[var(--color-background)] rounded-full">
                 <p class="font-normal text-sm text-black flex items-center justify-center gap-1.5">
                Versión <i data-lucide="shield-check" class="w-4 h-4 text-[var(--color-secondary)]"></i>
                <span class="font-black text-black tracking-wide"><?php echo htmlspecialchars($version); ?>™ 2.1</span>
            </p>
            </span>
        </div>

        <div class="px-4 py-4 border-b border-white/10 space-y-3">
            
            <div class="relative">
                <button type="button" id="platform-switcher-button" class="w-full flex items-center justify-between px-3 py-2.5 bg-white/5 rounded-lg hover:bg-white/10 transition-colors duration-150 focus:outline-none focus:ring-2 focus:ring-white/20">
                    <span class="flex items-center gap-3"><i data-lucide="gem" class="w-5 h-5 text-[var(--color-highlight)]"></i><span class="font-bold">Suite <?php echo htmlspecialchars($crmName); ?></span></span>
                    <i data-lucide="chevrons-up-down" class="w-4 h-4 text-white/70"></i>
                </button>
                <div id="platform-switcher-dropdown" class="platform-switcher-dropdown hidden absolute w-full bg-[var(--color-secondary)] rounded-lg shadow-xl overflow-hidden z-20 divide-y divide-white/10 mt-1">
                      <a href="/ia-marketing" class="flex items-start gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150"><i data-lucide="cpu" class="w-5 h-5 text-[var(--color-highlight)] flex-shrink-0 mt-1"></i><div><p class="font-bold leading-tight">IA Marketing Tools</p><p class="text-xs text-white/70">Herramientas De Marketing Con IA</p></div></a>
                      <a href="/adn-dashboard" class="flex items-start gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150"><i data-lucide="graduation-cap" class="w-5 h-5 text-[var(--color-highlight)] flex-shrink-0 mt-1"></i><div><p class="font-bold leading-tight">Programa ADN</p><p class="text-xs text-white/70">Acelerador De Negocios</p></div></a>
                      <a href="/stock-dashboard" class="flex items-start gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150"><i data-lucide="graduation-cap" class="w-5 h-5 text-[var(--color-highlight)] flex-shrink-0 mt-1"></i><div><p class="font-bold leading-tight">Recursos IAStock</p><p class="text-xs text-white/70">Recursos Creativos De Promoción</p></div></a>
                      <a href="/crm-store-dashboard" class="flex items-start gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150"><i data-lucide="graduation-cap" class="w-5 h-5 text-[var(--color-highlight)] flex-shrink-0 mt-1"></i><div><p class="font-bold leading-tight">De Todo En Publicidad</p><p class="text-xs text-white/70">Tienda Creativa En Línea</p></div></a>
                </div>
            </div>

            <div class="relative">
                <button type="button" onclick="document.getElementById('lang-dropdown').classList.toggle('hidden')" class="w-full flex items-center justify-between px-3 py-2.5 bg-white/5 rounded-lg hover:bg-white/10 transition-colors duration-150 focus:outline-none focus:ring-2 focus:ring-white/20">
                    <span class="flex items-center gap-3">
                        <i data-lucide="globe" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                        <span class="font-bold">
                            <?php echo ($_SESSION['lang'] ?? 'es') === 'main' ? 'English' : 'Español'; ?>
                        </span>
                    </span>
                    <i data-lucide="chevron-down" class="w-4 h-4 text-white/70"></i>
                </button>
                <div id="lang-dropdown" class="hidden absolute w-full bg-[var(--color-secondary)] rounded-lg shadow-xl overflow-hidden z-20 divide-y divide-white/10 mt-1">
                    <a href="?lang_switch=es" class="flex items-center gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150">
                        <span class="text-xl">🇪🇸</span>
                        <div class="font-bold">Español</div>
                    </a>
                    <a href="?lang_switch=main" class="flex items-center gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150">
                        <span class="text-xl">🇺🇸</span>
                        <div class="font-bold">English</div>
                    </a>
                </div>
            </div>

        </div>

        <div class="p-2 space-y-1">
            <?php foreach ($menuCategories as $key => $data): ?>
                
                <?php 
                if (isset($data['module']) && function_exists('is_module_active')) {
                    if (!is_module_active($data['module'])) {
                        continue; 
                    }
                }
                ?>

                <?php if (isset($data['is_title']) && $data['is_title']): ?>
                    <h3 class="text-xs font-bold uppercase text-[var(--color-highlight)] tracking-wider px-4 pt-3 pb-2">
                        <?php echo htmlspecialchars($data['label']); ?>
                    </h3>
                <?php else: 
                    $active = (htmlspecialchars($paginaActual) === $data['link']);
                    $classes = "flex items-center gap-3 px-4 py-2.5 rounded-lg text-[14px] transition-colors duration-150 hover:bg-[var(--color-secondary)] focus:outline-none focus:ring-2 focus:ring-white/20" . ($active ? " active-button" : "");
                ?>
                    <a href="/<?php echo $data['link']; ?>.php" class="<?php echo $classes; ?>">
                        <i data-lucide="<?php echo $data['icon']; ?>" class="w-5 h-5"></i>
                        <span class="uppercase font-bold"><?php echo htmlspecialchars($data['text']); ?></span>
                    </a>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>

        <div class="my-4 py-4 bg-black/20 border-y border-white/10">
            <div class="px-4">
                <div class="flex items-center gap-3 mb-3">
                    <i data-lucide="megaphone" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                    <h4 class="font-bold uppercase text-sm tracking-wider text-[var(--color-highlight)]">
                        <?php echo __('menu_boost_business'); ?>
                    </h4>
                </div>
                <?php @include 'ads.php'; ?>
            </div>
        </div>
        
        <div class="p-2 space-y-1">
            <button id="open-help" class="w-full flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-[var(--color-secondary)]" type="button">
                <i data-lucide="life-buoy" class="w-5 h-5"></i>
                <span class="uppercase font-bold text-[14px]"><?php echo __('menu_support'); ?></span>
            </button>
            <a href="/login.php?logout=true" class="w-full flex items-center gap-3 px-4 py-3 rounded-lg bg-red-700 hover:bg-red-800 text-white">
                <i data-lucide="log-out" class="w-5 h-5"></i>
                <span class="uppercase font-extrabold text-[14px]"><?php echo __('menu_logout'); ?></span>
            </a>
        </div>
        
        <div class="p-4 mt-auto border-t border-white/10">
            <?php @include 'brand/footer.php'; ?>
        </div>
    </nav>
</aside>

<div id="help-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 opacity-0 pointer-events-none transition-opacity duration-300" onclick="document.querySelector('[data-close-help]').click()"></div>
<aside id="help-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col" role="dialog" aria-modal="true" aria-labelledby="help-title">
    <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
        <h3 id="help-title" class="text-2xl font-black text-[var(--color-highlight)] flex items-center uppercase">
            <i data-lucide="life-buoy" class="w-8 h-8 mr-2 text-white"></i> <?php echo __('support_title'); ?>
        </h3>
        <button type="button" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200" data-close-help><i data-lucide="x" class="w-8 h-8"></i></button>
    </div>
    <div class="flex-grow overflow-y-auto p-3 relative">
        <div class="bg-white p-4 rounded-xl shadow-md transition duration-300">
            <div class="border-b pb-3 mb-4"><h4 class="text-2xl font-black text-[var(--color-secondary)] uppercase flex items-center"><i data-lucide="mail-question" class="w-5 h-5 mr-2"></i> <?php echo __('support_subtitle'); ?></h4></div>
            <form id="support-form" action="/support.php" method="POST" enctype="multipart/form-data" class="space-y-4">
                <div>
                    <label class="block text-md font-bold text-gray-600 mb-1 uppercase"><?php echo __('lbl_name'); ?></label>
                    <input type="text" name="name" value="<?php echo $userFullName ?? ''; ?>" class="w-full p-2 border border-gray-300 rounded-lg outline-none text-sm" required>
                </div>
                <div>
                    <label class="block text-md font-bold text-gray-600 mb-1 uppercase"><?php echo __('lbl_email'); ?></label>
                    <input type="email" name="email" value="<?php echo $userEmail ?? ''; ?>" class="w-full p-2 border border-gray-300 rounded-lg outline-none text-sm" required>
                </div>
                <div>
                    <label class="block text-md font-bold text-gray-600 mb-1 uppercase"><?php echo __('lbl_subject'); ?></label>
                    <select name="subject" class="w-full p-2 border border-gray-300 rounded-lg outline-none text-sm bg-white" required>
                        <option value="Soporte técnico"><?php echo __('support_opt_tech'); ?></option>
                        <option value="Facturación"><?php echo __('support_opt_billing'); ?></option>
                        <option value="Sugerencia"><?php echo __('support_opt_suggestion'); ?></option>
                        <option value="Otra consulta"><?php echo __('support_opt_other'); ?></option>
                    </select>
                </div>
                <div>
                    <label class="block text-md font-bold text-gray-600 mb-1 uppercase"><?php echo __('lbl_message'); ?></label>
                    <textarea name="message" rows="5" class="w-full p-2 border border-gray-300 rounded-lg outline-none text-sm" placeholder="<?php echo __('support_ph_message'); ?>" required></textarea>
                </div>
                <div>
                    <label class="block text-md font-bold text-gray-600 mb-1 uppercase"><?php echo __('lbl_attachment'); ?></label>
                    <input type="file" name="attachment" accept="image/*,.pdf" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-xs file:font-bold file:uppercase file:bg-[var(--color-primary)] file:text-white hover:file:bg-[var(--color-secondary)] cursor-pointer border border-gray-300 rounded-lg p-1">
                </div>
                <input type="hidden" name="current_page" value="<?php echo htmlspecialchars($paginaActual); ?>">
            </form>
        </div>
    </div>
    <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
        <div class="grid grid-cols-2 gap-3">
            <button type="button" class="w-full bg-[var(--color-secondary)] text-white font-bold py-2 rounded-lg uppercase flex items-center justify-center gap-2" data-close-help><i data-lucide="x-circle" class="w-5 h-5"></i> <?php echo __('btn_cancel'); ?></button>
            <button type="submit" form="support-form" class="w-full bg-[var(--color-primary)] text-white font-bold py-2 rounded-lg uppercase flex items-center justify-center gap-2"><i data-lucide="send" class="w-5 h-5"></i> <?php echo __('btn_send'); ?></button>
        </div>
    </div>
</aside>