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

// Valores por defecto (Fallback)
$company_logo_url = 'img/LogoPlaceholder.webp';
$company_name_from_db = 'FlowClean Cleaning LLC';
$primary_color_from_db = '#07162d'; 
$secondary_color_from_db = '#9e1428'; 
$contact_phone_from_db = 'N/A';

// Variables inyectadas para JavaScript (Valores por defecto iniciales)
$primary_color_js = json_encode($primary_color_from_db);
$secondary_color_js = json_encode($secondary_color_from_db);


try {
     $stmt_config = $pdo->prepare("SELECT logo_url, company_name, phone_primary, branding_color_primary, branding_color_secondary FROM business_info WHERE id = :id");
    $stmt_config->execute(['id' => 1]); // Ejecución obligatoria
    $config = $stmt_config->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        // Uso de operador de coalescencia nula (??) y sanitización (htmlspecialchars)
        $company_name_from_db = htmlspecialchars($config['company_name'] ?? $company_name_from_db);
        $contact_phone_from_db = htmlspecialchars($config['phone_primary'] ?? $contact_phone_from_db);
        $primary_color_from_db = htmlspecialchars($config['branding_color_primary'] ?? $primary_color_from_db);
        $secondary_color_from_db = htmlspecialchars($config['branding_color_secondary'] ?? $secondary_color_from_db);
        
        if (!empty($config['logo_url'])) {
            $company_logo_url = htmlspecialchars($config['logo_url']);
        }
        
        // **CAMBIO**: Actualizar variables JS con los valores de la DB si existen
        $primary_color_js = json_encode($primary_color_from_db);
        $secondary_color_js = json_encode($secondary_color_from_db);
    }
} catch (PDOException $e) {
    error_log("Error PDO al cargar business_info para PDF: " . $e->getMessage());
} catch (Exception $e) {
    error_log("Error general al cargar business_info para PDF: " . $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 Rendimiento Del Negocio <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
    <style>
        @media (max-width: 767px) {
            .responsive-table-stack tbody,
            .responsive-table-stack tr,
            .responsive-table-stack td {
                display: block;
                width: 100%;
            }

            .responsive-table-stack thead {
                display: none; 
            }

            .responsive-table-stack tr {
                margin-bottom: 1rem; 
                border: 1px solid #e2e8f0;
                border-radius: 0.5rem;
                padding: 0.5rem;
                background-color: white;
                box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
            }

            .responsive-table-stack td {
                text-align: right !important; 
                padding-left: 50% !important; 
                position: relative;
                border-bottom: 1px solid #edf2f7;
                padding-top: 0.75rem;
                padding-bottom: 0.75rem;
                white-space: normal; 
                word-break: break-word; 
            }

            .responsive-table-stack td:last-child {
                border-bottom: 0; 
            }

            .responsive-table-stack td::before {
                content: attr(data-label); 
                position: absolute;
                left: 0.75rem;
                width: calc(50% - 1.5rem);
                padding-right: 1rem;
                white-space: nowrap;
                text-align: left;
                font-weight: bold;
                text-transform: uppercase;
                color: #4a5568;
                flex-shrink: 0;
            }

            .responsive-table-stack td.actions-cell {
                text-align: center !important;
                padding-left: 0 !important;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                gap: 0.75rem; 
                min-height: 48px; 
                flex-wrap: wrap; 
            }

            .responsive-table-stack td.actions-cell::before {
                content: none; 
            }

            .responsive-table-stack td.actions-cell button {
                width: 100%; 
                flex-grow: 0;
                min-width: 80px;
            }
        }
    </style>
</head>
<body data-page-title="Panel De Rendimiento Del Negocio"
      data-page-subtitle="Consulta Y Analiza Las Métricas Clave De Tu Actividad Comercial"
      data-page-icon="chart-column-big">
    
    <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 '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="rendimiento" class="dashboard-section">
                <div id="business-info-pdf-header" class="w-full mb-8 p-4 border-b-2 border-gray-200">
    <div class="flex justify-between items-center">
        <img src="<?php echo $company_logo_url; ?>" alt="Logo Del Negocio" 
             class="h-16 w-auto object-contain">
        
        <div class="text-right">
            <h1 class="text-3xl font-black text-[var(--color-secondary)] uppercase"><?php echo $company_name_from_db; ?></h1>
            <p class="text-lg text-gray-600 font-black">Reporte De Rendimiento Empresarial</p>
            <p class="text-md text-gray-500">Teléfono: <?php echo $contact_phone_from_db; ?></p>
        </div>
    </div>
</div>
                <div class="mb-6">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                        <div>
                            <h3 class="text-4xl font-black text-[var(--color-primary)] flex items-center gap-2">
                                <i data-lucide="bar-chart-2" class="w-7 h-7 text-[var(--color-primary)]"></i> RESUMEN GENERAL DE RENDIMIENTO
                            </h3>
                            <p class="font-black text-gray-500 text-sm mt-1 uppercase">ANÁLISIS GLOBAL DE LAS MÉTRICAS DE TU NEGOCIO</p>
                        </div>
                        
                        <div class="flex items-center gap-3">
                            <label for="month-select" class="text-gray-600 font-black uppercase">Seleccionar Mes:</label>
                            <select id="month-select" class="p-2 border border-gray-300 rounded-md focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)]">
                            </select>
                            <button id="download-pdf-btn" onclick="generatePerformancePDF()" class="btn-primary py-2 px-4 rounded-lg flex items-center justify-center w-full md:w-auto uppercase" style="min-width: 150px;">
                                <i data-lucide="download" class="w-5 h-5 mr-2"></i> Descargar PDF
                            </button>
                        </div>
                        </div>
                </div>

  <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-6 mt-8">
    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="user-plus" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">PROSPECTOS ADQUIRIDOS</h3>
            <p id="stat-leads" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
            </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="users" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">CLIENTES CONVERTIDOS</h3>
            <p id="stat-clientes" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="package" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">SERVICIOS VENDIDOS</h3>
            <p id="stat-servicios" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="wallet" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">FACTURACIÓN MENSUAL</h3>
            <p id="stat-facturacion" class="text-5xl font-bold text-[var(--color-primary)]">$0</p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="file-text" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">COTIZACIONES GENERADAS</h3>
            <p id="stat-cotizaciones" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="receipt" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">FACTURAS PAGADAS</h3>
            <p id="stat-facturas" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="calendar-plus" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">CITAS NUEVAS</h3>
            <p id="stat-citas-nuevas" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="repeat" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">CITAS RECURRENTES</h3>
            <p id="stat-citas-recurrentes" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>
    
    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
        <i data-lucide="folder-check" class="w-12 h-12 text-[var(--color-secondary)]"></i>
        <div>
            <h3 class="text-lg font-black text-gray-500 mb-1">PROYECTOS COMPLETADOS</h3>
            <p id="stat-proyectos-completados" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>
</div>

                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mt-8">
                    
                                            <div class="bg-white p-6 rounded-xl shadow-md col-span-1 flex flex-col">
                        <h3 class="kpi-header text-2xl font-black text-gray-800 mb-4 flex items-center gap-2">Eficiencia Comercial y Conversión</h3>
                        <div class="flex-1 flex flex-col justify-center">
                            <div class="flex justify-between items-center mb-6">
                                <div class="text-center">
                                    <p id="visual-leads" class="text-4xl font-black text-[var(--color-primary)]">0</p>
                                    <p class="text-xs text-gray-500 mt-1">Prospectos (Leads)</p>
                                </div>
                                <i data-lucide="arrow-big-right-dash" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                                <div class="text-center">
                                    <p id="visual-clientes" class="text-4xl font-black text-[var(--color-secondary)]">0</p>
                                    <p class="text-xs text-gray-500 mt-1">Nuevos Clientes</p>
                                </div>
                            </div>
                            
                            <div class="mt-4">
                                <p class="text-lg font-black uppercase text-gray-500">Tasa de Conversión</p>
                                <div class="flex items-end gap-2 mb-2">
                                    <span id="conversion-rate-text" class="text-5xl font-black text-[var(--color-primary)]">0%</span>
                                    <span class="text-sm text-gray-500 mb-2 font-medium">de efectividad</span>
                                </div>
                                <div class="w-full bg-gray-100 rounded-full h-3 overflow-hidden">
                                    <div id="conversion-bar" class="bg-[var(--color-secondary)] h-3 rounded-full transition-all duration-1000" style="width: 0%"></div>
                                </div>
                            </div>

                            <div class="mt-8 pt-6 border-t border-gray-100 flex justify-between items-center">
                                <span class="text-lg font-black uppercase text-gray-500">Servicios Vendidos:</span>
                                <span id="visual-servicios" class="font-bold text-gray-800">0</span>
                            </div>
                        </div>
                    </div>

                                            <div class="bg-white p-6 rounded-xl shadow-md col-span-1 flex flex-col">
                        <h3 class="kpi-header text-2xl font-black text-gray-800 mb-4 flex items-center gap-2">Tendencia Citas (Nuevas vs Recurrentes)</h3>
                                                <div class="relative flex-1 h-full w-full" style="min-height: 250px;">
                            <canvas id="citasMixChart" class="h-full w-full"></canvas> 
                        </div>
                    </div>

                                            <div class="bg-white p-6 rounded-xl shadow-md col-span-1 flex flex-col">
                        <h3 class="kpi-header text-2xl font-black text-gray-800 mb-4 flex items-center gap-2">Tendencia de Facturación (6 Meses)</h3>
                                                <div class="relative flex-1 h-full w-full" style="min-height: 250px;">
                            <canvas id="revenueTrendChart" class="h-full w-full"></canvas>
                        </div>
                    </div>
                </div>

                                <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                    <h3 class="text-3xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                        <i data-lucide="list-checks" class="w-6 h-6 text-[var(--color-secondary)]"></i> DESGLOSE DE RENDIMIENTO POR MES
                    </h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white responsive-table-stack">
                            <thead>
                                <tr class="bg-gray-100 text-gray-600 uppercase text-xs leading-normal">
                                    <th class="py-3 px-6 text-left">Mes</th>
                                    <th class="py-3 px-6 text-left">Leads</th>
                                    <th class="py-3 px-6 text-left">Clientes</th>
                                    <th class="py-3 px-6 text-left">Servicios</th>
                                    <th class="py-3 px-6 text-left">Proyectos</th>
                                    <th class="py-3 px-6 text-left">Facturación</th>
                                    <th class="py-3 px-6 text-left">Cotizaciones</th>
                                    <th class="py-3 px-6 text-left">Facturas</th>
                                    <th class="py-3 px-6 text-left">Citas Nuevas</th>
                                    <th class="py-3 px-6 text-left">Citas Recurrentes</th>
                                </tr>
                            </thead>
                            <tbody id="performance-table-body" class="text-gray-600 text-xs font-light">
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<script>
// =================================================================
// ESTADO Y CONSTANTES DE LA APLICACIÓN
// =================================================================
const BRANDING_COLORS = {
    primary: <?php echo $primary_color_js; ?>,
    secondary: <?php echo $secondary_color_js; ?>
};

let APP_STATE = {
    rendimientoMensual: {},
    chartInstances: {
        // Corregido: Usamos nombres descriptivos para las instancias
        revenueTrend: null,
        leadsClients: null,
        citas: null
    }
};

const CONSTANTS = {
    MONTH_NAMES: {
        '01': 'Ene', '02': 'Feb', '03': 'Mar', '04': 'Abr', '05': 'May', '06': 'Jun',
        '07': 'Jul', '08': 'Ago', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dic'
    },
    MONTH_NAMES_LONG: {
        '01': 'Enero', '02': 'Febrero', '03': 'Marzo', '04': 'Abril', '05': 'Mayo', '06': 'Junio',
        '07': 'Julio', '08': 'Agosto', '09': 'Septiembre', '10': 'Octubre', '11': 'Noviembre', '12': 'Diciembre'
    },
    CSS_COLORS: {}
};


// =================================================================
// CACHÉ DE ELEMENTOS DEL DOM (IDs corregidos/mapeados)
// =================================================================
const UI = {
    mobileMenuButton: document.getElementById('mobile-menu-button'),
    sidebar: document.getElementById('sidebar'),
    sidebarOverlay: document.getElementById('sidebar-overlay'),
    monthSelect: document.getElementById('month-select'),
    statLeads: document.getElementById('stat-leads'),
    statClientes: document.getElementById('stat-clientes'),
    statServicios: document.getElementById('stat-servicios'),
    statFacturacion: document.getElementById('stat-facturacion'),
    statCotizaciones: document.getElementById('stat-cotizaciones'),
    statFacturas: document.getElementById('stat-facturas'),
    statCitasNuevas: document.getElementById('stat-citas-nuevas'),
    statCitasRecurrentes: document.getElementById('stat-citas-recurrentes'),
    statProyectosCompletados: document.getElementById('stat-proyectos-completados'),
    performanceTableBody: document.getElementById('performance-table-body'),
    // NUEVOS IDs CORREGIDOS y mapeados a los canvas existentes
    citasMixChartCtx: document.getElementById('citasMixChart')?.getContext('2d'),
    revenueTrendChartCtx: document.getElementById('revenueTrendChart')?.getContext('2d'),
    // Elementos visuales del primer card
    visualLeads: document.getElementById('visual-leads'),
    visualClientes: document.getElementById('visual-clientes'),
    visualServicios: document.getElementById('visual-servicios'),
    conversionRateText: document.getElementById('conversion-rate-text'),
    conversionBar: document.getElementById('conversion-bar'),

    tableDesgloseContainer: document.querySelector('#content-area .dashboard-section > .bg-white.p-6.rounded-xl.shadow-md.mt-8'),
    downloadPdfBtn: document.getElementById('download-pdf-btn'), 
    contentArea: document.getElementById('content-area')
};


// =================================================================
// FUNCIONES DE UTILIDAD
// =================================================================
const getCssVar = (name) => {
    try {
        const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
        if (!value) throw new Error(`Variable CSS '${name}' no definida.`);
        return value;
    } catch (e) {
        console.warn(e.message);
        const fallbacks = {
            '--color-primary': BRANDING_COLORS.primary || '#07162d',
            '--color-secondary': BRANDING_COLORS.secondary || '#9e1428',
            '--color-highlight': '#ffc857',
            '--color-success': '#10B981',
            '--color-warning': '#F59E0B'
        };
        return fallbacks[name] || '#CCCCCC';
    }
};

const sortMonthKeys = (dataObject) => {
    return Object.keys(dataObject).sort((a, b) => new Date(a) - new Date(b));
};


// =================================================================
// FUNCIONES DE RENDERIZADO DE LA UI
// =================================================================
function populateMonthSelect(sortedMonths) {
    UI.monthSelect.innerHTML = '';
    if (sortedMonths.length === 0) {
        UI.monthSelect.innerHTML = `<option value="">NO HAY DATOS</option>`;
        UI.monthSelect.disabled = true;
        return;
    }

    UI.monthSelect.disabled = false;
    sortedMonths.forEach(monthKey => {
        const [year, monthNum] = monthKey.split('-');
        const option = new Option(`${CONSTANTS.MONTH_NAMES[monthNum].toUpperCase()} ${year}`, monthKey);
        UI.monthSelect.add(option);
    });

    const today = new Date();
    const currentYearMonth = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`;
    UI.monthSelect.value = APP_STATE.rendimientoMensual[currentYearMonth] ? currentYearMonth : sortedMonths[sortedMonths.length - 1];
}

function updateConversionMetrics(leads, clients, services) {
    const conversionRate = leads > 0 ? (clients / leads) * 100 : 0;
    const roundedRate = Math.min(conversionRate, 100).toFixed(1); // Máximo 100%

    UI.visualLeads.textContent = leads.toLocaleString('es-ES');
    UI.visualClientes.textContent = clients.toLocaleString('es-ES');
    UI.visualServicios.textContent = services.toLocaleString('es-ES');
    UI.conversionRateText.textContent = `${roundedRate}%`;
    UI.conversionBar.style.width = `${roundedRate}%`;
}


function updateStatCards(monthKey) {
    const data = APP_STATE.rendimientoMensual[monthKey] || {};
    const formatCurrency = (num) => `$${(num || 0).toLocaleString('es-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
    
    const leads = data.leads || 0;
    const clients = data.clientes || 0;
    const services = data.serviciosVendidos || 0;

    UI.statLeads.textContent = leads;
    UI.statClientes.textContent = clients;
    UI.statServicios.textContent = services;
    UI.statFacturacion.textContent = formatCurrency(data.facturacion);
    UI.statCotizaciones.textContent = data.cotizacionesGeneradas || 0;
    UI.statFacturas.textContent = data.facturasPagadas || 0;
    UI.statCitasNuevas.textContent = data.citasNuevas || 0;
    UI.statCitasRecurrentes.textContent = data.citasRecurrentes || 0;
    UI.statProyectosCompletados.textContent = data.proyectosCompletados || 0;
    
    // Actualizar métricas de conversión
    updateConversionMetrics(leads, clients, services);

    if (typeof lucide !== 'undefined') lucide.createIcons();
}

function renderPerformanceTable(sortedMonths) {
    UI.performanceTableBody.innerHTML = '';
    if (sortedMonths.length === 0) {
        UI.performanceTableBody.innerHTML = `<tr><td colspan="10" class="py-3 px-6 text-center text-gray-500">No hay datos de rendimiento.</td></tr>`;
        return;
    }

    const fragment = document.createDocumentFragment();
    sortedMonths.forEach(monthKey => {
        const data = APP_STATE.rendimientoMensual[monthKey];
        const [year, monthNum] = monthKey.split('-');
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-200 hover:bg-gray-50';
        const formattedFacturacion = data.facturacion > 0 ? `$${data.facturacion.toLocaleString('es-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : '$0';
        row.innerHTML = `
            <td class="py-3 px-6 text-left whitespace-nowrap font-medium" data-label="MES">${CONSTANTS.MONTH_NAMES_LONG[monthNum]} ${year}</td>
            <td class="py-3 px-6 text-left" data-label="LEADS">${data.leads || 0}</td>
            <td class="py-3 px-6 text-left" data-label="CLIENTES">${data.clientes || 0}</td>
            <td class="py-3 px-6 text-left" data-label="SERVICIOS">${data.serviciosVendidos || 0}</td>
            <td class="py-3 px-6 text-left" data-label="PROYECTOS">${data.proyectosCompletados || 0}</td>
            <td class="py-3 px-6 text-left" data-label="FACTURACIÓN">${formattedFacturacion}</td>
            <td class="py-3 px-6 text-left" data-label="COTIZACIONES">${data.cotizacionesGeneradas || 0}</td>
            <td class="py-3 px-6 text-left" data-label="FACTURAS">${data.facturasPagadas || 0}</td>
            <td class="py-3 px-6 text-left" data-label="CITAS NUEVAS">${data.citasNuevas || 0}</td>
            <td class="py-3 px-6 text-left" data-label="CITAS RECURRENTES">${data.citasRecurrentes || 0}</td>
        `;
        fragment.appendChild(row);
    });
    UI.performanceTableBody.appendChild(fragment);
}


// =================================================================
// RENDERIZADO DE GRÁFICOS (IMPLEMENTADAS)
// =================================================================

// FUNCIÓN DE EJEMPLO para Facturación y Servicios (usando el canvas de tendencia)
function renderFacturacionServiciosChart(labels, facturacionData, serviciosData) {
    if (APP_STATE.chartInstances.revenueTrend) {
        APP_STATE.chartInstances.revenueTrend.destroy();
    }
    
    const ctx = UI.revenueTrendChartCtx; 
    if (!ctx) return;

    APP_STATE.chartInstances.revenueTrend = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Facturación ($)',
                data: facturacionData,
                backgroundColor: CONSTANTS.CSS_COLORS.primary + 'AA', // Primary semitransparente
                borderColor: CONSTANTS.CSS_COLORS.primary,
                yAxisID: 'yFacturacion',
                type: 'bar'
            }, {
                label: 'Servicios Vendidos (Unidades)',
                data: serviciosData,
                borderColor: CONSTANTS.CSS_COLORS.secondary,
                backgroundColor: CONSTANTS.CSS_COLORS.secondary,
                fill: false,
                yAxisID: 'yServicios',
                type: 'line'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false,
            },
            plugins: {
                legend: { position: 'top' },
                tooltip: { callbacks: { label: (context) => {
                    let label = context.dataset.label || '';
                    if (label) { label += ': '; }
                    if (context.dataset.yAxisID === 'yFacturacion') {
                        label += `$${context.parsed.y.toLocaleString('es-US')}`;
                    } else {
                        label += context.parsed.y.toLocaleString('es-ES');
                    }
                    return label;
                }}}
            },
            scales: {
                yFacturacion: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    title: { display: true, text: 'Facturación ($)' }
                },
                yServicios: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    grid: { drawOnChartArea: false },
                    title: { display: true, text: 'Servicios (Unidades)' },
                    min: 0
                }
            }
        }
    });
}

// FUNCIÓN DE EJEMPLO para Leads y Clientes (Añadida al final si quieres otro canvas, o combinada con la de Conversión)
// Mantenemos esta función vacía ya que solo tienes 2 canvas de gráfica.
function renderLeadsClientsChart(labels, leadsData, clientsData) {
    // Para simplificar, esta funcionalidad se ve reflejada en el card de "Eficiencia Comercial y Conversión".
    // Si deseas agregar un tercer canvas con ID 'leadsClientsChart', deberás agregarlo al HTML.
    // console.log('Gráfica Leads/Clientes no renderizada, métricas visibles en el card de Conversión.');
}

// FUNCIÓN IMPLEMENTADA para Tendencia Citas (usando citasMixChart)
function renderCitasChart(labels, citasNuevasData, citasRecurrentesData) {
    if (APP_STATE.chartInstances.citas) {
        APP_STATE.chartInstances.citas.destroy();
    }
    
    const ctx = UI.citasMixChartCtx; // ID Corregido: citasMixChart
    if (!ctx) return;

    APP_STATE.chartInstances.citas = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'Citas Nuevas',
                data: citasNuevasData,
                backgroundColor: CONSTANTS.CSS_COLORS.primary,
                borderColor: CONSTANTS.CSS_COLORS.primary,
                stack: 'stackCitas'
            }, {
                label: 'Citas Recurrentes',
                data: citasRecurrentesData,
                backgroundColor: CONSTANTS.CSS_COLORS.secondary,
                borderColor: CONSTANTS.CSS_COLORS.secondary,
                stack: 'stackCitas'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: { display: false }
            },
            scales: {
                x: { stacked: true },
                y: { stacked: true, beginAtZero: true }
            }
        }
    });
}


// =================================================================
// FUNCIÓN PARA DESCARGAR PDF (USANDO jspdf y html2canvas)
// =================================================================
const generatePerformancePDF = () => {
    showToast('Generando Reporte. Esto Puede Tomar Unos Segundos...', 'info');
    
    // El área principal de contenido a capturar
    const reportElement = UI.contentArea; 
    
    // Elementos a ocultar (controles de la web)
    const controlsContainer = reportElement.querySelector('.flex.items-center.gap-3');
    // CAMBIO: Obtener la referencia al contenedor de la tabla
    const tableSection = UI.tableDesgloseContainer;
    
    // Ocultamos elementos para la captura de pantalla
    if (controlsContainer) controlsContainer.style.display = 'none';
    if (tableSection) tableSection.style.display = 'none'; 

    // **[INICIO DEL CAMBIO CRUCIAL PARA GRÁFICAS]**
    // 1. Aumentar temporalmente el ancho del área principal para evitar recortes en gráficas.
    const originalWidth = reportElement.style.width;
    const originalPadding = reportElement.style.padding;
    reportElement.style.width = '1200px'; // Un ancho mayor asegura que las gráficas no se recorten.
    reportElement.style.padding = '30px'; 
    // **[FIN DEL CAMBIO CRUCIAL PARA GRÁFICAS]**

    // Asegurarse de que el jsPDF esté disponible
    if (window.jspdf) { window.jsPDF = window.jspdf.jsPDF; }
    
    // Generación del PDF
    html2canvas(reportElement, { 
        scale: 2, 
        useCORS: true,
        backgroundColor: '#ffffff'
    }).then(canvas => {
        // **[RESTAURAR ESTILOS - ES IMPORTANTE]**
        // Restaurar estilos al original después de la captura
        reportElement.style.width = originalWidth;
        reportElement.style.padding = originalPadding;
        if (controlsContainer) controlsContainer.style.display = 'flex';
        if (tableSection) tableSection.style.display = ''; 
        // **[FIN RESTAURAR ESTILOS]**

        const imgData = canvas.toDataURL('image/jpeg', 0.9);
        const pdf = new jsPDF({ 
            orientation: 'portrait', 
            unit: 'mm', 
            format: 'a4' 
        });
        
        // Se mantiene la lógica de paginación para reportes largos
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = pdf.internal.pageSize.getHeight();
        const imgHeight = (canvas.height * pdfWidth) / canvas.width;
        
        let heightLeft = imgHeight;
        let position = 0;

        // Primer página
        pdf.addImage(imgData, 'JPEG', 0, position, pdfWidth, imgHeight);
        heightLeft -= pdfHeight;

        // Páginas restantes si es necesario
        while (heightLeft >= 0) {
            position = heightLeft - imgHeight;
            pdf.addPage();
            pdf.addImage(imgData, 'JPEG', 0, position, pdfWidth, imgHeight);
            heightLeft -= pdfHeight;
        }

        const date = new Date().toLocaleDateString('es-ES').replace(/\//g, '_');
        pdf.save(`FlowCRM-ReporteRendimiento_${date}.pdf`);
        showToast('Reporte Descargado.', 'success');

    }).catch(err => {
        // **[RESTAURAR ESTILOS EN CASO DE ERROR - ES IMPORTANTE]**
        // Restaurar en caso de error
        reportElement.style.width = originalWidth;
        reportElement.style.padding = originalPadding;
        if (controlsContainer) controlsContainer.style.display = 'flex';
        if (tableSection) tableSection.style.display = ''; 
        console.error("Error al generar PDF:", err);
        showToast('Error al generar el PDF. Revisa la consola para más detalles.', 'error');
    });
};

// =================================================================
// LÓGICA PRINCIPAL Y MANEJO DE EVENTOS
// =================================================================
async function initDashboard() {
    // Cargar colores CSS
    CONSTANTS.CSS_COLORS.primary = BRANDING_COLORS.primary;
    CONSTANTS.CSS_COLORS.secondary = BRANDING_COLORS.secondary;
    CONSTANTS.CSS_COLORS.highlight = getCssVar('--color-highlight'); 
    
    // Cargar y procesar datos de rendimiento
    try {
        // Asegúrate de que este archivo exista y devuelva JSON con la estructura correcta
        const response = await fetch(`db/performance-read.php?t=${new Date().getTime()}`);
        const result = await response.json();
        if (result.success && result.data) {
            APP_STATE.rendimientoMensual = result.data;
        } else {
            showToast(result.message || 'Error al cargar datos de rendimiento.', 'error');
        }
    } catch (error) {
        showToast('Error de conexión al cargar datos de rendimiento.', 'error');
        console.error('Error de conexión:', error);
    }

    // Procesar datos para UI
    const sortedMonths = sortMonthKeys(APP_STATE.rendimientoMensual);
    const chartLabels = sortedMonths.map(key => {
        const [year, monthNum] = key.split('-');
        return new Date(year, monthNum - 1, 1).toLocaleDateString('es-ES', { month: 'short', year: '2-digit' });
    });

    // Extraer datos para las gráficas
    const facturacionData = sortedMonths.map(m => APP_STATE.rendimientoMensual[m].facturacion);
    const serviciosData = sortedMonths.map(m => APP_STATE.rendimientoMensual[m].serviciosVendidos);
    const leadsData = sortedMonths.map(m => APP_STATE.rendimientoMensual[m].leads);
    const clientsData = sortedMonths.map(m => APP_STATE.rendimientoMensual[m].clientes);
    const citasNuevasData = sortedMonths.map(m => APP_STATE.rendimientoMensual[m].citasNuevas);
    const citasRecurrentesData = sortedMonths.map(m => APP_STATE.rendimientoMensual[m].citasRecurrentes);

    // Renderizar UI
    populateMonthSelect(sortedMonths);
    // La llamada a updateStatCards también actualiza la Tasa de Conversión (updateConversionMetrics)
    updateStatCards(UI.monthSelect.value); 
    renderPerformanceTable(sortedMonths);

    // **********************************************
    // INICIALIZACIÓN DE GRÁFICAS CORREGIDA
    // **********************************************
    renderFacturacionServiciosChart(chartLabels, facturacionData, serviciosData); // Usa #revenueTrendChart
    renderLeadsClientsChart(chartLabels, leadsData, clientsData); // Función stub/sin implementación visual
    renderCitasChart(chartLabels, citasNuevasData, citasRecurrentesData); // Usa #citasMixChart
    // **********************************************


    // Configurar Event Listeners
    UI.monthSelect.addEventListener('change', (e) => {
        updateStatCards(e.target.value);
    });
    
    UI.mobileMenuButton.addEventListener('click', () => {
        UI.sidebar.classList.toggle('-translate-x-full');
        UI.sidebarOverlay.classList.toggle('hidden');
    });
    UI.sidebarOverlay.addEventListener('click', () => {
        UI.sidebar.classList.add('-translate-x-full');
        UI.sidebarOverlay.classList.add('hidden');
    });

    // Manejar notificaciones de la URL
    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);
    }
}

// Iniciar la aplicación cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', initDashboard);
</script>
<script src="files/toast.js"></script>
</body>
</html>