<?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 ---
// medication-administration-pdf.php - Reporte de Administración de Medicamentos
include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/CotizacionData.php';
include __DIR__ . '/core/app/model/UserData.php';
include __DIR__ . '/core/app/model/PacientData.php';
include __DIR__ . '/core/app/model/MedicData.php';

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)) : null;

// Signature (uses session + UserData)
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');

// Load entries (join user for "administered by" display)
$entries = [];
$res = $con->query("
    SELECT ma.*, u.name AS u_name, u.lastname AS u_lastname, u.username AS u_username
    FROM medication_administration ma
    LEFT JOIN user u ON u.id = ma.administered_by
    WHERE ma.pacient_id = $pacientId AND ma.is_active = 1
    ORDER BY ma.fecha_administracion DESC, ma.hora_administracion DESC
");
while ($r = $res->fetch_assoc()) {
    $entries[] = $r;
}

require_once 'tcpdf/tcpdf.php';

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('Cedimik');
$pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Administración de Medicamentos - ' . $pacient->name);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(5, 8, 5);
$pdf->SetAutoPageBreak(true, 10);
$pdf->SetFont('helvetica', '', 8);

$pdf->AddPage();

// === Header ===
$pdf->Image('assets/images/logo/logo.png', 5, 6, 30, 15, 'PNG');
$pdf->SetFont('helvetica', 'B', 12);
$pdf->SetXY(37, 5);
$pdf->Cell(120, 5, 'ADMINISTRACION DE MEDICAMENTOS', 0, 0, 'L');
$pdf->SetFont('helvetica', '', 7);
$pdf->SetXY(37, 10);
$pdf->Cell(120, 3, 'Registro de administraciones con responsable', 0, 1, 'L');

$pdf->SetFont('helvetica', 'B', 7);
$pdf->SetXY(150, 5);
$pdf->Cell(55, 4, 'Paciente: ' . $pacient->name, 0, 0, 'R');
$pdf->SetFont('helvetica', '', 6);
$pdf->SetXY(150, 9);
$pdf->Cell(55, 3, 'CI: ' . ($pacient->dni ?: '-') . ' | Edad: ' . ($age ?: '-'), 0, 1, 'R');

$pdf->Line(5, 16, 205, 16);
$pdf->Ln(2);

// === Patient summary (well below logo) ===
$pdf->SetY(20);
$pdf->SetFont('helvetica', 'B', 8);
$pdf->Cell(0, 5, 'Resumen del paciente', 0, 1, 'L');
$pdf->SetFont('helvetica', '', 8);
$pdf->Cell(95, 5, 'Nombre: ' . $pacient->name, 0, 0, 'L');
$pdf->Cell(95, 5, 'CI: ' . ($pacient->dni ?: '-'), 0, 1, 'L');
$pdf->Ln(3);
$pdf->Line(5, $pdf->GetY() + 1, 205, $pdf->GetY() + 1);
$pdf->Ln(4);

// === Table ===
$pdf->SetFont('helvetica', 'B', 8);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);

$w = [24, 55, 45, 60];
$headers = ['Hora', 'Medicamento', 'Vía / Dosis', 'Administrado por'];

foreach ($headers as $i => $h) {
    $pdf->Cell($w[$i], 7, $h, 1, 0, 'C', true);
}
$pdf->Ln();

if (count($entries) > 0) {
    $pdf->SetFont('helvetica', '', 7);
    $pdf->SetTextColor(0, 0, 0);
    $fill = false;
    $pdf->SetFillColor(245, 245, 245);

    foreach ($entries as $e) {
        $hora = date('d/m/Y', strtotime($e['fecha_administracion'])) . ' ' . date('H:i', strtotime($e['hora_administracion']));
        $med  = $e['medicamento'];
        $vd   = $e['via_dosis'];
        $uName = trim(($e['u_name'] ?? '') . ' ' . ($e['u_lastname'] ?? ''));
        if ($uName === '') $uName = $e['u_username'] ?? '-';

        $medLines = max(1, ceil(strlen($med) / 40));
        $vdLines = max(1, ceil(strlen($vd) / 30));
        $uLines = max(1, ceil(strlen($uName) / 40));
        $rowH = max(7, max($medLines, $vdLines, $uLines) * 4);

        if ($pdf->GetY() + $rowH > 280) {
            $pdf->AddPage();
            $pdf->SetFont('helvetica', 'B', 8);
            $pdf->SetFillColor(44, 62, 80);
            $pdf->SetTextColor(255, 255, 255);
            foreach ($headers as $i => $h) {
                $pdf->Cell($w[$i], 7, $h, 1, 0, 'C', true);
            }
            $pdf->Ln();
            $pdf->SetFont('helvetica', '', 7);
            $pdf->SetTextColor(0, 0, 0);
            $pdf->SetFillColor(245, 245, 245);
        }

        $pdf->Cell($w[0], $rowH, $hora, 1, 0, 'C', $fill);
        $pdf->Cell($w[1], $rowH, $med, 1, 0, 'L', $fill);
        $pdf->Cell($w[2], $rowH, $vd, 1, 0, 'L', $fill);
        $pdf->Cell($w[3], $rowH, $uName, 1, 0, 'L', $fill);
        $pdf->Ln();
        $fill = !$fill;
    }
} else {
    $pdf->SetFont('helvetica', 'I', 10);
    $pdf->Cell(0, 10, 'No hay administraciones registradas para este paciente.', 0, 1, 'C');
}

// === Footer ===
$pdf->SetY(-10);
$pdf->SetFont('helvetica', 'I', 5);
$pdf->Cell(0, 3, 'Reporte de Administracion de Medicamentos - Cedimik | ' . $clinicademo_sig_footer, 0, 1, 'C');

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