<?php
// anesthesia-record-pdf.php - PDF Registro de Anestesia
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');


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

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

$record = $con->query("SELECT * FROM anesthesia_record WHERE id = $id")->fetch_object();
if (!$record) {
    die('Registro no encontrado');
}

$pacient = $con->query("SELECT * FROM pacient WHERE id = $record->pacient_id")->fetch_object();
$age = $pacient->birthdate ? floor((time() - strtotime($pacient->birthdate)) / (365.25 * 24 * 60 * 60)) : '';
$sexo = $pacient->sex === 'F' ? 'Femenino' : ($pacient->sex === 'M' ? 'Masculino' : '');

require_once 'tcpdf/tcpdf.php';

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('Laboratorio Demo Clinica Especializada');
$pdf->SetAuthor('Laboratorio Demo Clinica Especializada');
$pdf->SetTitle('Hoja de Anestesia - ' . $pacient->name);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(15, 10, 15);
$pdf->SetAutoPageBreak(true, 15);
$pdf->AddPage();
$pdf->Image('assets/images/logo/logo.png', 15, 8, 30, 15, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

// Título
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 8, 'HOJA DE ANESTESIA', 0, 1, 'C');
$pdf->Ln(2);

// Helper para sección
function sectionTitle($pdf, $title) {
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->SetFillColor(22, 160, 133);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->Cell(0, 5, '  ' . $title, 1, 1, 'L', true);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->Ln(0.5);
}

function showKv($pdf, $label, $value) {
    $val = $value === null || $value === '' ? '-' : nl2br(htmlspecialchars($value));
    $pdf->SetFont('helvetica', '', 9);
    $html = '<b>' . $label . ':</b> ' . $val;
    $pdf->writeHTML($html, true, false, false, false, '');
}

function showKv2($pdf, $label1, $value1, $label2, $value2) {
    $v1 = $value1 === null || $value1 === '' ? '-' : htmlspecialchars($value1);
    $v2 = $value2 === null || $value2 === '' ? '-' : htmlspecialchars($value2);
    $html = '<table border="0" cellpadding="1" cellspacing="0" width="100%">
        <tr>
            <td width="50%"><b>' . $label1 . ':</b> ' . $v1 . '</td>
            <td width="50%"><b>' . $label2 . ':</b> ' . $v2 . '</td>
        </tr>
    </table>';
    $pdf->writeHTML($html, true, false, false, false, '');
}

function showKv3($pdf, $label1, $value1, $label2, $value2, $label3, $value3) {
    $v1 = $value1 === null || $value1 === '' ? '-' : htmlspecialchars($value1);
    $v2 = $value2 === null || $value2 === '' ? '-' : htmlspecialchars($value2);
    $v3 = $value3 === null || $value3 === '' ? '-' : htmlspecialchars($value3);
    $html = '<table border="0" cellpadding="1" cellspacing="0" width="100%">
        <tr>
            <td width="33%"><b>' . $label1 . ':</b> ' . $v1 . '</td>
            <td width="33%"><b>' . $label2 . ':</b> ' . $v2 . '</td>
            <td width="33%"><b>' . $label3 . ':</b> ' . $v3 . '</td>
        </tr>
    </table>';
    $pdf->writeHTML($html, true, false, false, false, '');
}

// Datos del paciente
sectionTitle($pdf, 'DATOS DEL PACIENTE');
$pdf->SetFont('helvetica', '', 9);
$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="20%"><b>Nombre:</b></td>
        <td width="42%">' . htmlspecialchars($pacient->name) . '</td>
        <td width="8%"><b>Edad:</b></td>
        <td width="10%">' . $age . ' años</td>
        <td width="8%"><b>Sexo:</b></td>
        <td width="12%">' . $sexo . '</td>
    </tr>
    <tr>
        <td><b>C.I.:</b></td>
        <td>' . htmlspecialchars($pacient->dni ?? '-') . '</td>
        <td colspan="2"><b>Fecha:</b></td>
        <td colspan="2">' . date('d/m/Y', strtotime($record->fecha)) . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(2);

// Datos de la anestesia
sectionTitle($pdf, 'DATOS DE LA ANESTESIA');
showKv3($pdf,
    'Hora Inicio', $record->hora_inicio ? date('H:i', strtotime($record->hora_inicio)) : null,
    'Hora Fin', $record->hora_finalizacion ? date('H:i', strtotime($record->hora_finalizacion)) : null,
    'Tipo Anestesia', $record->tipo_anestesia
);
showKv($pdf, 'Anestesiólogo', $record->anestesiologo);
showKv($pdf, 'Procedimiento Quirúrgico', $record->procedimiento_quirurgico);
$pdf->Ln(2);

// Evaluación Pre-Anestésica
sectionTitle($pdf, 'EVALUACIÓN PRE-ANESTÉSICA');
showKv3($pdf, 'ASA', $record->asa, 'Mallampati', $record->mallampati, 'Ayuno (hs)', $record->ayuno_horas);
showKv($pdf, 'Alergias', $record->alergias);
showKv($pdf, 'Medicación Pre-anestésica', $record->medicacion_preanestesica);
showKv($pdf, 'Examen Físico / Vía Aérea', $record->examen_fisico);
$pdf->Ln(2);

// Vía Aérea
sectionTitle($pdf, 'VÍA AÉREA');
showKv3($pdf, 'Tipo', $record->via_aerea_tipo, 'Tamaño', $record->via_aerea_detalle, 'N° Intentos', $record->intubacion_intentos);
showKv2($pdf, 'Resultado', $record->intubacion_resultado, 'Cormack-Lehane', $record->comientador_cormack);
$pdf->Ln(2);

// Líneas Vasculares
sectionTitle($pdf, 'LÍNEAS VASCULARES');
showKv($pdf, 'Catéter Periférico', $record->cateter_periferico);
showKv2($pdf, 'Línea Arterial', $record->linea_arterial, 'Vía Central', $record->via_central);
$pdf->Ln(2);

// Agentes Anestésicos
sectionTitle($pdf, 'AGENTES ANESTÉSICOS');
showKv2($pdf, 'Inducción', $record->agentes_induccion, 'Mantenimiento', $record->agentes_mantenimiento);
showKv2($pdf, 'Relajantes Musculares', $record->relajantes, 'Analgésicos / Opioides', $record->analgesicos);
$pdf->Ln(2);

// Líquidos y Pérdidas
sectionTitle($pdf, 'LÍQUIDOS Y PÉRDIDAS');
$pdf->SetFont('helvetica', '', 9);
$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="33%"><b>Cristaloides:</b> ' . ($record->cristaloide_ml ?? '-') . ' ml</td>
        <td width="33%"><b>Coloides:</b> ' . ($record->coloide_ml ?? '-') . ' ml</td>
        <td width="33%"><b>Sangre:</b> ' . ($record->sangre_ml ?? '-') . ' ml</td>
    </tr>
    <tr>
        <td><b>Hemoderivados:</b> ' . ($record->hemoderivados_ml ?? '-') . ' ml</td>
        <td><b>Sangrado Est.:</b> ' . ($record->sangrado_estimado_ml ?? '-') . ' ml</td>
        <td><b>Diuresis:</b> ' . ($record->diuresis_ml ?? '-') . ' ml</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(2);

// Monitorización Hemodinámica
sectionTitle($pdf, 'MONITORIZACIÓN HEMODINÁMICA INTRAOPERATORIA');
showKv($pdf, '', $record->monitorizacion);
$pdf->Ln(2);

// Complicaciones
sectionTitle($pdf, 'COMPLICACIONES');
showKv($pdf, '', $record->complicaciones);
$pdf->Ln(2);

// Recuperación Post-Anestésica
sectionTitle($pdf, 'RECUPERACIÓN POST-ANESTÉSICA');
showKv2($pdf, 'Hora Extubación', $record->hora_extubacion ? date('H:i', strtotime($record->hora_extubacion)) : null, 'Condición al Egreso', $record->condicion_egreso);
showKv($pdf, 'Indicaciones Postoperatorias', $record->indicaciones_postoperatorias);
$pdf->Ln(5);

// Firmas
$pdf->SetFont('helvetica', '', 9);
$pdf->Cell(80, 5, '_________________________', 0, 0, 'C');
$pdf->Cell(25);
$pdf->Cell(80, 5, '_________________________', 0, 1, 'C');
$pdf->Cell(80, 5, 'Anestesiólogo', 0, 0, 'C');
$pdf->Cell(25);
$pdf->Cell(80, 5, 'Sello y Firma', 0, 1, 'C');

// Footer
$pdf->SetY(-10);
$pdf->SetFont('helvetica', 'I', 5);
$pdf->Cell(0, 3, 'Hoja de Anestesia - Laboratorio Demo Clinica Especializada | Generado por: ' . $clinicademo_sig_user_name . ' | ' . date('d/m/Y H:i:s'), 0, 1, 'C');


$pdf->Output('Hoja_Anestesia_' . $record->id . '.pdf', 'I');
