<?php
// --- Auth gate (lab-resultado-pdf) ---
// This standalone endpoint includes only Database.php + two models and never
// loads core/autoload.php, so the application session never starts here.
// Start it explicitly and require a logged-in user BEFORE any DB access so
// unauthenticated callers cannot probe for orden existence.
// Mirrors invoice_pdf.php: the redirect MUST be "index.php?view=login".
// "Location: ?view=login" resolves against this script's own URL
// (/cedimik/lab-resultado-pdf.php?...) and loops back into this same
// endpoint (50 redirects with curl -L) instead of reaching the login page.
if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
if (empty($_SESSION['user_id'])) { header('Location: index.php?view=login'); exit; }
// --- end auth gate ---
require_once "core/controller/Database.php";
require_once "core/app/model/LabOrdenData.php";
require_once "core/app/model/LabOrdenDetalleData.php";
$oid=intval($_GET['orden_id']??0);
$orden=LabOrdenData::getById($oid);
if(!$orden) die("Orden no encontrada");
if($orden['estado']=='anulado') die("Orden anulada — PDF no disponible");
$detalles=LabOrdenDetalleData::getByOrden($oid);
require_once "tcpdf/tcpdf.php";
$pdf=new TCPDF('P','mm','A4',true,'UTF-8',false);
$pdf->SetCreator('Cedimik'); $pdf->SetAuthor('Cedimik');
$pdf->SetTitle('Resultado Laboratorio #'.$oid);
$pdf->AddPage();
if(file_exists(__DIR__.'/assets/images/logo/logo.png')) $pdf->Image(__DIR__.'/assets/images/logo/logo.png', 15, 10, 40, 18, 'PNG');
$pdf->SetFont('helvetica','B',14); $pdf->Cell(0,10,'CEDIMIK S.R.L.',0,1,'C');
$pdf->SetFont('helvetica','',8); $pdf->Cell(0,4,'Laboratorio Clinico Especializado — Resultado',0,1,'C');
$pdf->Cell(0,4,'Sede: '.$orden['sede'].' | Paciente: '.($orden['pacient_name']??'-').' | Fecha: '.$orden['fecha_solicitud'],0,1,'C');
$pdf->Cell(0,4,'Orden #'.$orden['id'].' — Estado: '.$orden['estado'].' | Solicitante: '.($orden['solicitante']??'-'),0,1,'C');
if(!empty($orden['seguro_nombre_snapshot'])) { $pdf->Cell(0,4,'Seguro: '.$orden['seguro_nombre_snapshot'],0,1,'C'); }
$pdf->Ln(4);
$pdf->SetFont('helvetica','B',8);
$w=[25,60,25,35,25];
$pdf->Cell($w[0],7,'Codigo',1,0,'C'); $pdf->Cell($w[1],7,'Examen',1,0,'C'); $pdf->Cell($w[2],7,'Resultado',1,0,'C'); $pdf->Cell($w[3],7,'Referencia',1,0,'C'); $pdf->Cell($w[4],7,'Flag',1,1,'C');
$pdf->SetFont('helvetica','',8);
foreach($detalles as $d){
  $res=$d['resultado_valor']!==null ? $d['resultado_valor']." ".($d['unidad']??"") : "-";
  $ref=$d['ref_min']!==null ? $d['ref_min']." - ".$d['ref_max'] : ($d['ref_text']??"-");
  $flag=$d['flag']??"-";
  $pdf->Cell($w[0],6,$d['codigo'],1,0,'C'); $pdf->Cell($w[1],6,substr($d['nombre'],0,28),1,0,'L'); $pdf->Cell($w[2],6,$res,1,0,'C'); $pdf->Cell($w[3],6,$ref,1,0,'C'); $pdf->Cell($w[4],6,$flag,1,1,'C');
}
// --- Price footer section ---
$total = LabOrdenDetalleData::getOrdenTotal($oid);
$pdf->SetFont('helvetica','B',9);
if ($total === null) {
    $pdf->Cell(0, 6, 'Total: Bs. — (precios incompletos — algunos estudios no tienen precio)', 0, 1, 'R');
} else {
    $pdf->Cell(0, 6, 'Total: Bs. ' . number_format($total, 2), 0, 1, 'R');
}
$pdf->Ln(2);
// --- End price footer ---
$pdf->Ln(2); $pdf->SetFont('helvetica','',7); $pdf->Cell(0,4,'Generado: '.date('d/m/Y H:i').' | contacto@cedimik.com | Tel: (591) 2 222-2222',0,1,'C');
$pdf->Cell(0,4,'Este informe es valido con firma y sello del bioquimico responsable.',0,1,'C');
$pdf->Output('lab-resultado-'.$oid.'.pdf','I');
