<?php

if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] === $_SERVER['SERVER_ADDR']) {
	$_SESSION['MM_Username'] = 'informes';
}

header('Content-type: application/pdf');
define('PERMITIDO', true);
require_once("../inc/init.php");
require('../lib/valido.php');
require_once('../lib/util.php');
require_once('../lib/connection.php');
require_once("../lib/config.php");
require_once '../Connections/conexionlab.php';
require_once '../pdfClasses/class.ezpdf.php';
require_once '../assets/php/noCache.php';
include('../assets/php/phpqrcode/qrlib.php');
noCache();

ini_set('memory_limit', '256M'); # memoria para crear las imágenes (funciones imagecreatefrompng y imagecreatefromjpeg)
date_default_timezone_set('America/Santiago');

$pdf = new Cezpdf('LETTER');
$pdf->selectFont('../pdfClasses/fonts/Helvetica.afm');
$pdf->ezStartPageNumbers(330, 5, 9, '', 'Página {PAGENUM} de {TOTALPAGENUM}', 1);

$idAtencion = isset($_GET["idate"]) ? $_GET["idate"] : "-1";
# datos de la atención
mysql_select_db($database_conexionlab, $conexionlab);
$query_atencion = "SELECT a.ID_ATENCION, a.ID_CONVENIO, a.FECHA AS FECHA2, DATE_FORMAT(a.FECHA,'%d/%m/%Y') AS FECHA, DATE_FORMAT(p1.FECHA_NACIMIENTO,'%d/%m/%Y') AS FECHA_NACIMIENTO,
DATE_FORMAT(a.FECHA_INF,'%d/%m/%Y') AS FECHA_INF, DATE_FORMAT(p1.FECHA_NACIMIENTO,'%d%m%y') AS F_NAC, p1.NOMBRES, p1.APELLIDO_PATERNO, p1.APELLIDO_MATERNO, p1.GENERO, 
TIMESTAMPDIFF(MONTH, p1.FECHA_NACIMIENTO, a.FECHA) AS EDAD_MES, p2.APELLIDO_PATERNO AS DR, cc.NOMBRE, p1.NRO_RUT, p1.DV_RUT, p1.PASAPORTE, p1.PAIS, p1.FLAG_EXTRANJERO, cg.DESCRIPCION_CG AS PAIS, CONCAT_WS(' ', DATE_FORMAT(a.FECHA_TM, '%d/%m/%Y'), DATE_FORMAT(a.HORA_TM,'%H:%i')) AS HORA_TM, 
CONCAT_WS(' ', DATE_FORMAT(a.FECHA_R, '%d/%m/%Y'), DATE_FORMAT(a.HORA_R, '%H:%i')) AS HORA_R
FROM atenciones a
LEFT JOIN personas p1 ON a.ID_CLIENTE = p1.ID_PERSONA
LEFT JOIN personas p2 ON a.ID_MEDICO = p2.ID_PERSONA
LEFT JOIN centros_contacto cc ON a.ID_CENTRO_CONTACTO = cc.ID_CENTRO_CONTACTO
LEFT JOIN codigos_generales cg ON p1.PAIS = cg.CODIGO AND cg.COD_TABLA = 'SIS_PAIS'
WHERE a.ID_ATENCION = '$idAtencion'";
$atencion = mysql_query($query_atencion, $conexionlab) or die(mysql_error());
$row_atencion = mysql_fetch_assoc($atencion);

# exámenes agrupados por por área del laboratorio
$qAreasAtencion = $mysqli->prepare("SELECT ex.AREA_LAB, cg.DESCRIPCION_CG
FROM examenes_atenciones ea 
INNER JOIN examenes ex ON ea.COD_EXAMEN = ex.COD_INTERNO
LEFT JOIN codigos_generales cg ON ex.AREA_LAB = cg.CODIGO AND cg.COD_TABLA = 'SIS_AREAS' 
WHERE ID_ATENCION = ? AND ea.FECHA_VAL IS NOT NULL 
GROUP BY ex.AREA_LAB 
ORDER BY ea.ID_EXATE ASC");
$qAreasAtencion->bind_param('i', $idAtencion);
$qAreasAtencion->execute();
$qAreasAtencion->bind_result($codigoAreaAtencion, $descripcionAreaAtencion);
$qAreasAtencion->store_result();
$totalRows_areas = $qAreasAtencion->num_rows;

# observaciones de los resultados
mysql_select_db($database_conexionlab, $conexionlab);
$query_obs = "SELECT obs_resultados.OBS FROM obs_resultados WHERE obs_resultados.ID_ATENCION = '$idAtencion' AND obs_resultados.F_INF = '1'";
$obs = mysql_query($query_obs, $conexionlab) or die(mysql_error());
$row_obs = mysql_fetch_assoc($obs);
$totalRows_obs = mysql_num_rows($obs);

mysql_select_db($database_conexionlab, $conexionlab);
$query_pie = "SELECT VALOR FROM parametros_sistema WHERE DESCRIPCION_PS = 'PIE INFORME'";
$pie = mysql_query($query_pie, $conexionlab) or die(mysql_error());
$row_pie = mysql_fetch_assoc($pie);

$logoEmpresa = imagecreatefrompng('../assets/img/logoEmpresaConCertificado.png');
$logo_convenio_atencion = imagecreatefrompng('../assets/img/logo_pcr_rapido.png');
$certificado_sis = imagecreatefrompng('../assets/img/certificacion_sis.png');
$rut_qr = number_format($row_atencion['NRO_RUT'], '0', ',', '.') . '-' . $row_atencion['DV_RUT'];
$pasaporte_qr = $row_atencion['PASAPORTE'];
$nombreImagenCodigoQr = time();
$informacion = "https://ripit.cl/SILCLCE/pacientes/informesPacienteQr.php?rut=" . $rut_qr . "&atencion=" .  $row_atencion['ID_ATENCION'] . "&resultado=mostrar&pasaporte=" . $pasaporte_qr;
QRcode::png($informacion, __DIR__ . '/temp/' . $nombreImagenCodigoQr . '.png', QR_ECLEVEL_M, 4);
$codigo_qr = imagecreatefrompng(__DIR__ . '/temp/' . $nombreImagenCodigoQr . '.png');

$cont = 0;
$resultadoPcr = null;
while ($qAreasAtencion->fetch()) {
	$cont = $cont + 1;
	$pdf->ezSetCmMargins(3, 5.5, 1, 1);
	unset($hemograma); # Se inician todas las áreas de-seteando la variable para hemograma (01.01.045) y orina completa (09.09.022)
	unset($orinacompleta);
	
	# obtener firma de usuario validador del área
	$qFirmasUsuario = $mysqli->prepare("SELECT u.FIRMA 
	FROM examenes_atenciones ea
	INNER JOIN examenes e ON ea.COD_EXAMEN = e.COD_INTERNO
	INNER JOIN usuarios u ON ea.USUARIO_VAL = u.ID_USUARIO 
	WHERE ea.ID_ATENCION = ? AND e.AREA_LAB = ? AND u.FIRMA IS NOT NULL AND ea.USUARIO_VAL != 12 
	GROUP BY ea.USUARIO_VAL");
	$qFirmasUsuario->bind_param('ii', $idAtencion, $codigoAreaAtencion);
	$qFirmasUsuario->execute();
	$qFirmasUsuario->bind_result($archivoFirmaUsuarioValidador);
	$qFirmasUsuario->store_result();
	$qFirmasUsuario->fetch();
	$qFirmasUsuario->close();
	if ($archivoFirmaUsuarioValidador == "") $archivoFirmaUsuarioValidador = "andoni_e.jpg";

	$qExamenesArea = $mysqli->prepare("SELECT ea.COD_EXAMEN, ea.PADRE, ea.RESULTADO, ex.NOMBRE, ex.NOMBRE_INF, ex.METODO, ex.AREA_LAB, ex.TIPO_VARIABLE,
	ex.N_DECIMALES, ex.REFERENCIA, ex.FLAG_AGRUPACION, cg.DESCRIPCION_CG, cg2.DESCRIPCION_CG
	FROM examenes_atenciones ea
	INNER JOIN examenes ex ON ea.COD_EXAMEN = ex.COD_INTERNO
	LEFT JOIN codigos_generales cg ON ex.UNIDAD_MEDIDA = cg.CODIGO AND cg.COD_TABLA = 'SIS_UNIMED'
	LEFT JOIN codigos_generales cg2 ON ex.TIPO_MUESTRA = cg2.CODIGO  AND cg2.COD_TABLA = 'SIS_TIPMUE'
	WHERE ID_ATENCION = ? AND ea.FECHA_VAL IS NOT NULL AND ex.AREA_LAB = ? AND ex.F_INF = 'S'
	ORDER BY cg2.DESCRIPCION_CG, ea.ID_EXATE ASC");
	$qExamenesArea->bind_param('ii', $idAtencion, $codigoAreaAtencion);
	$qExamenesArea->execute();
	$qExamenesArea->bind_result($ea_codExamen, $ea_codigoExamenPadre, $ea_resultado, $ea_nombre, $ea_nombreInforme, $ea_metodo, $ea_areaLaboratorio, $ea_tipoVariable,
	$ea_nroDecimales, $ea_referencia, $ea_flagAgrupacion, $ea_unidadMedida, $ea_tipoMuestra);
	$qExamenesArea->store_result();

	$data = [];
	$data2 = [];

	$tipoMuestra = "";
	$tipoMuestraText = "";

	while ($qExamenesArea->fetch()) {
		$genero = $row_atencion['GENERO'];

		# para cada examen busco sus rangos de validación
		$qRangoValidacion = $mysqli->prepare("SELECT rv.RC_MIN, rv.RC_MAX, rv.RV_MIN, rv.RV_MAX	
		FROM rangos_variables rv
		WHERE rv.COD_INTERNO = ? AND rv.GENERO = ? AND F_REGISTRO <= ? AND (? BETWEEN rv.EDAD_MIN AND rv.EDAD_MAX)
		ORDER BY F_REGISTRO DESC LIMIT 1");
		$qRangoValidacion->bind_param('sssi', $ea_codExamen, $genero, $row_atencion['FECHA2'], $row_atencion['EDAD_MES']);
		$qRangoValidacion->execute();
		$qRangoValidacion->bind_result($rcMin, $rcMax, $rvMin, $rvMax);
		$qRangoValidacion->store_result();
		$qRangoValidacion->fetch();
		$qRangoValidacion->close();

		if ($ea_codExamen == '01.01.045') $hemograma = 1;
		if ($ea_codExamen == '09.09.022') $orinacompleta = 1;
		if ($ea_codExamen == '00.00.069') $resultadoPcr = $ea_resultado;

		$nombreExamen = $ea_nombreInforme != "" ? $ea_nombreInforme : $ea_nombre; # Se muestra el "nombre de informe" en vez del nombre si es que tiene
		if ($ea_codigoExamenPadre != "") $nombreExamen = "      $nombreExamen"; # Si es hijo se muestra con sangría
		if ($ea_flagAgrupacion == 'N' && $ea_metodo != "") $nombreExamen = "$nombreExamen - $ea_metodo"; # Si no es agrupación, se añade al nombre del método
		
		# Numérico
		if ($ea_tipoVariable == 1) {
			$decimales = $ea_nroDecimales != "" ? $ea_nroDecimales : 2;
			if ($ea_unidadMedida == "S/U.M.") $ea_unidadMedida = "";

			$resu = number_format($ea_resultado, $decimales, ',', '.') . " " . $ea_unidadMedida;
			if (is_numeric($rvMin) && ($ea_resultado < $rvMin || $ea_resultado > $rvMax)) $resu = number_format($ea_resultado, $decimales, ',', '.') . " " . $ea_unidadMedida . "*";
			if (!is_numeric($ea_resultado)) $resu = $ea_resultado . " " . $ea_unidadMedida; # creo que este caso no pasa ya que no se pueden ingresar valores no-numéricos en el registro de resultados --- MARCELO

			$rango_val = $ea_referencia;
			if (is_numeric($rvMin) && $ea_referencia == "") $rango_val = number_format($rvMin, $decimales, ',', '.') . " - " . number_format($rvMax, $decimales, ',', '.');
		}
		# Alfanumérico
		if ($ea_tipoVariable == 2) {
			$resu = $ea_referencia == NULL || $ea_resultado == $ea_referencia ? $ea_resultado : "$ea_resultado*";
			$rango_val = $ea_referencia;
		}
		# Texto
		if ($ea_tipoVariable == 3) {
			$resu = $ea_resultado;
			$rango_val = $ea_referencia;
		}
		# Agrupación
		if ($ea_flagAgrupacion == "S") {
			$resu = "";
			$rango_val = "";
		}

		# Si es tipo texto y no es hijo (PADRE: null)
		if ($ea_codigoExamenPadre == NULL && $ea_tipoVariable == 3) {
			if ($tipoMuestraText != $ea_tipoMuestra) {
				$tipoMuestraText = $ea_tipoMuestra;
				$data2[] = array('NOM' => '<b>Tipo de Muestra: ' . $tipoMuestraText . '</b>');
			}
			$data2[] = array('NOM' => $nombreExamen, 'RES' => $resu);
			$mark = 1;
		# Todo lo demás
		} else {
			if ($tipoMuestra != $ea_tipoMuestra) {
				$tipoMuestra = $ea_tipoMuestra;
				$data[] = array('NOM' => '<b>Tipo de Muestra: ' . $tipoMuestra . '</b>');
			}
			$data[] = array('NOM' => $nombreExamen, 'RES' => $resu, 'RANGO' => $rango_val);
			$mark2 = 1;
		}
	} # while exámenes de area


	// Títulos de la tabla si no es texto
	$titles = [
		'NOM' => '<b>Examen</b>',
		'RES' => '<b>Resultado</b>',
		'RANGO' => '<b>Referencia</b>'
	];
	// Opciones de la tabla si no es texto
	$options = [
		'shadeCol' => [0.9, 0.9, 0.9],
		'showLines' => 0,
		'shaded' => 0,
		'xOrientation' => 'center',
		'width' => 560,
		'fontSize' => 8,
		'cols' => array(
			'NOM' => array('justification' => 'left'),
			'RES' => array('justification' => 'left'),
			'RANGO' => array('justification' => 'left', 'width' => 120)
		)
	];

	// Títulos de la tabla si es texto
	$titles2 = [
		'NOM' => '<b>Nombre</b>',
		'RES' => '<b>Resultado</b>'
	];
	// Opciones de la tabla si es texto
	$options2 = [
		'shadeCol' => [0.9, 0.9, 0.9],
		'showLines' => 0,
		'shaded' => 0,
		'xOrientation' => 'center',
		'width' => 560,
		'fontSize' => 8,
		'cols' => array(
			'NOM' => array('justification' => 'left', 'width' => 220),
			'RES' => array('justification' => 'left')
		)
	];

	///////////////////////////////////////////////////////// Informe ///////////////////////////////////////////////////////
	if (isset($_REQUEST['old'])) {
		$header = imagecreatefrompng('../imagenes/header.png');
		$pdf->addImage($header, 0, 739, 612);
	} else {
		# header izquierda
		$pdf->addImage($logoEmpresa, 30, 715, null, 75);
		# header derecha
		$pdf->addText(372, 755, 9, 'Escanea el código QR para verificar');
		$pdf->addText(380, 745, 9, 'la autenticidad del la información');
		$pdf->addImage($codigo_qr, 520, 720, 70);
		# footer izquierda
		if ($row_atencion['ID_CONVENIO'] == 145) {
			$pdf->addImage($logo_convenio_atencion, 18, 55, 75, 30);
			$pdf->addText(100, 75, 9, "<b>Toma de muestra gestionada por: PCR Rápido.</b>", 0, 0);
		}
		$pdf->addText(18, 20, 8, $row_pie['VALOR'], 0, 0);
		# footer derecha
		$pdf->addTextWrap(540, 50, 100, 9, 'Arlegui   440', 'justification');
		$pdf->addTextWrap(540, 40, 100, 9, 'Oficina   218', 'justification');
		$pdf->addTextWrap(540, 30, 100, 9, '(32) 2714189', 'justification');
		$pdf->addTextWrap(540, 20, 100, 9, 'Viña del Mar', 'justification');
		$pdf->setStrokeColor(1, 0, 0);
		$pdf->line(535, 60, 535, 15);
	}

	if ($codigoAreaAtencion == 11) { // Si área es VIH, el nombre del paciente está compuesto por 3 iniciales, fecha de nacimiento y últimos 3 dígitos del RUT más dígito verificador... ej  yo: AEL 230470 679-2
		$inici = substr($row_atencion['NOMBRES'], 0, 1) . substr($row_atencion['APELLIDO_PATERNO'], 0, 1) . substr($row_atencion['APELLIDO_MATERNO'], 0, 1);
		$fnac = $row_atencion['F_NAC'];
		$xrut = substr($row_atencion['NRO_RUT'], -3, 3) . "-" . $row_atencion['DV_RUT'];
		$nombre_paciente = $inici . " " . $fnac . " " . $xrut;
	} else {
		$nombre_paciente = $row_atencion['NOMBRES'] . " " . $row_atencion['APELLIDO_PATERNO'] . " " . $row_atencion['APELLIDO_MATERNO'];
	}

	if ($row_atencion['PASAPORTE'] != "" && !(substr($row_atencion['NRO_RUT'], 0, 2) == "99" && strlen($row_atencion['NRO_RUT']) == 8)) {
		$tipo_identificación = 'RUT:';
		$identificación_paciente = number_format($row_atencion['NRO_RUT'], '0', ',', '.') . '-' . $row_atencion['DV_RUT'];
		$rut_qr = $identificación_paciente;
		$tipo_identificación_2 = 'Pasaporte / DNI:';
		$identificación_paciente_2 = $row_atencion['PAIS'] ? $row_atencion['PASAPORTE'] . ' - ' . $row_atencion['PAIS'] : $row_atencion['PASAPORTE'];
	} else {
		if ($row_atencion['PAIS'] == "") {
			$tipo_identificación = 'RUT:';
			$identificación_paciente = number_format($row_atencion['NRO_RUT'], '0', ',', '.') . '-' . $row_atencion['DV_RUT'];
			$rut_qr = $identificación_paciente;
		} elseif ($row_atencion['PAIS'] != "") {
			$tipo_identificación = 'Pasaporte / DNI:';
			$identificación_paciente = $row_atencion['PASAPORTE'] . ' - ' . $row_atencion['PAIS'];
		}
	}

	$fecha_toma_muestra = $row_atencion['HORA_TM'] . ' h';
	$fecha_recepcion_muestra = $row_atencion['HORA_R'] . ' h';

	if ($row_atencion['GENERO'] == 'F') {
		$titulo_paciente = "SRA(ITA): ";
		$genero1 = "Femenino";
	} else {
		$titulo_paciente  = "SR: ";
		$genero1 = "Masculino";
	}

	$ate = $row_atencion['ID_ATENCION']; // Id de atención
	$cc = $row_atencion['NOMBRE']; // Local
	$medico = $row_atencion['DR']; // Doctor
	$fecha_atencion = $row_atencion['FECHA']; // Fecha de atención
	$fechNac = $row_atencion['FECHA_NACIMIENTO']; // Fecha de nacimiento
	$fecha_informe = $row_atencion['FECHA_INF']; // Fecha de informe

	# Generación de edad en texto
	$date_time_hoy = new DateTime();
	$date_time_fecha_nacimiento = DateTime::createFromFormat('d/m/Y', $fechNac);
	$date_interval_diferencia = $date_time_fecha_nacimiento->diff($date_time_hoy);
	$edad = "{$date_interval_diferencia->y} a, {$date_interval_diferencia->m} m";

	if ($row_atencion['PASAPORTE'] != "" && !(substr($row_atencion['NRO_RUT'], 0, 2) == "99" && strlen($row_atencion['NRO_RUT']) == 8)) {
		$contenidoTablaAtencion = [
			['1' => $titulo_paciente, '2' => $nombre_paciente, '3' => "Fecha atención:", '4' => $fecha_atencion],
			['1' => $tipo_identificación, '2' => $identificación_paciente, '3' => "Toma de muestra:", '4' => $fecha_toma_muestra],
			['1' => $tipo_identificación_2, '2' => $identificación_paciente_2, '3' => "Recepción de muestra:", '4' => $fecha_recepcion_muestra],
			['1' => "Fecha de Nac.:", '2' => "$fechNac - $edad - $genero1", '3' => "Fecha informe:", '4' => $fecha_informe],
			['1' => "Nro. Atención:",	'2' => $ate . " / " . $cc, '3' => "", '4' => ""],
			['1' => "Solicitante:", '2' => $medico, '3' => "", '4' => ""]
		];
	} else {
		$contenidoTablaAtencion = [
			['1' => $titulo_paciente, '2' => $nombre_paciente, '3' => "Fecha atención:", '4' => $fecha_atencion],
			['1' => $tipo_identificación, '2' => $identificación_paciente, '3' => "Toma de muestra:", '4' => $fecha_toma_muestra],
			['1' => "Fecha de Nac.:", '2' => "$fechNac - $edad - $genero1", '3' => "Recepción de muestra:", '4' => $fecha_recepcion_muestra],
			['1' => "Nro. Atención:",	'2' => $ate . " / " . $cc, '3' => "Fecha informe:", '4' => $fecha_informe],
			['1' => "Solicitante:", '2' => $medico, '3' => "", '4' => ""]
		];
	}
	$titulosTablaAtencion = [
		"1" => "",
		"2" => "",
		"3" => "",
		"4" => ""
	];
	$opcionesTablaAtencion = [
		'shadeCol' => array(0.9, 0.9, 0.9),
		'showLines' => 0,
		'shaded' => 0,
		'showHeadings' => 0,
		'xOrientation' => 'center',
		'width' => 550,
		'rowGap' => 1,
		'fontSize' => 8,
		'cols' => array(
			'1' => array('justification' => 'left', 'width' => 75),
			'2' => array('justification' => 'left', 'width' => 245),
			'3' => array('justification' => 'left', 'width' => 130),
			'4' => array('justification' => 'left', 'width' => 100)
		)
	];

	$pdf->ezTable($contenidoTablaAtencion, $titulosTablaAtencion, '', $opcionesTablaAtencion);
	$pdf->ezText("_____________________________________________________________________________________________________________________________________________________________________", 6, array('justification' => 'center'));
	$pdf->ezText("$descripcionAreaAtencion\n", 9, array('justification' => 'center')); # TITULO DE AREA
	if (isset($mark2)) $pdf->ezTable($data, $titles, '', $options);
	if (isset($mark))	 $pdf->ezTable($data2, $titles2, '', $options2);

	$pdf->ezText("_____________________________________________________________________________________________________________________________________________________________________", 6, array('justification' => 'center'));
	if (substr($resultadoPcr, 0, 8) == "POSITIVO") {
		$pdf->ezText("\nEstimado paciente, usted debe consultar a un médico para que lo oriente en los cuidados que debe tener, para que ingrese su caso en Epivigila, y para que le emita una licencia médica si corresponde.", 8);
	}

	$pdf->ezSetCmMargins(3, 1.5, 0, 0);
	$pdf->ezText("\n", 9, array('justification' => 'center'));
	$pdf->ezColumnsStart(["num" => 2, "gap" => 100]); # inicio del modo "columnas", num = numero de columnas, gap = distancia entre columnas
	$pdf->ezImage("../firmas/$archivoFirmaUsuarioValidador", 0, 110, 'none', 'right');
	$pdf->ezNewPage(); # esto representa cambio de una columna a otra
	$pdf->ezImage("../firmas/director_andoni_etcheverry.jpg", 0, 120, 'none', 'left'); // director_francisca_martinez.jpg
	$pdf->ezColumnsStop(); # fin del modo "columnas"
	# $pdf->ezText("ward test: $cont $totalRows_areas", 9, array('justification' => 'center'));

	if (isset($hemograma)) {
		$nota = "Nota: +     : Leve/Escaso
			++   : Moderado/Regular cantidad
			+++ : Marcado/Abundante";
		$pdf->addText(18, 40, 7, $nota, 0, 0);
		$pdf->addText(18, 30, 7, "Método: Analizador automatizado Mindray M-5380/Microscopía", 0, 0);
	}

	if (isset($orinacompleta)) {
		$nota = "Nota: +        : Escaso
			++     : Regular cantidad
			+++   : Abundante";
		$pdf->addText(18, 40, 7, $nota, 0, 0);
	}

	if ($cont < $totalRows_areas) {
		$pdf->ezNewPage();
	}
	unset($mark);
	unset($mark2);
} // Fin de while áreas

// Mostrar observaciones al final de la hoja
if ($totalRows_obs > 0 && $row_obs['OBS'] != NULL) {
	$pdf->ezText("\n\nObservaciones:\n", 9);
	do {
		$pdf->ezText("- " . $row_obs['OBS'], 9);
	} while ($row_obs = mysql_fetch_assoc($obs));
}

# Hoja adicional de resultado PCR en inglés.
if ($resultadoPcr) {
	$pdf->ezNewPage();
	$pdf->ezSetCmMargins(3, 5.5, 1, 1);

	$pdf->addImage($logoEmpresa, 30, 715, null, 75);;
	$pdf->addTextWrap(540, 65, 100, 9, 'Arlegui   440', 'justification');
	$pdf->addTextWrap(540, 55, 100, 9, 'Oficina   218', 'justification');
	$pdf->addTextWrap(540, 45, 100, 9, '(32) 2714189', 'justification');
	$pdf->addTextWrap(540, 35, 100, 9, 'Viña del Mar', 'justification');
	$pdf->setStrokeColor(1, 0, 0);
	$pdf->line(535, 75, 535, 30);

	# datos de la atención en inglés 
	$titulo_paciente = ($row_atencion['GENERO'] == 'M' ? 'Mr.:' : 'Ms.:');
	$nombre_paciente = $row_atencion['NOMBRES'] . ' ' . $row_atencion['APELLIDO_PATERNO'] . ' ' . $row_atencion['APELLIDO_MATERNO'];

	if ($row_atencion['PASAPORTE'] != "" && !(substr($row_atencion['NRO_RUT'], 0, 2) == "99" && strlen($row_atencion['NRO_RUT']) == 8)) {
		$tipo_identificación = 'RUT:';
		$identificación_paciente = number_format($row_atencion['NRO_RUT'], '0', ',', '.') . '-' . $row_atencion['DV_RUT'];
		$tipo_identificación_2 = 'Passport / DNI:';
		$identificación_paciente_2 = $row_atencion['PAIS'] ? $row_atencion['PASAPORTE'] . ' - ' . $row_atencion['PAIS'] : $row_atencion['PASAPORTE'];
	} else {
		if ($row_atencion['PAIS'] == "") {
			$tipo_identificación = 'RUT:';
			$identificación_paciente = number_format($row_atencion['NRO_RUT'], '0', ',', '.') . '-' . $row_atencion['DV_RUT'];
		} elseif ($row_atencion['PAIS'] != "") {
			$tipo_identificación = 'Passport / DNI:';
			$identificación_paciente = $row_atencion['PASAPORTE'] . ' - ' . $row_atencion['PAIS'];
		}
	}

	$date_time_fecha_nacimiento = DateTime::createFromFormat('d/m/Y', $row_atencion['FECHA_NACIMIENTO']);
	$fecha_nacimiento = $date_time_fecha_nacimiento->format('F jS, Y');
	$médico = $row_atencion['DR'] == 'PARTICULAR' ? 'PARTICULAR ATTENTION' : '<b>M.D. </b>' . $row_atencion['DR'];
	$date_time_fecha_atención = DateTime::createFromFormat('d/m/Y', $row_atencion['FECHA']);
	$fecha_atencion = $date_time_fecha_atención->format('F jS, Y');
	$date_time_fecha_toma_muestra = DateTime::createFromFormat('d/m/Y H:i', $row_atencion['HORA_TM']);
	$fecha_toma_muestra = $date_time_fecha_toma_muestra->format('F jS, Y. H:i');
	$date_time_fecha_recepción_muestra = DateTime::createFromFormat('d/m/Y H:i', $row_atencion['HORA_R']);
	$fecha_recepcion_muestra = $date_time_fecha_recepción_muestra->format('F jS, Y. H:i');
	$date_time_fecha_informe = DateTime::createFromFormat('d/m/Y', $row_atencion['FECHA_INF']);
	$fecha_informe = $date_time_fecha_informe->format('F jS, Y');

	if ($row_atencion['PASAPORTE'] != "" && !(substr($row_atencion['NRO_RUT'], 0, 2) == "99" && strlen($row_atencion['NRO_RUT']) == 8)) {
		$contenidoTablaAtencionIngles = [
			['1' => $titulo_paciente, '2' => $nombre_paciente, '3' => 'Attention date:', '4' => $fecha_atencion],
			['1' => $tipo_identificación, '2' => $identificación_paciente, '3' => "Sample collection date:", '4' => $fecha_toma_muestra],
			['1' => $tipo_identificación_2, '2' => $identificación_paciente_2, '3' => 'Sample reception date:', '4' => $fecha_recepcion_muestra],
			['1' => 'Birthdate: ', '2' => $fecha_nacimiento, '3' => 'Report date:', '4' => $fecha_informe],
			['1' => 'Attention ID: ', '2' => $idAtencion, '3' => '', '4' => ''],
			['1' => 'Doctor:', '2' => $médico, '3' => '', '4' => '']
		];
	} else {
		$contenidoTablaAtencionIngles = [
			['1' => $titulo_paciente, '2' => $nombre_paciente, '3' => 'Attention date:', '4' => $fecha_atencion],
			['1' => $tipo_identificación, '2' => $identificación_paciente, '3' => "Sample collection date:", '4' => $fecha_toma_muestra],
			['1' => 'Birthdate: ', '2' => $fecha_nacimiento, '3' => 'Sample reception date:', '4' => $fecha_recepcion_muestra],
			['1' => 'Attention ID: ', '2' => $idAtencion, '3' => 'Report date:', '4' => $fecha_informe],
			['1' => 'Doctor:', '2' => $médico, '3' => '', '4' => '']
		];
	}
	$titulosTablaAtencionIngles = [
		"1" => "",
		"2" => "",
		"3" => "",
		"4" => ""
	];
	$opcionesTablaAtencionIngles = [
		'shadeCol' => [0.9, 0.9, 0.9],
		'showLines' => 0,
		'shaded' => 0,
		'showHeadings' => 0,
		'xOrientation' => 'center',
		'width' => 550,
		'rowGap' => 1,
		'fontSize' => 8,
		'cols' => [
			'1' => ['justification' => 'left', 'width' => 75],
			'2' => ['justification' => 'left', 'width' => 225],
			'3' => ['justification' => 'left', 'width' => 130],
			'4' => ['justification' => 'left', 'width' => 120]
		]
	];

	$resultadoPcr = strtoupper(trim($resultadoPcr));
	if (substr($resultadoPcr, 0, 8) === 'NEGATIVO') $resultadoPcr = 'NEGATIVE';
	if (substr($resultadoPcr, 0, 8) === 'POSITIVO') $resultadoPcr = 'POSITIVE';
	if (substr($resultadoPcr, 0, 13) === 'INDETERMINADO') $resultadoPcr = 'INDETERMINATE';
	if (substr($resultadoPcr, 0, 8) === 'INVALIDO') $resultadoPcr = 'INVALID';
	$resultadoPcr .= "\n\nReference value: NEGATIVE\nSample: Nasopharyngeal Swab\nMethod: Real-time polymerase chain reaction (RT-PCR)\nLaboratory validated by Chile's Institute of Public Health (ISP) on June 26th, 2020";

	$contenidoTablaExamenesAreaIngles = [];
	$contenidoTablaExamenesAreaIngles[] = ['NOM' => '<b>Sample Type: Nasopharyngeal Swab</b>'];
	$contenidoTablaExamenesAreaIngles[] = ['NOM' => 'CORONAVIRUS COVID-19 RT-PCR', 'RES' => $resultadoPcr];
	$titulosTablaExamenesAreaIngles = [
		'NOM' =>
		'<b>Name</b>',
		'RES' => '<b>Result</b>'
	];
	$opcionesTablaExamenesAreaIngles = [
		'shadeCol' => [0.9, 0.9, 0.9],
		'showLines' => 0,
		'shaded' => 0,
		'xOrientation' => 'center',
		'width' => 560,
		'fontSize' => 8,
		'cols' => ['NOM' => ['justification' => 'left', 'width' => 220], 'RES' => ['justification' => 'left']]
	];

	$pdf->ezTable($contenidoTablaAtencionIngles, $titulosTablaAtencionIngles, "", $opcionesTablaAtencionIngles);
	$pdf->ezText('_____________________________________________________________________________________________________________________________________________________________________', 6, ['justification' => 'center']);
	$pdf->ezText('MOLECULAR BIOLOGY - PCR REPORT' . "\n", 9, ['justification' => 'center']);
	$pdf->ezTable($contenidoTablaExamenesAreaIngles, $titulosTablaExamenesAreaIngles, '', $opcionesTablaExamenesAreaIngles);
	$pdf->ezText('_____________________________________________________________________________________________________________________________________________________________________', 6, ['justification' => 'center']);

	$pdf->ezSetCmMargins(3, 1.5, 0, 0);
	$pdf->ezText("\n", 9, array('justification' => 'center'));
	$pdf->ezColumnsStart(["num" => 2, "gap" => 100]);
	$pdf->ezImage("../firmas/ing_$archivoFirmaUsuarioValidador", 0, 110, 'none', 'right');
	$pdf->ezNewPage();
	$pdf->ezImage("../firmas/director_andoni_etcheverry.jpg", 0, 120, 'none', 'left');
	$pdf->ezColumnsStop();
}

ob_end_clean();
unlink(__DIR__ . '/temp/' . $nombreImagenCodigoQr . '.png');
$pdf->addInfo([
	'Title' => 'Informe de Resultados al Paciente',
	'Author' => 'SILCL RIPIT',
	'Subject' => "Resultados de la atención $idAtencion",
	'Creator' => "",
	'Producer' => "www.ripit.cl"
]);
$pdf->ezStream(["Content-Disposition" => "Atencion_$idAtencion.pdf"]);
