<?php
require_once 'dompdf/autoload.inc.php'; 
use Dompdf\Dompdf;
use Dompdf\Options;

session_start();
include_once 'db/db_connection.php';
include_once 'db/business_info_functions.php'; 

if (!isset($_SESSION['user_id'])) {
    die('Acceso no autorizado.');
}

try {
    require 'db/performance-read-data.php'; 
    $performanceData = getPerformanceData($pdo, $_SESSION['user_id']); 
    
    $businessInfo = getBusinessInfo($pdo);

    if (empty($performanceData)) {
        die('No hay datos de rendimiento disponibles para generar el reporte.');
    }

} catch (Exception $e) {
    die('Error fatal al cargar los datos: ' . $e->getMessage());
}

$months = array_keys($performanceData);
$latestMonth = end($months);
$latestData = $performanceData[$latestMonth];

$html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Reporte de Rendimiento Mensual</title>
    <style>
        @page { margin: 100px 50px 50px 50px; }
        body { font-family: sans-serif; margin: 0; padding: 0; color: #333; }
        header { 
            position: fixed; top: -60px; left: 0px; right: 0px; 
            height: 50px; background-color: ' . $businessInfo['primary_color'] . '; 
            color: white; text-align: center; line-height: 40px; 
            border-bottom: 5px solid ' . $businessInfo['secondary_color'] . ';
        }
        .header-content { display: flex; justify-content: space-between; align-items: center; padding: 5px 20px; }
        .logo { max-width: 150px; height: auto; }
        h1 { font-size: 24px; color: ' . $businessInfo['secondary_color'] . '; margin-top: 10px; border-bottom: 2px solid #ccc; padding-bottom: 5px; }
        h2 { font-size: 18px; color: ' . $businessInfo['primary_color'] . '; margin-top: 20px; }
        .stats-grid { 
            display: flex; flex-wrap: wrap; justify-content: space-between; 
            margin-top: 20px; 
        }
        .stat-card { 
            width: 30%; background: #f4f4f4; border: 1px solid #ddd; 
            padding: 10px; margin-bottom: 15px; text-align: center; 
            border-left: 5px solid ' . $businessInfo['secondary_color'] . '; 
            display: inline-block; 
        }
        .stat-card p { margin: 0; }
        .stat-card .value { font-size: 30px; font-weight: bold; color: ' . $businessInfo['primary_color'] . '; }
        .stat-card .label { font-size: 12px; text-transform: uppercase; color: #666; }

        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { padding: 8px; border: 1px solid #ddd; text-align: left; font-size: 10px; }
        th { background-color: ' . $businessInfo['primary_color'] . '; color: white; text-transform: uppercase; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        .page_break { page-break-before: always; }
    </style>
</head>
<body>
    <header>
        <div style="float: left; padding-left: 10px; padding-top: 5px;">
            <img src="' . $businessInfo['logo_url'] . '" alt="Logo" class="logo" style="width: 40px; height: auto; display: block;">
        </div>
        <div style="text-align: right; padding-right: 10px; font-size: 14px; padding-top: 5px;">
            REPORTE DE RENDIMIENTO | ' . $businessInfo['company_name'] . '
        </div>
    </header>

    <main>
        <h1>REPORTE DE RENDIMIENTO EMPRESARIAL</h1>
        <p>Análisis Mensual General: **' . (isset($latestMonth) ? date('F Y', strtotime($latestMonth . '-01')) : 'Sin Datos') . '**</p>

        <h2>Resumen Del Mes Clave</h2>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="label">PROSPECTOS ADQUIRIDOS</div>
                <div class="value">' . ($latestData['leads'] ?? 0) . '</div>
            </div>
            <div class="stat-card">
                <div class="label">CLIENTES CONVERTIDOS</div>
                <div class="value">' . ($latestData['clientes'] ?? 0) . '</div>
            </div>
            <div class="stat-card">
                <div class="label">FACTURACIÓN MENSUAL</div>
                <div class="value">$' . number_format($latestData['facturacion'] ?? 0, 2) . '</div>
            </div>
        </div>

        <div class="stats-grid" style="margin-top: 5px;">
             <div class="stat-card">
                <div class="label">SERVICIOS VENDIDOS</div>
                <div class="value">' . ($latestData['serviciosVendidos'] ?? 0) . '</div>
            </div>
            <div class="stat-card">
                <div class="label">PROYECTOS COMPLETADOS</div>
                <div class="value">' . ($latestData['proyectosCompletados'] ?? 0) . '</div>
            </div>
            <div class="stat-card">
                <div class="label">CITAS NUEVAS + RECURRENTES</div>
                <div class="value">' . (($latestData['citasNuevas'] ?? 0) + ($latestData['citasRecurrentes'] ?? 0)) . '</div>
            </div>
        </div>
        
        <div class="page_break"></div>

        <h2>Desglose Histórico Por Mes</h2>
        <table>
            <thead>
                <tr>
                    <th>Mes</th>
                    <th>Leads</th>
                    <th>Clientes</th>
                    <th>Servicios</th>
                    <th>Proyectos</th>
                    <th>Facturación</th>
                    <th>Cotizaciones</th>
                    <th>Facturas Pagadas</th>
                </tr>
            </thead>
            <tbody>';

foreach ($performanceData as $monthKey => $data) {
    $monthName = date('M Y', strtotime($monthKey . '-01'));
    $formattedFacturacion = '$' . number_format($data['facturacion'], 2);

    $html .= '
                <tr>
                    <td>' . $monthName . '</td>
                    <td>' . $data['leads'] . '</td>
                    <td>' . $data['clientes'] . '</td>
                    <td>' . $data['serviciosVendidos'] . '</td>
                    <td>' . $data['proyectosCompletados'] . '</td>
                    <td>' . $formattedFacturacion . '</td>
                    <td>' . $data['cotizacionesGeneradas'] . '</td>
                    <td>' . $data['facturasPagadas'] . '</td>
                </tr>';
}

$html .= '
            </tbody>
        </table>
        
        <p style="text-align: center; margin-top: 50px; font-size: 10px;">Reporte Generado El ' . date('d/m/Y H:i:s') . ' Por FlowCRM™ De OrozDesign Powered By OrozCO</p>
    </main>
</body>
</html>';


$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'sans-serif');

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('letter', 'portrait');
$dompdf->render();

$filename = "Reporte_Rendimiento_" . date('Y_m_d') . ".pdf";
$dompdf->stream($filename, ["Attachment" => true]);
?>