<?php
// ============================================
// GENERADOR PDF MSP-051 · HISTORIA CLÍNICA MATERNA PERINATAL
// Reconstrucción TCPDF puro con paleta MSP oficial, emisor dinámico y QR de firma.
// (Reemplaza la estrategia "calco con imagen de fondo" que descuadraba.)
// ============================================

function generarPDFMsp051($idatencion, $json)
{
    if (!cargarTCPDF()) return null;

    $p = obtenerDatosPaciente($idatencion);
    $d = json_decode($json, true) ?? [];
    $emisor = _mspObtenerEmisor();
    $val = function ($k, $alt = '—') use ($d) { return _mspVal($d, $k, $alt); };
    $valnl = function ($k, $alt = '—') use ($d) { return _mspValnl($d, $k, $alt); };

    $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $pdf->SetCreator('Sistema Médico HC');
    $pdf->SetAuthor($emisor['institucion'] ?: 'Profesional médico');
    $pdf->SetTitle('HISTORIA CLÍNICA MATERNA PERINATAL · MSP-051');
    $pdf->SetMargins(10, 8, 10);
    $pdf->SetAutoPageBreak(TRUE, 12);

    $qrTimestamp = date('Y-m-d H:i:s');
    $qrContent = _mspQrContent($idatencion, 'MSP-051 · Historia Clínica Materna Perinatal', $emisor, $qrTimestamp);
    $estilo = _mspEstiloOficial();

    // ============================================================
    // PÁGINA 1: IDENTIFICACIÓN · ANTECEDENTES · GESTACIÓN ACTUAL
    // ============================================================
    $pdf->AddPage();
    $html = $estilo . _mspCabeceraEmisor($emisor) . _mspIdentificacionPaciente($emisor, $p);

    $html .= '
    <table cellspacing="0">
        <tr><td class="section-band" style="text-align:center; font-size:11pt;">
            MSP-051 · HISTORIA CLÍNICA MATERNA PERINATAL
        </td></tr>
        <tr><td class="small text-center" style="padding:4px;">
            CLAP-SMR · OPS/OMS · MSP/UEHCM
        </td></tr>
    </table><br>';

    // 1. DATOS GENERALES Y ANTECEDENTES PERSONALES
    $html .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band"><span class="section-num">1</span>DATOS GENERALES DE LA GESTANTE</td></tr>
        <tr>
            <td width="25%" class="subhead-left">DOMICILIO</td>
            <td colspan="3" class="data-cell">' . $val('domicilio', $p['direccion'] ?? '—') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">LUGAR DE CONTROL PRENATAL</td>
            <td class="data-cell">' . $val('lugar_control_prenatal') . '</td>
            <td class="subhead-left">LUGAR DEL PARTO / ABORTO</td>
            <td class="data-cell">' . $val('lugar_parto_aborto') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">ETNIA / AUTOIDENTIFICACIÓN</td>
            <td class="data-cell">' . $val('etnia') . '</td>
            <td class="subhead-left">AÑOS DE ESTUDIO / ALFABETA</td>
            <td class="data-cell">' . $val('anos_estudio') . '</td>
        </tr>
        <tr>
            <td colspan="4" class="subhead">ESTADO CIVIL</td>
        </tr>
        <tr style="font-size:8.5pt;">
            <td colspan="4" class="data-cell text-center">
                ' . _msp051CheckLabel('Soltera',   $val('estado_civil', '')) . '
                ' . _msp051CheckLabel('Casada',    $val('estado_civil', '')) . '
                ' . _msp051CheckLabel('Unión',     $val('estado_civil', '')) . '
                ' . _msp051CheckLabel('Separada',  $val('estado_civil', '')) . '
                ' . _msp051CheckLabel('Viuda',     $val('estado_civil', '')) . '
            </td>
        </tr>
    </table><br>';

    // 2. ANTECEDENTES FAMILIARES / PERSONALES / OBSTÉTRICOS
    $itemsFam = [
        'ant_tbc' => 'TBC', 'ant_diabetes' => 'Diabetes', 'ant_hta' => 'HTA',
        'ant_preeclampsia' => 'Preeclampsia', 'ant_eclampsia' => 'Eclampsia',
        'ant_cirugia_gu' => 'Cir. Génito-Urin.', 'ant_infertilidad' => 'Infertilidad',
        'ant_cardiopatia' => 'Cardiopatía', 'ant_nefropatia' => 'Nefropatía',
        'ant_violencia' => 'Violencia', 'ant_vih' => 'VIH(+)', 'ant_otra' => 'Otra',
    ];

    $html .= '
    <table cellspacing="0">
        <tr><td colspan="12" class="section-band"><span class="section-num">2</span>ANTECEDENTES (Familiares · Personales · Obstétricos)</td></tr>
        <tr>
            <td colspan="4" class="subhead">CONDICIÓN</td>
            <td colspan="4" class="subhead">FAMILIAR</td>
            <td colspan="4" class="subhead">PERSONAL</td>
        </tr>';
    foreach ($itemsFam as $k => $label) {
        $fam = !empty($d['fam_'.$k]) ? 'X' : '';
        $per = !empty($d['per_'.$k]) ? 'X' : '';
        $html .= '<tr style="font-size:8pt;">
            <td colspan="4" class="item-label">' . $label . '</td>
            <td colspan="4" class="cp-sp">' . $fam . '</td>
            <td colspan="4" class="cp-sp">' . $per . '</td>
        </tr>';
    }
    $html .= '</table><br>';

    // 3. ANTECEDENTES OBSTÉTRICOS
    $html .= '
    <table cellspacing="0">
        <tr><td colspan="6" class="section-band"><span class="section-num">3</span>ANTECEDENTES OBSTÉTRICOS</td></tr>
        <tr>
            <td width="16%" class="subhead-left">GESTAS PREVIAS</td>
            <td width="16%" class="data-cell text-center">' . $val('gestas_previas') . '</td>
            <td width="16%" class="subhead-left">PARTOS</td>
            <td width="16%" class="data-cell text-center">' . $val('partos') . '</td>
            <td width="18%" class="subhead-left">VAGINALES / CESÁREAS</td>
            <td width="18%" class="data-cell text-center">' . $val('vaginales') . ' / ' . $val('cesareas') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">ABORTOS</td>
            <td class="data-cell text-center">' . $val('abortos') . '</td>
            <td class="subhead-left">ECTÓPICOS</td>
            <td class="data-cell text-center">' . $val('ectopicos') . '</td>
            <td class="subhead-left">NACIDOS VIVOS / MUERTOS</td>
            <td class="data-cell text-center">' . $val('nacidos_vivos') . ' / ' . $val('nacidos_muertos') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">MUERTOS 1ª SEMANA</td>
            <td class="data-cell text-center">' . $val('muertos_1a_sem') . '</td>
            <td class="subhead-left">MUERTOS DESPUÉS 1ª SEM</td>
            <td class="data-cell text-center">' . $val('muertos_despues_1a_sem') . '</td>
            <td class="subhead-left">EMBARAZO PLANEADO</td>
            <td class="data-cell text-center">' . $val('embarazo_planeado') . '</td>
        </tr>
        <tr>
            <td colspan="6" class="subhead-left">FIN DEL EMBARAZO ANTERIOR</td>
        </tr>
        <tr>
            <td colspan="6" class="data-cell">' . $val('fin_embarazo_anterior') . '</td>
        </tr>
    </table><br>';

    // 4. GESTACIÓN ACTUAL
    $html .= '
    <table cellspacing="0">
        <tr><td colspan="6" class="section-band"><span class="section-num">4</span>GESTACIÓN ACTUAL</td></tr>
        <tr>
            <td width="16%" class="subhead-left">PESO ANTERIOR (kg)</td>
            <td width="16%" class="data-cell">' . $val('peso_anterior') . '</td>
            <td width="16%" class="subhead-left">TALLA (cm)</td>
            <td width="16%" class="data-cell">' . $val('talla', $p['talla'] ?? '—') . '</td>
            <td width="18%" class="subhead-left">FUM</td>
            <td width="18%" class="data-cell">' . $val('fum') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">EG CONFIABLE POR FUM</td>
            <td class="data-cell">' . $val('eg_fum') . '</td>
            <td class="subhead-left">ECO &lt; 20 SEM</td>
            <td class="data-cell">' . $val('eco_20sem') . '</td>
            <td class="subhead-left">FPP (Fecha Probable Parto)</td>
            <td class="data-cell">' . $val('fpp') . '</td>
        </tr>
        <tr>
            <td colspan="6" class="subhead-left">VACUNAS / HÁBITOS / VIOLENCIA</td>
        </tr>
        <tr style="font-size:8pt;">
            <td colspan="6" class="data-cell">
                <b>Antirubeola:</b> ' . $val('antirubeola') . '  ·  <b>Antitetánica:</b> ' . $val('antitetanica') .
                '<br><b>Tabaco antes:</b> ' . $val('tabaco_antes') . '  ·  <b>Tabaco durante:</b> ' . $val('tabaco_durante') .
                '  ·  <b>Alcohol:</b> ' . $val('alcohol') . '  ·  <b>Drogas:</b> ' . $val('drogas') .
                '  ·  <b>Violencia:</b> ' . $val('violencia') . '
            </td>
        </tr>
    </table><br>';

    // 5. EXÁMENES Y LABORATORIO
    $html .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band"><span class="section-num">5</span>EXÁMENES Y LABORATORIO</td></tr>
        <tr>
            <td width="25%" class="subhead-left">EXAMEN ODONTOLÓGICO</td>
            <td width="25%" class="data-cell">' . $val('odontologico') . '</td>
            <td width="25%" class="subhead-left">EXAMEN MAMAS</td>
            <td width="25%" class="data-cell">' . $val('examen_mamas') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">CÉRVIX (inspección)</td>
            <td class="data-cell">' . $val('cervix_inspeccion') . '</td>
            <td class="subhead-left">PAP / COLPOSCOPIA</td>
            <td class="data-cell">' . $val('pap') . ' / ' . $val('colp') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">GRUPO Y RH</td>
            <td class="data-cell">' . $val('grupo_rh') . '</td>
            <td class="subhead-left">HB &lt; 20 SEM / ≥ 20 SEM</td>
            <td class="data-cell">' . $val('hb_menor20') . ' / ' . $val('hb_mayor20') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">VDRL &lt; 20 / ≥ 20 SEM</td>
            <td class="data-cell">' . $val('vdrl_menor20') . ' / ' . $val('vdrl_mayor20') . '</td>
            <td class="subhead-left">VIH</td>
            <td class="data-cell">' . $val('vih_test') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">CHAGAS</td>
            <td class="data-cell">' . $val('chagas') . '</td>
            <td class="subhead-left">PALUDISMO</td>
            <td class="data-cell">' . $val('paludismo') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">BACTERIURIA</td>
            <td class="data-cell">' . $val('bacteriuria') . '</td>
            <td class="subhead-left">GLICEMIA AYUNO / POST-PRANDIAL</td>
            <td class="data-cell">' . $val('glicemia_ayuno') . ' / ' . $val('glicemia_postprandial') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">ESTREPTOCOCO B (35-37 sem)</td>
            <td class="data-cell">' . $val('estreptococo_b') . '</td>
            <td class="subhead-left">PREPARACIÓN PARA EL PARTO</td>
            <td class="data-cell">' . $val('preparacion_parto') . '</td>
        </tr>
    </table>';

    $pdf->writeHTML($html, true, false, true, false, '');
    _mspPieFirmaConQR($pdf, $emisor, $qrContent, $qrTimestamp, $estilo, '051', 'HISTORIA CLÍNICA MATERNA PERINATAL · ANVERSO');

    // ============================================================
    // PÁGINA 2: PARTO / ABORTO · ENFERMEDADES · PARTOGRAMA
    // ============================================================
    $pdf->AddPage();
    $html2 = $estilo . _mspCabeceraEmisor($emisor) . _mspIdentificacionPaciente($emisor, $p);

    // 6. PARTO / ABORTO
    $html2 .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band"><span class="section-num">6</span>PARTO / ABORTO</td></tr>
        <tr>
            <td width="25%" class="subhead-left">FECHA INGRESO</td>
            <td width="25%" class="data-cell">' . $val('fecha_ingreso_parto') . '</td>
            <td width="25%" class="subhead-left">HORA INGRESO</td>
            <td width="25%" class="data-cell">' . $val('hora_ingreso_parto') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">CARNET</td>
            <td class="data-cell">' . $val('carnet') . '</td>
            <td class="subhead-left">CONSULTAS PRENATALES (total)</td>
            <td class="data-cell">' . $val('consultas_prenatales') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">HOSPITALIZACIÓN PREVIA</td>
            <td class="data-cell">' . $val('hospitalizacion_previa') . '</td>
            <td class="subhead-left">TAMAÑO FETAL</td>
            <td class="data-cell">' . $val('tamano_fetal') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">ACOMPAÑANTE</td>
            <td class="data-cell">' . $val('acompanante') . '</td>
            <td class="subhead-left">POSICIÓN PARTO</td>
            <td class="data-cell">' . $val('posicion_parto') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">TERMINACIÓN</td>
            <td class="data-cell">' . $val('terminacion') . '</td>
            <td class="subhead-left">INDICACIÓN PRINCIPAL</td>
            <td class="data-cell">' . $val('indicacion_principal') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">EPISIOTOMÍA</td>
            <td class="data-cell">' . $val('episiotomia') . '</td>
            <td class="subhead-left">DESGARROS</td>
            <td class="data-cell">' . $val('desgarros') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">OXITÓCICOS</td>
            <td class="data-cell">' . $val('oxitocicos') . '</td>
            <td class="subhead-left">PLACENTA</td>
            <td class="data-cell">' . $val('placenta') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">LIGADURA CORDÓN</td>
            <td class="data-cell">' . $val('ligadura_cordon') . '</td>
            <td class="subhead-left">ATENDIÓ</td>
            <td class="data-cell">' . $val('atendio') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">ALUMBRAMIENTO</td>
            <td class="data-cell">' . $val('alumbramiento') . '</td>
            <td class="subhead-left">MEDICACIÓN ADMINISTRADA</td>
            <td class="data-cell">' . $val('medicacion_parto') . '</td>
        </tr>
    </table><br>';

    // 7. ENFERMEDADES INTRA-PARTO
    $enfermedades = [
        'hipertension_cronica' => 'Hipertensión Crónica',
        'preeclampsia'         => 'Preeclampsia',
        'eclampsia'            => 'Eclampsia',
        'infeccion'            => 'Infección',
        'hemorragia'           => 'Hemorragia',
        'anemia'               => 'Anemia',
        'itu'                  => 'ITU',
        'diabetes_gest'        => 'Diabetes Gestacional',
        'otra_enf'             => 'Otra',
    ];
    $html2 .= '
    <table cellspacing="0">
        <tr><td colspan="6" class="section-band"><span class="section-num">7</span>ENFERMEDADES (Intra-parto)</td></tr>
        <tr>';
    $col = 0;
    foreach ($enfermedades as $k => $label) {
        $marca = !empty($d['enf_'.$k]) ? 'X' : '';
        $html2 .= '<td width="11%" class="item-label">' . $label . '</td>'
               .  '<td width="5.5%" class="cp-sp">' . $marca . '</td>';
        $col++;
        if ($col % 3 == 0) $html2 .= '</tr><tr>';
    }
    $html2 .= '</tr>
        <tr><td colspan="6" class="subhead-left">OBSERVACIONES</td></tr>
        <tr><td colspan="6" class="data-cell" style="height:35px;">' . $valnl('observaciones_enf') . '</td></tr>
    </table><br>';

    // 8. PARTOGRAMA (resumen)
    $html2 .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band"><span class="section-num">8</span>PARTOGRAMA · RESUMEN</td></tr>
        <tr>
            <td width="25%" class="subhead-left">INICIO DEL TRABAJO DE PARTO</td>
            <td width="25%" class="data-cell">' . $val('partograma_inicio') . '</td>
            <td width="25%" class="subhead-left">RUPTURA DE MEMBRANAS</td>
            <td width="25%" class="data-cell">' . $val('ruptura_membranas') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">DILATACIÓN INICIAL (cm)</td>
            <td class="data-cell">' . $val('dilatacion_inicial') . '</td>
            <td class="subhead-left">DILATACIÓN MÁXIMA (cm)</td>
            <td class="data-cell">' . $val('dilatacion_maxima') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">FCF MÍNIMA / MÁXIMA</td>
            <td class="data-cell">' . $val('fcf_minima') . ' / ' . $val('fcf_maxima') . '</td>
            <td class="subhead-left">CONTRACCIONES (10 min)</td>
            <td class="data-cell">' . $val('contracciones') . '</td>
        </tr>
        <tr>
            <td colspan="4" class="subhead-left">OBSERVACIONES DEL PARTOGRAMA</td>
        </tr>
        <tr>
            <td colspan="4" class="data-cell" style="height:45px;">' . $valnl('partograma_observaciones') . '</td>
        </tr>
    </table>';

    $pdf->writeHTML($html2, true, false, true, false, '');
    _mspPieFirmaConQR($pdf, $emisor, $qrContent, $qrTimestamp, $estilo, '051', 'HISTORIA CLÍNICA MATERNA PERINATAL · PARTO');

    // ============================================================
    // PÁGINA 3: RECIÉN NACIDO + EGRESO RN + EGRESO MATERNO
    // ============================================================
    $pdf->AddPage();
    $html3 = $estilo . _mspCabeceraEmisor($emisor) . _mspIdentificacionPaciente($emisor, $p);

    // 9. RECIÉN NACIDO
    $html3 .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band"><span class="section-num">9</span>RECIÉN NACIDO</td></tr>
        <tr>
            <td width="25%" class="subhead-left">SEXO RN</td>
            <td width="25%" class="data-cell">' . $val('rn_sexo') . '</td>
            <td width="25%" class="subhead-left">PESO RN (g)</td>
            <td width="25%" class="data-cell">' . $val('rn_peso') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">TALLA RN (cm)</td>
            <td class="data-cell">' . $val('rn_talla') . '</td>
            <td class="subhead-left">PERÍMETRO CEFÁLICO (cm)</td>
            <td class="data-cell">' . $val('rn_perimetro_cef') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">APGAR 1 min</td>
            <td class="data-cell">' . $val('apgar_1') . '</td>
            <td class="subhead-left">APGAR 5 min</td>
            <td class="data-cell">' . $val('apgar_5') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">EDAD GESTACIONAL (sem)</td>
            <td class="data-cell">' . $val('rn_eg') . '</td>
            <td class="subhead-left">VIVO / MUERTO</td>
            <td class="data-cell" style="font-weight:bold;">' . $val('rn_vivo_muerto') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">REANIMACIÓN</td>
            <td class="data-cell">' . $val('rn_reanimacion') . '</td>
            <td class="subhead-left">DEFECTOS CONGÉNITOS</td>
            <td class="data-cell">' . $val('rn_defectos') . '</td>
        </tr>
        <tr>
            <td colspan="4" class="subhead-left">EXAMEN FÍSICO DEL RECIÉN NACIDO</td>
        </tr>
        <tr>
            <td colspan="4" class="data-cell" style="height:50px;">' . $valnl('rn_examen_fisico') . '</td>
        </tr>
        <tr>
            <td colspan="4" class="subhead-left">ENFERMEDADES NEONATALES</td>
        </tr>
        <tr>
            <td colspan="4" class="data-cell" style="height:35px;">' . $valnl('rn_enf_neonatales') . '</td>
        </tr>
    </table><br>';

    // 10. EGRESO RECIÉN NACIDO
    $html3 .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band"><span class="section-num">10</span>EGRESO DEL RECIÉN NACIDO</td></tr>
        <tr>
            <td width="25%" class="subhead-left">CONDICIÓN DE EGRESO</td>
            <td width="25%" class="data-cell" style="font-weight:bold;">' . $val('rn_egreso_condicion') . '</td>
            <td width="25%" class="subhead-left">FECHA</td>
            <td width="25%" class="data-cell">' . $val('rn_egreso_fecha') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">HORA</td>
            <td class="data-cell">' . $val('rn_egreso_hora') . '</td>
            <td class="subhead-left">ALIMENTACIÓN AL ALTA</td>
            <td class="data-cell">' . $val('rn_alimentacion_alta') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">BCG</td>
            <td class="data-cell">' . $val('rn_bcg') . '</td>
            <td class="subhead-left">ANTIRRETROVIRAL</td>
            <td class="data-cell">' . $val('rn_antirretroviral') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">VITAMINA K</td>
            <td class="data-cell">' . $val('rn_vit_k') . '</td>
            <td class="subhead-left">PESO DE EGRESO</td>
            <td class="data-cell">' . $val('rn_peso_egreso') . '</td>
        </tr>
    </table><br>';

    // 11. EGRESO MATERNO
    $html3 .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band"><span class="section-num">11</span>EGRESO MATERNO</td></tr>
        <tr>
            <td width="25%" class="subhead-left">CONDICIÓN DE EGRESO</td>
            <td width="25%" class="data-cell" style="font-weight:bold;">' . $val('madre_egreso_condicion') . '</td>
            <td width="25%" class="subhead-left">FECHA</td>
            <td width="25%" class="data-cell">' . $val('madre_egreso_fecha') . '</td>
        </tr>
        <tr>
            <td class="subhead-left">HORA</td>
            <td class="data-cell">' . $val('madre_egreso_hora') . '</td>
            <td class="subhead-left">ANTICONCEPCIÓN AL ALTA</td>
            <td class="data-cell">' . $val('madre_anticoncepcion') . '</td>
        </tr>
        <tr>
            <td colspan="4" class="subhead-left">DATOS DE RETIRO / OBSERVACIONES</td>
        </tr>
        <tr>
            <td colspan="4" class="data-cell" style="height:45px;">' . $valnl('madre_egreso_obs') . '</td>
        </tr>
    </table><br>';

    // DIAGNÓSTICO
    $html3 .= '
    <table cellspacing="0">
        <tr><td colspan="4" class="section-band">
            <span class="section-num">·</span>DIAGNÓSTICOS (CIE-10)
            <span class="small">  ·  PRE = PRESUNTIVO   ·   DEF = DEFINITIVO</span>
        </td></tr>
        <tr>
            <td width="14%" class="subhead">CIE-10</td>
            <td width="62%" class="subhead">DESCRIPCIÓN</td>
            <td width="12%" class="subhead">PRE</td>
            <td width="12%" class="subhead">DEF</td>
        </tr>
        ' . obtenerDiagnosticosFormat($idatencion) . '
    </table>';

    $pdf->writeHTML($html3, true, false, true, false, '');
    _mspPieFirmaConQR($pdf, $emisor, $qrContent, $qrTimestamp, $estilo, '051', 'HISTORIA CLÍNICA MATERNA PERINATAL · EGRESO');

    return salvarPDF($pdf, 'msp051', $idatencion);
}

/** Helper para MSP-051: dibuja un checkbox con etiqueta marcando si coincide. */
function _msp051CheckLabel($label, $valor)
{
    $marca = (strcasecmp(trim($valor), $label) === 0) ? 'X' : '&nbsp;';
    return '<span style="background:#FFFF99; padding:2px 5px; border:1px solid #555; margin-right:6px;">'
         . $marca . '</span> ' . $label . '  ';
}
