<?php
// surgical-protocol-pdf.php - PDF Protocolo Quirúrgico
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();

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

$pacient = $con->query("SELECT * FROM pacient WHERE id = $protocol->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('Protocolo Quirúrgico - ' . $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);

$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 8, 'PROTOCOLO QUIRÚRGICO', 0, 1, 'C');
$pdf->Ln(2);

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

$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="15%"><b>Nombre:</b></td>
        <td width="35%">' . htmlspecialchars($pacient->name) . '</td>
        <td width="15%"><b>Edad:</b></td>
        <td width="15%">' . $age . ' años</td>
        <td width="20%"><b>Sexo:</b></td>
        <td width="20%">' . $sexo . '</td>
    </tr>
    <tr>
        <td><b>C.I.:</b></td>
        <td>' . htmlspecialchars($pacient->dni ?? '-') . '</td>
        <td><b>Fecha:</b></td>
        <td>' . date('d/m/Y', strtotime($protocol->fecha)) . '</td>
        <td><b>Hora Inicio:</b></td>
        <td>' . ($protocol->hora_inicio ? date('H:i', strtotime($protocol->hora_inicio)) : '-') . '</td>
    </tr>
    <tr>
        <td><b>Hora Fin:</b></td>
        <td>' . ($protocol->hora_finalizacion ? date('H:i', strtotime($protocol->hora_finalizacion)) : '-') . '</td>
        <td><b>Tipo Operación:</b></td>
        <td colspan="3">' . htmlspecialchars($protocol->tipo_operacion ?? '-') . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(3);

// Diagnósticos
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 5, '  DIAGNÓSTICOS', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="20%"><b>Pre-Operatorio:</b></td>
        <td width="80%">' . nl2br(htmlspecialchars($protocol->diagnostico_pre_operatorio ?? '')) . '</td>
    </tr>
    <tr>
        <td><b>Post-Operatorio:</b></td>
        <td>' . nl2br(htmlspecialchars($protocol->diagnostico_post_operatorio ?? '')) . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(3);

// Equipo Quirúrgico
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 5, '  EQUIPO QUIRÚRGICO', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="30%"><b>Cirujano:</b></td>
        <td width="70%">' . htmlspecialchars($protocol->cirujano ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>1er Ayudante:</b></td>
        <td>' . htmlspecialchars($protocol->primer_ayudante ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>2do Ayudante:</b></td>
        <td>' . htmlspecialchars($protocol->segundo_ayudante ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>3er Ayudante:</b></td>
        <td>' . htmlspecialchars($protocol->tercer_ayudante ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Instrumentador:</b></td>
        <td>' . htmlspecialchars($protocol->instrumentador ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Anestesiólogo:</b></td>
        <td>' . htmlspecialchars($protocol->anestesiologo ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Tipo de Anestesia:</b></td>
        <td>' . htmlspecialchars($protocol->tipo_anestesia ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Otro Médico Tratante:</b></td>
        <td>' . htmlspecialchars($protocol->otro_medico_tratante ?? '-') . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(3);

// Descripción
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 5, '  DESCRIPCIÓN DEL ACTO OPERATORIO', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('helvetica', '', 9);
$pdf->MultiCell(0, 5, htmlspecialchars($protocol->descripcion_acto_operatorio ?? '(Sin registro)'), 1, 'L');
$pdf->Ln(3);

// Hallazgos y Complicaciones
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 5, '  HALLAZGOS Y COMPLICACIONES', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="25%"><b>Hallazgos Intraoperatorios:</b></td>
        <td width="75%">' . nl2br(htmlspecialchars($protocol->hallazgos_intraoperatorios ?? '')) . '</td>
    </tr>
    <tr>
        <td><b>Complicaciones:</b></td>
        <td>' . nl2br(htmlspecialchars($protocol->complicaciones_intraoperatorias ?? '')) . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(3);

// Material Empleado
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 5, '  MATERIAL EMPLEADO', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

$html = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;">
    <tr>
        <td width="35%"><b>N° de Gasas:</b></td>
        <td width="65%">' . htmlspecialchars($protocol->nro_gasas ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>N° de Compresas:</b></td>
        <td>' . htmlspecialchars($protocol->nro_compresas ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Materias de Sutura:</b></td>
        <td>' . htmlspecialchars($protocol->materias_sutura ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Drenaje (Tipo y Cantidad):</b></td>
        <td>' . htmlspecialchars($protocol->drenaje ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Otros Materiales:</b></td>
        <td>' . htmlspecialchars($protocol->otros_materiales ?? '-') . '</td>
    </tr>
    <tr>
        <td><b>Tamaño y N° Empleado:</b></td>
        <td>' . htmlspecialchars($protocol->tamano_nro_empleado ?? '-') . '</td>
    </tr>
</table>';
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->Ln(8);

// Esquema Gráfico (empty box)
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(44, 62, 80);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 5, '  ESQUEMA GRÁFICO', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

$pdf->SetFillColor(245, 245, 245);
$pdf->Rect(15, $pdf->GetY(), 180, 80);
$pdf->SetXY(15, $pdf->GetY() + 35);
$pdf->SetFont('helvetica', 'I', 8);
$pdf->SetTextColor(150, 150, 150);
$pdf->Cell(180, 10, '(Espacio para dibujo)', 0, 1, 'C');
$pdf->SetTextColor(0, 0, 0);
$pdf->SetY($pdf->GetY() + 45);

// Firmas
$pdf->Ln(5);
$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, 'Cirujano', 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, 'Protocolo Quirúrgico - Laboratorio Demo Clinica Especializada | Generado por: ' . $clinicademo_sig_user_name . ' | ' . date('d/m/Y H:i:s'), 0, 1, 'C');


$pdf->Output('Protocolo_Quirurgico_' . $protocol->id . '.pdf', 'I');
