<?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 ---
// patient-evolution-pdf.php - PDF Hoja de Evoluciones
include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/UserData.php';
include __DIR__ . '/core/app/model/PacientData.php';

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;
        }
    }
}

if (!isset($_GET['pacient_id'])) {
    die('Paciente ID requerido');
}

$pacientId = intval($_GET['pacient_id']);
$con = Database::getCon();

$pacient = $con->query("SELECT * FROM pacient WHERE id = $pacientId")->fetch_object();
if (!$pacient) die('Paciente no encontrado');

$age = $pacient->birthdate ? floor((time() - strtotime($pacient->birthdate)) / (365.25 * 24 * 60 * 60)) : '';
$sexo = $pacient->sex === 'F' ? 'Femenino' : ($pacient->sex === 'M' ? 'Masculino' : '');

// Evoluciones
$evolutions = [];
$res = $con->query("SELECT e.*, u.name AS user_name, u.lastname AS user_lastname 
    FROM patient_evolutions e 
    LEFT JOIN user u ON e.created_by = u.id 
    WHERE e.pacient_id = $pacientId 
    ORDER BY e.created_at DESC");
while ($r = $res->fetch_assoc()) {
    $evolutions[] = $r;
}

require_once 'tcpdf/tcpdf.php';

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Hoja de Evoluciones - ' . PacientData::fullName($pacient));
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(12, 12, 12);
$pdf->SetAutoPageBreak(true, 14);
$pdf->SetFont('helvetica', '', 9);

$pdf->AddPage();

// Header
$pdf->Image('assets/images/logo/logo.png', 12, 8, 28, 14, 'PNG');
$pdf->SetFont('helvetica', 'B', 14);
$pdf->SetXY(44, 8);
$pdf->Cell(150, 7, 'HOJA DE EVOLUCIONES', 0, 1, 'L');
$pdf->SetFont('helvetica', '', 8);
$pdf->SetXY(44, 15);
$pdf->Cell(150, 4, 'Cedimik', 0, 1, 'L');

// Datos del paciente
$pdf->Ln(2);
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 6, '  DATOS DEL PACIENTE', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="15%"><b>Nombre</b></td>
        <td width="55%">' . htmlspecialchars($pacient->name) . '</td>
        <td width="12%"><b>Edad</b></td>
        <td width="18%">' . $age . ' años</td>
    </tr>
    <tr>
        <td><b>C.I.</b></td>
        <td>' . htmlspecialchars($pacient->dni ?? '-') . '</td>
        <td><b>Sexo</b></td>
        <td>' . $sexo . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(3);

// Evoluciones
if (count($evolutions) > 0) {
    foreach ($evolutions as $ev) {
        $fecha = date('d/m/Y', strtotime($ev['created_at']));
        $hora = date('H:i', strtotime($ev['created_at']));
        $user = trim(($ev['user_name'] ?? '') . ' ' . ($ev['user_lastname'] ?? ''));
        if (!$user) $user = '-';

        // Fila título - full width
        $tableLeft = 12;
        $tableRight = 198;
        $tableWidth = $tableRight - $tableLeft; // 186mm
        $boxSize = 25;

        $pdf->SetFont('helvetica', 'B', 8);
        $pdf->SetFillColor(232, 241, 255);
        $pdf->Cell($tableWidth, 5, '  ' . $fecha . ' - ' . $hora . '  |  ' . $user, 1, 1, 'L', true);

        // Fila contenido + cuadro firma
        $startY = $pdf->GetY();
        $contentW = $tableWidth - $boxSize; // 161mm

        // Contenido (con borde) en columna izquierda
        $pdf->SetFont('helvetica', '', 8);
        $pdf->MultiCell($contentW, 5, $ev['content'], 1, 'L', false, 1, $tableLeft, $startY);

        $endY = $pdf->GetY();
        $rowHeight = max($boxSize, $endY - $startY);

        // Cuadro de firma (cuadrado vacío) en columna derecha — misma altura que el detalle
        $pdf->Rect($tableLeft + $contentW, $startY, $boxSize, $rowHeight);

        // Avanzar el cursor
        $pdf->SetY($startY + $rowHeight);
        $pdf->Ln(3);
    }
} else {
    $pdf->SetFont('helvetica', 'I', 9);
    $pdf->Cell(0, 6, 'No hay evoluciones registradas para este paciente.', 1, 1, 'L');
}

// Footer (desactivar auto page break para que no genere una página extra solo por el pie)
$pdf->SetAutoPageBreak(false);
$pdf->SetY(-12);
$pdf->SetFont('helvetica', 'I', 7);
$pdf->Cell(0, 3, 'Hoja de Evoluciones - Cedimik | Generado por: ' . $clinicademo_sig_user_name . ' | ' . date('d/m/Y H:i:s'), 0, 1, 'C');
$pdf->SetAutoPageBreak(true, 14);

$pdf->Output('Evoluciones_' . $pacientId . '.pdf', 'I');
