<?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 ---
// epicrisis-pdf.php - PDF Epicrisis
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');

include __DIR__ . '/core/app/model/PacientData.php';

$con = Database::getCon();

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $epi = $con->query("SELECT * FROM epicrisis WHERE id = $id")->fetch_object();
    if (!$epi) die('Epicrisis no encontrada');
} elseif (isset($_GET['pacient_id'])) {
    $pid = intval($_GET['pacient_id']);
    $epi = $con->query("SELECT * FROM epicrisis WHERE pacient_id = $pid ORDER BY id DESC LIMIT 1")->fetch_object();
    if (!$epi) die('No hay epicrisis para este paciente');
} else {
    die('ID requerido');
}

$pacient = $con->query("SELECT * FROM pacient WHERE id = $epi->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' : '');

// Médico tratante desde la admisión
$medicoTratante = '';
$admPdf = $con->query("SELECT * FROM admission WHERE pacient_id = $epi->pacient_id AND status = 'discharged' ORDER BY created_at DESC LIMIT 1")->fetch_object();
if ($admPdf && $admPdf->medic_id) {
    $medPdf = $con->query("SELECT name, lastname FROM medic WHERE id = " . intval($admPdf->medic_id))->fetch_object();
    if ($medPdf) $medicoTratante = trim($medPdf->name . ' ' . $medPdf->lastname);
}

require_once 'tcpdf/tcpdf.php';

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

// Logo + título
$pdf->AddPage();
$pdf->Image('assets/images/logo/logo.png', 15, 8, 30, 15, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

// Línea 1: EPICRISIS (izquierda) + Código (derecha)
$pdf->SetFont('helvetica', 'B', 16);
$pdf->SetXY(50, 10);
$pdf->Cell(120, 8, 'EPICRISIS', 0, 0, 'L');
$pdf->SetFont('helvetica', 'B', 12);
$pdf->Cell(40, 8, 'Historia Clínica Nro. ' . ($epi->id ? '#' . $epi->id : '— Nueva'), 0, 1, 'R');

// Línea 2: Clínica (izquierda) + Médico Tratante (derecha)
$pdf->SetFont('helvetica', '', 9);
$pdf->SetXY(50, 18);
$pdf->Cell(120, 5, 'Cedimik', 0, 0, 'L');
if ($medicoTratante) {
    $pdf->SetFont('helvetica', 'B', 9);
    $pdf->Cell(40, 5, 'Dr. ' . $medicoTratante, 0, 1, 'R');
} else {
    $pdf->Cell(40, 5, '', 0, 1, 'R');
}
$pdf->SetFont('helvetica', '', 9);

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

$html = '
<table border="1" cellpadding="4" cellspacing="0" style="font-size:10px;">
    <tr>
        <td width="20%"><b>Nombre</b></td>
        <td width="80%" colspan="3">' . htmlspecialchars($pacient->name) . '</td>
    </tr>
    <tr>
        <td><b>C.I.</b></td>
        <td width="30%">' . htmlspecialchars($pacient->dni ?? '-') . '</td>
        <td width="10%"><b>Edad</b></td>
        <td width="40%">' . $age . ' años | <b>Sexo:</b> ' . $sexo . '</td>
    </tr>
    <tr>
        <td><b>Empresa</b></td>
        <td colspan="3">' . htmlspecialchars($epi->empresa ?? '-') . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(2);

// Función para secciones
function pdfSection($pdf, $title, $content, $bgR = 102, $bgG = 126, $bgB = 234) {
    if ($content === null || $content === '') return;
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->SetFillColor($bgR, $bgG, $bgB);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->Cell(0, 6, '  ' . $title, 1, 1, 'L', true);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFont('helvetica', '', 9);
    $pdf->MultiCell(0, 5, $content, 1, 'L');
    $pdf->Ln(2);
}

// Ingreso / Egreso
$pdf->SetFont('helvetica', 'B', 10);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 6, '  INGRESO Y EGRESO', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

$html = '
<table border="1" cellpadding="4" cellspacing="0" style="font-size:9px;">
    <tr style="background-color:#e8f1ff;">
        <td width="15%"><b>Fecha Ingreso:</b></td>
        <td width="20%">' . ($epi->fecha_ingreso ? date('d/m/Y', strtotime($epi->fecha_ingreso)) : '-') . '</td>
        <td width="20%"><b>Diagnóstico Ingreso:</b></td>
        <td width="32%">' . htmlspecialchars($epi->diagnostico_ingreso ?? '-') . '</td>
        <td width="13%"><b>Tiempo Intern.:</b></td>
    </tr>
    <tr>
        <td colspan="2">&nbsp;</td>
        <td colspan="2">&nbsp;</td>
        <td>' . htmlspecialchars($epi->tiempo_informacion ?? '-') . '</td>
    </tr>
    <tr style="background-color:#e8f1ff;">
        <td><b>Fecha Egreso:</b></td>
        <td>' . ($epi->fecha_egreso ? date('d/m/Y', strtotime($epi->fecha_egreso)) : '-') . '</td>
        <td><b>Diagnóstico Egreso:</b></td>
        <td colspan="2">' . htmlspecialchars($epi->diagnostico_egreso ?? '-') . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(2);

pdfSection($pdf, 'MOTIVO DE INGRESO', $epi->motivo_ingreso);
// Signos Vitales al Alta (source of truth: vital_signs, REQ-IMC-003)
$vsResult = $con->query("SELECT weight, height, bmi, measured_at FROM vital_signs WHERE patient_id = " . intval($pacient->id) . " ORDER BY measured_at DESC LIMIT 1");
$vs = $vsResult ? $vsResult->fetch_assoc() : null;
if ($vs) {
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->SetFillColor(52, 152, 219);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->Cell(0, 6, '  SIGNOS VITALES AL ALTA', 1, 1, 'L', true);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFont('helvetica', '', 9);
    $peso = $vs['weight'] !== null ? htmlspecialchars($vs['weight']) . ' kg' : '-';
    $altura = $vs['height'] !== null ? htmlspecialchars($vs['height']) . ' cm' : '-';
    $imc = $vs['bmi'] !== null ? round(floatval($vs['bmi']), 1) . ' kg/m2' : '-';
    $fecha = $vs['measured_at'] ? date('d/m/Y H:i', strtotime($vs['measured_at'])) : '-';
    $vsHtml = '<table border="1" cellpadding="4" cellspacing="0" style="font-size:9px;"><tr><td width="25%"><b>Peso</b></td><td width="25%">' . $peso . '</td><td width="25%"><b>Altura</b></td><td width="25%">' . $altura . '</td></tr><tr><td><b>IMC</b></td><td>' . $imc . '</td><td><b>Fecha</b></td><td>' . $fecha . '</td></tr></table>';
    $pdf->writeHTML($vsHtml, true, false, false, false, '');
    $pdf->Ln(2);
} else {
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->SetFillColor(52, 152, 219);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->Cell(0, 6, '  SIGNOS VITALES AL ALTA', 1, 1, 'L', true);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFont('helvetica', 'I', 9);
    $pdf->Cell(0, 6, 'Sin registros de signos vitales al alta.', 1, 1, 'L');
    $pdf->Ln(2);
}

pdfSection($pdf, 'EXAMEN FÍSICO', $epi->examen_fisico, 232, 241, 255);
pdfSection($pdf, 'PRUEBAS DE LABORATORIO', $epi->pruebas_laboratorio);
pdfSection($pdf, 'ECOGRAFÍAS / RX', $epi->ecografias_rx, 232, 241, 255);
pdfSection($pdf, 'ECG / OTROS', $epi->ecg_otros);
pdfSection($pdf, 'TRATAMIENTO MÉDICO', $epi->tratamiento_medico, 232, 241, 255);
pdfSection($pdf, 'TRATAMIENTO QUIRÚRGICO', $epi->tratamiento_quirurgico);

// Parto (solo si aplica)
if ($epi->parto) {
    $pdf->SetFont('helvetica', 'B', 10);
    $pdf->SetFillColor(155, 89, 182);
    $pdf->SetTextColor(255, 255, 255);
    $pdf->Cell(0, 6, '  PARTO', 1, 1, 'L', true);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetFont('helvetica', '', 9);

    $html = '
<table border="1" cellpadding="4" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="25%"><b>Recién Nacido:</b></td>
        <td width="55%">' . htmlspecialchars($epi->rn ?? '-') . '</td>
        <td width="20%"><b>Apgar:</b></td>
        <td width="20%">' . htmlspecialchars($epi->apgar ?? '-') . '</td>
    </tr>
</table>';
    $pdf->writeHTML($html, true, false, false, false, '');
    $pdf->Ln(2);
}

pdfSection($pdf, 'EVOLUCIÓN - COMPLICACIONES', $epi->evolucion_complicaciones, 209, 231, 221);
$altaReco = trim($epi->condiciones_alta ?? '');
if (!empty($epi->recomendaciones)) {
    $altaReco .= ($altaReco !== '' ? "\n\n" : '') . trim($epi->recomendaciones);
}
pdfSection($pdf, 'CONDICIONES DE ALTA / RECOMENDACIONES', $altaReco ?: null, 209, 231, 221);

// Firmas
$pdf->Ln(5);
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(80, 5, '_________________________', 0, 0, 'C');
$pdf->Cell(25);
$pdf->Cell(80, 5, '_________________________', 0, 1, 'C');
$pdf->Cell(80, 5, 'Médico Tratante', 0, 0, 'C');
$pdf->Cell(25);
$pdf->Cell(80, 5, 'Sello y Firma', 0, 1, 'C');

// Footer
$pdf->SetY(-12);
$pdf->SetFont('helvetica', 'I', 7);
$pdf->Cell(0, 3, 'Epicrisis - Cedimik | Generado por: ' . $clinicademo_sig_user_name . ' | ' . date('d/m/Y H:i:s'), 0, 1, 'C');


$pdf->Output('Epicrisis_' . $epi->id . '.pdf', 'I');
