<?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 ---
// glicemia-pdf.php - PDF Control de Glicemias
include __DIR__ . '/core/autoload.php';
include __DIR__ . '/core/app/model/UserData.php';
include __DIR__ . '/core/app/model/PacientData.php';

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;
        }
    }
}

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)) : '';
$sexo = $pacient->sex === 'F' ? 'Femenino' : ($pacient->sex === 'M' ? 'Masculino' : '');

// Cama del paciente
$cama = '';
$admCama = $con->query("SELECT * FROM admission WHERE pacient_id = $pacientId ORDER BY created_at DESC LIMIT 1")->fetch_object();
if ($admCama && !empty($admCama->room_id)) {
    $r = $con->query("SELECT no_cama, numero, habitacion FROM room WHERE id = " . intval($admCama->room_id))->fetch_object();
    if ($r) {
        $cama = trim(($r->habitacion ?? '') . ' ' . ($r->no_cama ?? ''));
        if (!$cama) $cama = 'Habitación ' . ($r->numero ?? $admCama->room_id);
    }
}

// Glicemias
$glicemias = [];
$res = $con->query("SELECT g.*, u.name AS user_name, u.lastname AS user_lastname
    FROM patient_glicemias g
    LEFT JOIN user u ON g.created_by = u.id
    WHERE g.pacient_id = $pacientId
    ORDER BY g.created_at ASC");
while ($r = $res->fetch_assoc()) {
    $glicemias[] = $r;
}

require_once 'tcpdf/tcpdf.php';

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

$pdf->AddPage();

// Header
$pdf->Image('assets/images/logo/logo.png', 12, 8, 28, 14, 'PNG');
$pdf->SetFont('helvetica', 'B', 14);
$pdf->SetXY(44, 8);
$pdf->Cell(150, 7, 'CONTROL DE GLICEMIAS', 0, 1, 'L');
$pdf->SetFont('helvetica', '', 8);
$pdf->SetXY(44, 15);
$pdf->Cell(150, 4, 'Cedimik', 0, 1, 'L');

// Datos del paciente
$pdf->Ln(2);
$pdf->SetFont('helvetica', 'B', 9);
$pdf->SetFillColor(108, 117, 125);  // Bootstrap secondary gray
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(0, 6, '  DATOS DEL PACIENTE', 1, 1, 'L', true);
$pdf->SetTextColor(0, 0, 0);

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

// Registros - un cuadro por glicemia con cuadro de firma a la derecha
$tableLeft = 12;
$boxSize = 25;
$contentW = 186 - $boxSize; // 161mm

if (count($glicemias) > 0) {
    // Header de la tabla
    $tblHtml = '
<table border="1" cellpadding="3" cellspacing="0" style="font-size:9px;width:100%;">
    <thead>
        <tr style="background-color:#6c757d;color:#ffffff;font-weight:bold;">
            <th width="12%" align="center">Fecha</th>
            <th width="10%" align="center">Hora</th>
            <th width="17%" align="center">Glicemia</th>
            <th width="38%" align="center">Corrección con insulina</th>
            <th width="23%" align="center">Firma</th>
        </tr>
    </thead>
    <tbody>';
    foreach ($glicemias as $g) {
        $fecha = date('d/m/Y', strtotime($g['created_at']));
        $hora = date('H:i', strtotime($g['created_at']));
        $valor = number_format((float)$g['valor'], 1);
        $unidad = $g['unidad'] ?? 'mg/dL';
        $obs = $g['observaciones'] ?? '';
        $user = trim(($g['user_name'] ?? '') . ' ' . ($g['user_lastname'] ?? ''));
        if (!$user) $user = '-';

        // Color de la celda de glicemia según rango. Solo se aplica color cuando el valor está fuera de lo normal (v < 70 o v > 180). Normal no se tiñe.
        $v = (float)$g['valor'];
        if ($v < 70) {
            $bgColor = '#ffc107;';  // warning yellow (Bootstrap)
            $colorLabel = 'Hipoglicemia';
        } elseif ($v > 180) {
            $bgColor = '#dc3545;';  // danger red (Bootstrap)
            $colorLabel = 'Hiperglicemia';
        } else {
            $bgColor = '';  // sin teñir (Normal)
            $colorLabel = 'Normal';
        }

        $obsHtml = $obs !== '' ? nl2br(htmlspecialchars($obs)) : '<i style="color:#999;">Sin corrección</i>';
        $tblHtml .= '
        <tr>
            <td width="12%" align="center">' . $fecha . '</td>
            <td width="10%" align="center">' . $hora . '</td>
            <td width="17%" align="center" style="' . ($bgColor !== '' ? 'background-color:' . $bgColor . ';color:#fff;' : '') . '"><b>' . $valor . ' ' . htmlspecialchars($unidad) . '</b><br><small style="font-size:7px;">' . $colorLabel . '</small></td>
            <td width="38%" style="font-size:8px;">' . $obsHtml . '</td>
            <td width="23%" align="center" style="font-size:8px;">' . htmlspecialchars($user) . '</td>
        </tr>';
    }
    $tblHtml .= '
    </tbody>
</table>';
    $pdf->writeHTML($tblHtml, true, false, false, false, '');
} else {
    $pdf->SetFont('helvetica', 'I', 9);
    $pdf->Cell(0, 6, 'No hay glicemias registradas para este paciente.', 1, 1, 'L');
}

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

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