<?php
// --- Auth gate: PDF standalone, sin sesión no se sirve ---
if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
if (empty($_SESSION['user_id'])) { header('Location: index.php?view=login'); exit; }
// --- end auth gate ---
// evaluation-billing-pdf.php - Reporte PDF del resumen de pagos
include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/UserData.php';
// === User signature for footer (clinicademo) ===
if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
$clinicademo_sig_user_id = $_SESSION['user_id'] ?? null;
$clinicademo_sig_user_name = 'Sistema';
if ($clinicademo_sig_user_id) {
    $_u = UserData::getById($clinicademo_sig_user_id);
    if ($_u) {
        $_n = trim(($_u->name ?? '') . ' ' . ($_u->lastname ?? ''));
        if ($_n !== '') {
            $clinicademo_sig_user_name = $_n;
        } elseif (!empty($_u->username)) {
            $clinicademo_sig_user_name = $_u->username;
        }
    }
}
$clinicademo_sig_footer = 'Generado por: ' . $clinicademo_sig_user_name . ' | ' . date('d/m/Y H:i:s');


$con = Database::getCon();

$doctorId = isset($_GET['doctor_id']) ? intval($_GET['doctor_id']) : 0;
$status = $_GET['status'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';

$where = [];
$params = [];
$types = '';

if ($doctorId > 0) {
    $where[] = 'se.professional_id = ?';
    $params[] = $doctorId;
    $types .= 'i';
}
if ($status === 'particular' || $status === 'facturado') {
    $where[] = 'eb.status = ?';
    $params[] = $status;
    $types .= 's';
}
if ($dateFrom) {
    $where[] = 'DATE(se.evaluation_date) >= ?';
    $params[] = $dateFrom;
    $types .= 's';
}
if ($dateTo) {
    $where[] = 'DATE(se.evaluation_date) <= ?';
    $params[] = $dateTo;
    $types .= 's';
}

$whereSql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT
        se.professional_id AS doctor_id,
        CONCAT(u.name, ' ', u.lastname) AS doctor_name,
        c.name AS specialty_name,
        COUNT(*) AS item_count,
        COUNT(DISTINCT se.id) AS eval_count,
        COALESCE(SUM(CASE WHEN eb.status = 'particular' THEN eb.total_price ELSE 0 END), 0) AS total_particular,
        COALESCE(SUM(CASE WHEN eb.status = 'facturado' THEN eb.total_price ELSE 0 END), 0) AS total_facturado,
        COALESCE(SUM(eb.total_price), 0) AS total_general
    FROM evaluation_billing eb
    INNER JOIN specialty_evaluation se ON eb.evaluation_id = se.id
    LEFT JOIN user u ON se.professional_id = u.id
    LEFT JOIN category c ON se.specialty_id = c.id
    $whereSql
    GROUP BY se.professional_id, c.name
    ORDER BY doctor_name, specialty_name
";

$stmt = $con->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

require_once 'tcpdf/tcpdf.php';

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Reporte de Pagos de Evaluaciones');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(15, 15, 15);
$pdf->SetAutoPageBreak(TRUE, 20);
$pdf->SetFont('helvetica', '', 9);
$pdf->AddPage();
$pdf->Image('assets/images/logo/logo.png', 15, 8, 30, 15, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

// Header
$pdf->SetFont('helvetica', 'B', 16);
$pdf->SetTextColor(102, 126, 234);
$pdf->Cell(0, 8, 'REPORTE DE PAGOS DE EVALUACIONES', 0, 1, 'C');
$pdf->SetFont('helvetica', '', 9);
$pdf->SetTextColor(100, 100, 100);
$pdf->Cell(0, 5, 'Generado por: ' . $clinicademo_sig_user_name . ' | ' . date('d/m/Y H:i:s'), 0, 1, 'C');
$pdf->Ln(3);

// Filtros aplicados
$filtersTxt = 'Filtros: ';
if ($doctorId > 0) {
    $doctor = $con->query("SELECT CONCAT(name, ' ', lastname) AS n FROM user WHERE id = $doctorId")->fetch_object();
    $filtersTxt .= 'Doctor=' . ($doctor->n ?? '?') . ' | ';
}
$filtersTxt .= 'Estado=' . ($status ?: 'Todos') . ' | ';
if ($dateFrom) $filtersTxt .= 'Desde=' . $dateFrom . ' | ';
if ($dateTo) $filtersTxt .= 'Hasta=' . $dateTo . ' | ';
$filtersTxt = rtrim($filtersTxt, ' | ');
$pdf->SetFont('helvetica', 'I', 8);
$pdf->Cell(0, 4, $filtersTxt, 0, 1, 'L');
$pdf->Ln(3);

// Tabla header
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(50, 50, 50);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(45, 7, 'Doctor', 1, 0, 'L', true);
$pdf->Cell(40, 7, 'Servicio', 1, 0, 'L', true);
$pdf->Cell(15, 7, '# Items', 1, 0, 'C', true);
$pdf->Cell(15, 7, '# Evals', 1, 0, 'C', true);
$pdf->Cell(25, 7, 'Particular', 1, 0, 'R', true);
$pdf->Cell(25, 7, 'Facturado', 1, 0, 'R', true);
$pdf->Cell(25, 7, 'Total (Bs)', 1, 1, 'R', true);

// Datos
$pdf->SetFont('helvetica', '', 8);
$pdf->SetTextColor(0, 0, 0);
$grandParticular = 0;
$grandFacturado = 0;
$grandTotal = 0;
$grandItems = 0;

foreach ($rows as $r) {
    $pdf->Cell(45, 6, substr($r['doctor_name'], 0, 30), 1, 0, 'L');
    $pdf->Cell(40, 6, substr($r['specialty_name'], 0, 25), 1, 0, 'L');
    $pdf->Cell(15, 6, $r['item_count'], 1, 0, 'C');
    $pdf->Cell(15, 6, $r['eval_count'], 1, 0, 'C');
    $pdf->Cell(25, 6, number_format((float)$r['total_particular'], 2), 1, 0, 'R');
    $pdf->Cell(25, 6, number_format((float)$r['total_facturado'], 2), 1, 0, 'R');
    $pdf->Cell(25, 6, number_format((float)$r['total_general'], 2), 1, 1, 'R');
    $grandParticular += $r['total_particular'];
    $grandFacturado += $r['total_facturado'];
    $grandTotal += $r['total_general'];
    $grandItems += $r['item_count'];
}

// Total
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(220, 220, 220);
$pdf->Cell(85, 7, 'TOTAL GENERAL:', 1, 0, 'R', true);
$pdf->Cell(15, 7, $grandItems, 1, 0, 'C', true);
$pdf->Cell(15, 7, count($rows) . ' gr', 1, 0, 'C', true);
$pdf->Cell(25, 7, number_format($grandParticular, 2), 1, 0, 'R', true);
$pdf->Cell(25, 7, number_format($grandFacturado, 2), 1, 0, 'R', true);
$pdf->Cell(25, 7, number_format($grandTotal, 2), 1, 1, 'R', true);

$pdf->Ln(5);
$pdf->SetFont('helvetica', 'I', 7);
$pdf->SetTextColor(120, 120, 120);
$pdf->Cell(0, 4, 'Reporte generado electronicamente - Cedimik', 0, 1, 'C');

$pdf->Output('pagos_evaluaciones_' . date('Y-m-d') . '.pdf', 'I');
