<?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';

// Variables para el Branding
$company_logo_url = 'img/placeholder-logo.png';
$company_name_from_db = 'FlowClean Cleaning LLC';
$primary_color_from_db = '#07162d'; 
$secondary_color_from_db = '#9e1428'; 
$contact_phone_from_db = 'N/A';

try {
    // Consulta para obtener el logo, colores y nombre de la tabla business_info
    $stmt_config = $pdo->query("SELECT logo_url, company_name, phone_primary, branding_color_primary, branding_color_secondary FROM business_info WHERE id = 1");
    $config = $stmt_config->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        $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']);
        }
    }
} catch (PDOException $e) {
    error_log("Error PDO al cargar business_info para PDF: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Rendimiento Empresarial FlowCRM™ De OrozDesign Powered By OrozCO</title>
  <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">

    <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>
    <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>
        /* Agregamos las reglas CSS para tablas responsivas que ya hemos usado */
        @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; /* Oculta el encabezado de la tabla original */
            }

            .responsive-table-stack tr {
                margin-bottom: 1rem; /* Espacio entre las "tarjetas" de fila */
                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; /* Alinea el valor a la derecha */
                padding-left: 50% !important; /* Deja espacio para la etiqueta */
                position: relative;
                border-bottom: 1px solid #edf2f7; /* Separador entre campos */
                padding-top: 0.75rem;
                padding-bottom: 0.75rem;
                white-space: normal; /* Permite que el texto se ajuste */
                word-break: break-word; /* Rompe palabras largas */
            }

            .responsive-table-stack td:last-child {
                border-bottom: 0; /* No hay borde inferior en el último campo */
            }

            /* Etiqueta del campo (header) */
            .responsive-table-stack td::before {
                content: attr(data-label); /* Usa el atributo data-label como contenido */
                position: absolute;
                left: 0.75rem;
                width: calc(50% - 1.5rem); /* Ocupa la mitad izquierda */
                padding-right: 1rem;
                white-space: nowrap; /* Evita que la etiqueta se rompa */
                text-align: left;
                font-weight: bold;
                text-transform: uppercase;
                color: #4a5568;
                flex-shrink: 0;
            }

            /* Ajustes para celdas de acciones/botones (si se aplican) */
            .responsive-table-stack td.actions-cell {
                text-align: center !important;
                padding-left: 0 !important;
                display: flex;
                flex-direction: column; /* Apila los botones verticalmente */
                justify-content: center;
                align-items: center;
                gap: 0.75rem; /* Espacio entre botones */
                min-height: 48px; /* Altura mínima para la fila de botones */
                flex-wrap: wrap; /* Permite que los botones se envuelvan si hay muchos */
            }

            .responsive-table-stack td.actions-cell::before {
                content: none; /* No mostrar etiqueta para celdas de acciones */
            }

            .responsive-table-stack td.actions-cell button {
                width: 100%; /* Toma todo el ancho disponible */
                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-2xl font-extrabold text-gray-800 flex items-center gap-2">
                                <i data-lucide="bar-chart-2" class="w-7 h-7 text-[var(--color-primary)]"></i> VISTA GENERAL DE RENDIMIENTO
                            </h3>
                            <p class="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-semibold">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-primary)]">
        <i data-lucide="user-plus" class="w-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">PROSPECTOS ADQUIRIDOS</h3>
            <p id="stat-leads" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-secondary)]">
        <i data-lucide="users" class="w-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">CLIENTES CONVERTIDOS</h3>
            <p id="stat-clientes" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">SERVICIOS VENDIDOS</h3>
            <p id="stat-servicios" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">FACTURACIÓN MENSUAL</h3>
            <p id="stat-facturacion" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">$0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-primary)]">
        <i data-lucide="file-text" class="w-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">COTIZACIONES GENERADAS</h3>
            <p id="stat-cotizaciones" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-secondary)]">
        <i data-lucide="receipt" class="w-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">FACTURAS PAGADAS</h3>
            <p id="stat-facturas" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">CITAS NUEVAS</h3>
            <p id="stat-citas-nuevas" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-secondary)]">
        <i data-lucide="repeat" class="w-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">CITAS RECURRENTES</h3>
            <p id="stat-citas-recurrentes" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</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-purple-500">
        <i data-lucide="folder-check" class="w-10 h-10 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">PROYECTOS COMPLETADOS</h3>
            <p id="stat-proyectos-completados" class="text-5xl font-bold text-[var(--color-secondary)] uppercase">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">En el mes</p>
        </div>
    </div>
</div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-8">
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                            <i data-lucide="trending-up" class="w-6 h-6 text-[var(--color-secondary)]"></i> FACTURACIÓN Y SERVICIOS (MENSUAL)
                        </h3>
                        <div class="h-80">
                            <canvas id="facturacionServiciosChart"></canvas>
                        </div>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                            <i data-lucide="pie-chart" class="w-6 h-6 text-[var(--color-secondary)]"></i> PROSPECTOS VS. CLIENTES CONVERTIDOS (MENSUAL)
                        </h3>
                        <div class="h-80">
                            <canvas id="leadsClientsChart"></canvas>
                        </div>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md lg:col-span-2">
                        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                            <i data-lucide="calendar" class="w-6 h-6 text-[var(--color-secondary)]"></i> CITAS NUEVAS VS. RECURRENTES (MENSUAL)
                        </h3>
                        <div class="h-80">
                            <canvas id="citasChart"></canvas>
                        </div>
                    </div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                    <h3 class="text-xl 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
// =================================================================
let APP_STATE = {
    rendimientoMensual: {},
    chartInstances: {
        facturacionServicios: 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
// =================================================================
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'),
    facturacionServiciosChartCtx: document.getElementById('facturacionServiciosChart')?.getContext('2d'),
    leadsClientsChartCtx: document.getElementById('leadsClientsChart')?.getContext('2d'),
    citasChartCtx: document.getElementById('citasChart')?.getContext('2d'),
    // NUEVO: Botón de descarga para ocultar/mostrar durante la generación
    downloadPdfBtn: document.getElementById('download-pdf-btn'), 
    contentArea: document.getElementById('content-area') // Área a convertir en PDF
};


// =================================================================
// 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': '#07162d',
            '--color-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 updateStatCards(monthKey) {
    const data = APP_STATE.rendimientoMensual[monthKey] || {};
    const formatCurrency = (num) => `$${(num || 0).toLocaleString('es-US')}`;

    UI.statLeads.textContent = data.leads || 0;
    UI.statClientes.textContent = data.clientes || 0;
    UI.statServicios.textContent = data.serviciosVendidos || 0;
    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;


    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
// =================================================================
function renderFacturacionServiciosChart(labels, facturacionData, serviciosData) {
    if (!UI.facturacionServiciosChartCtx) return;
    if (APP_STATE.chartInstances.facturacionServicios) APP_STATE.chartInstances.facturacionServicios.destroy();

    APP_STATE.chartInstances.facturacionServicios = new Chart(UI.facturacionServiciosChartCtx, {
        type: 'line',
        data: {
            labels,
            datasets: [{
                label: 'Facturación',
                data: facturacionData,
                borderColor: CONSTANTS.CSS_COLORS.primary,
                backgroundColor: CONSTANTS.CSS_COLORS.primary + '20',
                fill: true,
                tension: 0.3
            }, {
                label: 'Servicios Vendidos',
                data: serviciosData,
                borderColor: CONSTANTS.CSS_COLORS.secondary,
                backgroundColor: CONSTANTS.CSS_COLORS.secondary + '20',
                fill: true,
                tension: 0.3,
                yAxisID: 'y1'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { mode: 'index', intersect: false },
            scales: {
                y: { beginAtZero: true, position: 'left', ticks: { callback: value => `$${value.toLocaleString('es-US')}` }},
                y1: { beginAtZero: true, position: 'right', grid: { drawOnChartArea: false } }
            },
            plugins: { legend: { position: 'top' } }
        }
    });
}

function renderLeadsClientsChart(labels, leadsData, clientsData) {
    if (!UI.leadsClientsChartCtx) return;
    if (APP_STATE.chartInstances.leadsClients) APP_STATE.chartInstances.leadsClients.destroy();

    APP_STATE.chartInstances.leadsClients = new Chart(UI.leadsClientsChartCtx, {
        type: 'bar',
        data: {
            labels,
            datasets: [{
                label: 'Leads',
                data: leadsData,
                backgroundColor: CONSTANTS.CSS_COLORS.primary,
                borderRadius: 5
            }, {
                label: 'Clientes Convertidos',
                data: clientsData,
                backgroundColor: CONSTANTS.CSS_COLORS.secondary,
                borderRadius: 5
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: { y: { beginAtZero: true } },
            plugins: { legend: { position: 'top' } }
        }
    });
}

function renderCitasChart(labels, citasNuevasData, citasRecurrentesData) {
    if (!UI.citasChartCtx) return;
    if (APP_STATE.chartInstances.citas) APP_STATE.chartInstances.citas.destroy();

    APP_STATE.chartInstances.citas = new Chart(UI.citasChartCtx, {
        type: 'bar',
        data: {
            labels,
            datasets: [{
                label: 'Citas Nuevas',
                data: citasNuevasData,
                backgroundColor: CONSTANTS.CSS_COLORS.highlight,
                borderRadius: 5
            }, {
                label: 'Citas Recurrentes',
                data: citasRecurrentesData,
                backgroundColor: CONSTANTS.CSS_COLORS.secondary,
                borderRadius: 5
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: { y: { beginAtZero: true, stacked: false } },
            plugins: { legend: { position: 'top' } }
        }
    });
}


// =================================================================
// 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.flex-col.md\\:flex-row.justify-between.items-start.md\\:items-center.gap-4 .flex.items-center.gap-3');
    
    // Ocultamos elementos para la captura de pantalla
    if (controlsContainer) controlsContainer.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';
        // **[FIN RESTAURAR ESTILOS]**

        const imgData = canvas.toDataURL('image/jpeg', 0.9);
        const pdf = new jsPDF({ 
            orientation: 'portrait', 
            unit: 'mm', 
            format: 'a4' 
        });
        
        // ... (El resto de la lógica de jspdf se mantiene igual)

        // 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';

        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 = getCssVar('--color-primary');
    CONSTANTS.CSS_COLORS.secondary = getCssVar('--color-secondary');
    CONSTANTS.CSS_COLORS.highlight = getCssVar('--color-highlight');
    
    // Cargar y procesar datos de rendimiento
    try {
        // NOTA: Usamos 'db/performance-read.php' (el archivo que corregimos antes)
        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' });
    });

    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);
    const proyectosCompletadosData = sortedMonths.map(m => APP_STATE.rendimientoMensual[m].proyectosCompletados);


    // Renderizar UI
    populateMonthSelect(sortedMonths);
    updateStatCards(UI.monthSelect.value);
    renderPerformanceTable(sortedMonths);
    renderFacturacionServiciosChart(chartLabels, facturacionData, serviciosData);
    renderLeadsClientsChart(chartLabels, leadsData, clientsData);
    renderCitasChart(chartLabels, citasNuevasData, citasRecurrentesData);

    // 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>
</body>
</html>