<?php
namespace App\Controllers;

class PrintResult extends BaseController {

	function checkRange($input, $normal_range) {
		// Ekstrak angka dari input dan default menggunakan regex
		if (!preg_match('/^(\d+)\s*-\s*(\d+)$/', $input, $inputMatches) ||
			!preg_match('/^(\d+)\s*-\s*(\d+)$/', $normal_range, $defaultMatches)) {
			return false; // Jika format tidak sesuai, return false
		}
	
		// Konversi ke integer
		$inputMin = (int) $inputMatches[1];
		$inputMax = (int) $inputMatches[2];
		$defaultMin = (int) $defaultMatches[1];
		$defaultMax = (int) $defaultMatches[2];
	
		// Cek apakah input berada dalam batas default
		if ($inputMin < $defaultMin || $inputMax > $defaultMax) {
			return 'AB';
		}
	
		return true;
	}

	// public function pdfViewerOld($resultData, $data, $note) {

	// 	// Mengetahui Apakah User Login adalah Bali atau Surabaya
	// 	$cityid = session()->get('usercityid');

	// 	// Digunakan untuk mengetahui user yang melakukan Validasi khusus analis surabaya
	// 	foreach($resultData as $result) {
	// 		$uservalidator = $result['validator'];
	// 		break;
	// 	}

	// 	if ($cityid == 1) {

	// 		if ($uservalidator != null){
	// 			$doctor = "dr. I Komang Parwata Sp.PK";
	// 			$analyst = "Mrs. Gusti Ayu Riska Mastari";
	// 			$noreg = "Reg. No: 570/SIPDS/0001/I/DPMPTSP/2023";
	// 			$signature = "<img src='http://cmod.id/assets/img/ttd_dr_komang.png' alt=''>";
	// 			$enteredby = "<td><u>Entered By</u></td>";
	// 			$labtech = "<td>Lab Technician</td>";
	// 			$verifiedby = "<td align='right'><u>Verified By</u></td>";

	// 		} else {
	// 			$verifiedby = "<td align='right' class='red_font'><b><u>Waiting for Validation</u></b></td>";
	// 			$enteredby = "<td class='red_font'><b><u>Waiting for Validation</u></b></td>";
	// 			$labtech = "<td></td>";
	// 			$doctor = "";
	// 			$analyst = "";
	// 			$noreg = "";
	// 			$signature = "";
	// 		}
			
	// 	} elseif ($cityid == 2) {

	// 		if ($uservalidator == "MG") {
	// 			$doctor = "dr. I.G.A.A Putri Sri Rejeki, Sp.PK";
	// 			$noreg = "SIP : 503.446/1091/B/IP.DS/436.7.15/2022";
	// 			$signature = "<img id='ttd_p' src='http://cmod.id/assets/img/ttd_dr_putri.jpg' alt=''>";
	// 			$enteredby = "<td><u>Entered By</u></td>";
	// 			$labtech = "<td>Lab Technician</td>";
	// 			$analyst = "Mrs. Mega Rahayu Ningsih";
	// 			$verifiedby = "<td align='right'><u>Verified By</u></td>";
	// 		} else if ($uservalidator == "ACP") {
	// 			$doctor = "dr. I.G.A.A Putri Sri Rejeki, Sp.PK";
	// 			$noreg = "SIP : 503.446/1091/B/IP.DS/436.7.15/2022";
	// 			$signature = "<img id='ttd_p' src='http://cmod.id/assets/img/ttd_dr_putri.jpg' alt=''>";
	// 			$enteredby = "<td><u>Entered By</u></td>";
	// 			$labtech = "<td>Lab Technician</td>";
	// 			$analyst = "Mrs. Afrita Catur Pratiwi";
	// 			$verifiedby = "<td align='right'><u>Verified By</u></td>";
	// 		} else {
	// 			$verifiedby = "<td align='right' class='red_font'><b><u>Waiting for Validation</u></b></td>";
	// 			$enteredby = "<td class='red_font'><b><u>Waiting for Validation</u></b></td>";
	// 			$labtech = "<td></td>";
	// 			$doctor = "";
	// 			$analyst = "";
	// 			$noreg = "";
	// 			$signature = "";
	// 		}

	// 	} else { //Jika Login Adalah Sistem dan tidak punya city id
	// 		$verifiedby = "<td align='right' class='red_font'><b><u>LISFSE/SYSTEM/ADMIN</u></b></td>";
	// 		$enteredby = "<td class='red_font'><b><u>LISFSE/SYSTEM/ADMIN</u></b></td>";
	// 		$labtech = "<td></td>";
	// 		$doctor = "";
	// 		$analyst = "";
	// 		$noreg = "";
	// 		$signature = "";
	// 	}

	// 	if ($data[0] != null) {

	// 		$accessnumber = $data[0]['SP_ACCESSNUMBER'];
			
	// 		$sex = $data[0]['SEX'] == 1 ? "Male" : "Female";
			
	// 		$rm_number = $data[0]['PATNUMBER'];
	// 		$rm_number = substr($rm_number, -10);

	// 		$first_name = $data[0]['FIRSTNAME'];
	// 		$last_name = $data[0]['NAME'];
			
	// 		$birth_date = $data[0]['BIRTHDATE'];
	// 		$birth_date = \DateTime::createFromFormat('Y-m-d H:i:s.u', $birth_date);
	// 		if ($birth_date) { $birth_date = $birth_date->format('d-m-Y'); }

	// 		$hostordernumber = $data[0]['HOSTORDERNUMBER'];
			
	// 		$collection_date = $data[0]['COLLECTIONDATE'];
	// 		$dateTimeCol = \DateTime::createFromFormat('Y-m-d H:i:s.u', $collection_date);
	// 		if ($dateTimeCol) {
	// 			$collection_date = $dateTimeCol->format('d-m-Y H:i');
	// 		}

	// 		$result_date = end($resultData);
	// 		$result_date = $result_date["RESDATE_FIX"];
	// 		$dateTimeRes = \DateTime::createFromFormat('Y-m-d H:i:s.u', $result_date);
	// 		if ($dateTimeRes) {
	// 			$result_date = $dateTimeRes->format('d-m-Y H:i');
	// 		}
			
	// 	} else {
	// 		$sex ='';
	// 		$accessnumber = "";
	// 		$rm_number = "";
	// 		$first_name = "";
	// 		$last_name = "";
	// 		$birth_date = "";
	// 		$hostordernumber = "";
	// 		$collection_date = "";
	// 		$result_date = "";
	// 	}
		
	// 	$fullPage="";
	// 	$headPage = "
	// 	<div id='page'>
	// 		<div id='pagetop' style='height:0.01cm'> </div>
	
	// 		<div id='dinfo'>
	
	// 			<table class='information t_center'>
	// 				<tr>
	// 					<th class='padmaColor' colspan='6' align='center'>CLINICAL LABORATORY</th>
	// 				</tr>

	// 				<tr>
	// 					<th style='width:18%' align='left'>RM Number</th>
	// 					<td style='width:2%'>:</td>
	// 					<td style='width:35%'>$rm_number</td>
	// 					<th style='width:18%' align='left'>Visit Number</th>
	// 					<td style='width:2%'>:</td>
	// 					<td style='width:35%'>$hostordernumber</td>
	// 				</tr>
	
	// 				<tr>
	// 					<th align='left'>First Name</th>
	// 					<td>:</td>
	// 					<td>$first_name</td>
	// 					<th align='left'>Request Number</th>
	// 					<td>:</td>
	// 					<td>$accessnumber</td>
	// 				</tr>
	
	// 				<tr>
	// 					<th align='left'>Last Name</th>
	// 					<td>:</td>
	// 					<td>$last_name</td>
	// 					<th align='left'>Order Date/Time</th>
	// 					<td>:</td>
	// 					<td>$collection_date</td>
	// 				</tr>
	// 				<tr>
	// 					<th align='left'>DoB/Gender</th>
	// 					<td>:</td>
	// 					<td>$birth_date / $sex</td>
	// 					<th align='left'>Result Date/Time</th>
	// 					<td>:</td>
	// 					<td>$result_date</td>
	// 				</tr>
	
	// 			</table>
			
	// 		</div>
			
	// 		<div id='dresult'>
	// 		<br>
	// 			<table class='result t_center'>
					
	// 				<tr align='left'>
	// 					<th class='padmaColor' style='width:35%'>Parameter</th>
	// 					<th class='padmaColor' style='width:1%'> </th>
	// 					<th class='padmaColor' style='width:20%'>Result</th>
	// 					<th class='padmaColor' style='width:12%'>Unit</th>
	// 					<th class='padmaColor' style='width:20%'>Normal Range</th>
	// 					<th class='padmaColor' style='width:12%'>Sample</th>
	// 				</tr>
	// 		";
	
	// 	$resultTest ="";

	// 	// Untuk Collection
	// 	if ($data[1] != null) {			
	// 		$colltext = '';
	// 		$recvtext = '';
	// 		$qcolldate = '';
	// 		$qcolltime = '';
	// 		$qrecvdate = '';
	// 		$qrecvtime = '';
	// 		foreach ($data[1] as $item) {
	// 			$samp = $item['SHORTTEXT'];
	// 			$colldate = $item['colldate'];
	// 			$recvdate = $item['recvdate'];
	// 			$colltime = $item['colltime'];
	// 			$recvtime = $item['recvtime'];
	// 			if($colldate !='') {
	// 				if($colldate != $qcolldate) { $colltext .= "$colldate $colltime $samp"; $qcolldate = $colldate; $qcolltime = $colltime; }
	// 				else {
	// 					if($colltime != $qcolltime) { $colltext .= ", $colltime $samp"; $qcolltime = $colltime; }
	// 					else { $colltext .= ", $samp"; }
	// 				}
	// 			}
	// 			if($recvdate !='') {
	// 				if($recvdate != $qrecvdate) { $recvtext .= "$recvdate $recvtime $samp"; $qrecvdate = $recvdate; $qrecvtime = $recvtime; }
	// 				else {
	// 					if($recvtime != $qrecvtime) { $recvtext .= ", $recvtime $samp"; $qrecvtime = $recvtime; }
	// 					else { $recvtext .= ", $samp"; }
	// 				}
	// 			}
	// 		}
	// 	}
		
	// 	$resultNoteandSpecimen = "
	// 			<br>
	
	// 			<table class='result t_center'>
	// 				<tr>
	// 					<th align='left' class='padmaColor'>Notes</th>
	// 				</tr>
	// 				<tr>
	// 					<td>
	// 					".$note."
	// 					</td>
	// 				</tr>
	// 			</table>
				
	// 			<br>
				
	// 			<table class='t_center table_collection' >
	// 				<tr>
	// 					<td width='15%'>Collection datetime : </td>
	// 					<td>$colltext</td>
	// 				</tr>
	// 				<tr>
	// 					<td>Reception datetime : </td>
	// 					<td>$recvtext</td>
	// 				</tr>
	// 			</table>
	// 	";
	// 	$footerPage = "
	// 	<div id='footer'>
	// 		<table class='table_footer t_center'>
	// 			<tr>
	// 				<td></td>
	// 				<td align='right'>".$signature."</td>
	// 			</tr>
	// 			<tr>
	// 				".$enteredby
	// 				.$verifiedby."
	// 			</tr>
	// 			<tr>
	// 				".$labtech."
	// 				<td align='right'>".$doctor."</td>
	// 			</tr>
	// 			<tr>
	// 				<td>".$analyst."</td>
	// 				<td align='right'>".$noreg."</td>
	// 			</tr>
	// 		</table>
	// 	</div>
	// 	";
	// 	$lastDiv="</div>";

    //     $tempChapEng = "";
    //     $tempChapInd = "";

	// 	$i=0;
	// 	foreach ($resultData as $item) {

	// 		// Untuk Spasi Depth
	// 		$space="";
	// 		if ($item['RESULT'] != null) {
	// 			$j=0;

	// 			$space.="&nbsp;";
	// 			for ($j=0; $j<=$item['DEPTH']; $j++) {
	// 				$space .= "&nbsp;&nbsp;";
	// 			}
	// 			if ($item['DEPTH']==0){
	// 				$space.="&nbsp;";
	// 			}
				
	// 		} else {

	// 			for ($j=0; $j<=$item['DEPTH']; $j++) {
	// 				$space .= "&nbsp;&nbsp;";
	// 			}

	// 		}

	// 		// Untuk Penamaan Serum Khusus test
	// 		if ($item["RESULT"] == null) {
	// 			$serum_type = "";
	// 		}else {
	// 			$serum_type = $item["serum_type"];
	// 		}

	// 		$resflag = $item["RESFLAG"] == "N" ? '' : $item["RESFLAG"];
			
    //         if ($tempChapEng != $item['chap_eng']) {
    //             $tempChapEng = $item['chap_eng'];
    //             $tempChapInd = $item['chap_ind'];
                
    //             $i++;

	// 			// Melebihi batas Kertas
	// 			if($i % 25 == 0) {
	// 				$resultTest .= "</table></div>";
	// 				$fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;
	// 				$i=0;
	// 				$resultTest = "";
	// 			}
				
	// 			if($i==0){
	// 				$i++;
	// 			}
	// 			// Untuk Chapter
	// 			$resultTest .= "
	// 				<tr align='left' class='chapter'>
	// 					<td colspan='5'>
	// 						<pre><b>".$tempChapEng."</b></pre>
	// 						<!-- <pre><b>".$i.". ".$tempChapEng."</b></pre> -->
	// 					</td>
	// 				</tr>
	// 			";
    //         }

    //         // Melebihi batas Kertas
    //         if($i % 25 == 0 && $i!=0) {
    //             $resultTest .= "</table></div>";
    //             $fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;
    //             $i=0;
    //             $resultTest = "";
    //         }

    //         $i++;
    //         if ($item['RESTYPE'] == "CE"){
    //             $resvalue = $item['RESULT'];
    //         } else if ($item['RESTYPE'] == null) {
	// 			$resvalue = $item['RESULT'];
	// 		} else {
    //             $resvalue = $item['RESVALUE'];
    //         }
	// 		$reff = $item["REFRANGE"];
	// 		$refftext = $item["REFFTEXT"];
	// 		if($refftext !='') {$reff = $refftext;}
	// 		$unit = $item['UNIT'];
	// 		$unittext = $item['UNITTEXT'];
	// 		if($unittext !='') {$unit = $unittext;}
			
	// 		// Untuk mewarnai value yang tidak beda dengan nilai normal
	// 		$color = "";
	// 		if ($resflag == 'L' || $resflag == 'H') {
	// 			$color = "red_font";
	// 		}

	// 		// Hanya Untuk Yang Kode Nya Adalah CODE/CM
	// 		$range = $this->checkRange($item['RESULT'], $item['REFFTEXT']);
	// 		if ($item['code_type'] == 6 && $item['REFFTEXT'] != null) {
				
	// 			if ($range == true) { // Jika nilai masih dalam rentang nilai normal misal : 0 - 1
	// 				$color = "";
	// 			} elseif ($range == false) { // Jika nilai bukan merupakan rentang alias hanya code
	// 				$redWord = ["positive", "reactive"];
	// 				if (in_array(strtolower($item['RESULT']), $redWord)) {
	// 					$color = "red_font";
	// 				}
	// 			} 
	// 			else { // Jika Rentang diatas nilai normal
	// 				$color = "red_font";
	// 			}
	// 		}

	// 		// Hanya Untuk Kondisi Ada Komentar Dibawah Result
	// 		if ($item['RESCOMMENT'] != null) {
	// 			$redWord = ["positive", "reactive", "pos", "reac"];
	// 			if (in_array(strtolower($item['RESCOMMENT']), $redWord)) {
	// 				$color = "red_font";
	// 			}

	// 			$comment = $item['RESCOMMENT'];
	// 			// Kondisi Sangat Khusus 
	// 			if ($item['RESCOMMENT'] == "NREAC") { 
	// 				$comment = "Non Reactive";
	// 			} else if ($item['RESCOMMENT'] == "REAC") { 
	// 				$comment = "Reactive";
	// 			}
	// 			$rescomment = "<br><i>" . $comment . "</i>";
			
	// 		} else {
	// 			$rescomment = "";
	// 		}


	// 		$test = "";
	// 		// Untuk Nama Test Apakah lebih dari 25 karaktera
	// 		if ( strlen($item['test_eng']) > 25 || strlen($item['test_ind']) > 25) {
	// 			$test = "<pre>" . $space . $item["test_eng"]."<br>$space<small><i>".$item["test_ind"]."</i></small></pre>";
	// 		} else {
	// 			$test = "<pre>" . $space . $item["test_eng"]." "."<small><i>".$item["test_ind"]."</i></small></pre>";
	// 		}

	// 		if ($item['code_type'] == 5) {
	// 			$resultTest .= "
	// 				<tr>
	// 					<td colspan='1' class=''>
	// 						".$test."
	// 					</td>
	// 					<td class='".$color."'>" . $resflag . "</td>
	// 					<td colspan='3' class='".$color."'>" . $resvalue . $rescomment ."</td>
	// 					<td class=''>" . $serum_type . "</td>
	// 				</tr>
	// 			";
	// 		} else {
	// 			$resultTest .= "
	// 				<tr>
	// 					<td colspan='1' class=''>
	// 						".$test."
	// 					</td>
	// 					<td class='".$color."'>" . $resflag . "</td>
	// 					<td class='".$color."'>" . $resvalue .  $rescomment ."</td>
	// 					<td class=''>" . "<pre>" .$unit. "<pre>" . "</td>
	// 					<td class=''>" . "<pre>" .$reff. "<pre>" . "</td>
	// 					<td class=''>" . $serum_type . "</td>
	// 				</tr>
	// 			";
	// 		}
			
			
            
    //         // Melebihi batas Kertas
    //         if($i % 25 == 0 && $i != 0) {
    //             $resultTest .= "</table></div>";
    //             $fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;
    //             $i=0;
    //             $resultTest = "";
    //         }
	
	// 	}

	// 	$resultTest .= "
	// 			</table>
	// 			".$resultNoteandSpecimen."
	// 			</div>";
		
	// 	$fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;

	// 	return $fullPage;
	// }

	public function pdfViewerNew($resultData, $data, $note) {

		// Mengetahui Apakah User Login adalah Bali atau Surabaya
		$cityid = session()->get('usercityid');

		// Digunakan untuk mengetahui user yang melakukan Validasi khusus analis surabaya
		foreach($resultData as $result) {
			$uservalidator = $result['validator'];
			break;
		}

		// Untuk Membedakan Laporan Bali dan Surabaya
		$hostordernumber = $data[0]['HOSTORDERNUMBER'];
		if ($hostordernumber[0] == 'B' || $hostordernumber[0] == 'Z') {

			if ($uservalidator != null){
				$doctor = "dr. I Komang Parwata, SpPK Subsp.B.D.K.T.(K)";
				$analyst = "Mrs. Gusti Ayu Riska Mastari";
				$noreg = "Reg. No: 570/SIPDS/0001/I/DPMPTSP/2023";
				$signature = "<td class='margin_right_img_bali'><img id='ttd_k' src='http://cmod.id/assets/img/ttdnewdokpar3.png' alt=''></td>";
				$enteredby = "<td><u>Entered By</u></td>";
				$labtech = "<td>Lab Technician</td>";
				$verifiedby = "<td class='margin_right'><u>Verified By</u></td>";

			} else {
				$verifiedby = "<td align='right' class='red_font'><b><u>Waiting for Validation</u></b></td>";
				$enteredby = "<td class='red_font'><b><u>Waiting for Validation</u></b></td>";
				$labtech = "<td></td>";
				$doctor = "";
				$analyst = "";
				$noreg = "";
				$signature = "<td class='margin_right'></td>";
			}
			
		} elseif ($hostordernumber[0] == 'S' || $hostordernumber[0] == 'X') {

			$doctor = "dr. I.G.A.A Putri Sri Rejeki, Sp.PK";
			$noreg = "SIP : 503.446/1091/B/IP.DS/436.7.15/2022";
			$signature = "<td class='margin_right_sby_img'><img id='ttd_p' src='http://cmod.id/assets/img/ttd_dr_putri.jpg' alt=''></td>";
			$enteredby = "<td><u>Entered By</u></td>";
			$labtech = "<td>Lab Technician</td>";
			$verifiedby = "<td class='margin_right_sby'><u>Verified By</u></td>";

			if ($uservalidator == "MG") {
				$analyst = "Mrs. Mega Rahayu Ningsih";
			} else if ($uservalidator == "ACP") {
				$analyst = "Mrs. Afrita Catur Pratiwi";
			} else {
				$verifiedby = "<td align='right' class='red_font'><b><u>Waiting for Validation</u></b></td>";
				$enteredby = "<td class='red_font'><b><u>Waiting for Validation</u></b></td>";
				$labtech = "<td></td>";
				$doctor = "";
				$analyst = "";
				$noreg = "";
				$signature = "<td class='margin_right'></td>";
			}

		} 
		else { //Jika Login Adalah Sistem dan tidak punya city id
			$verifiedby = "<td align='right' class='red_font'><b><u>LISFSE/SYSTEM/ADMIN</u></b></td>";
			$enteredby = "<td class='red_font'><b><u>LISFSE/SYSTEM/ADMIN</u></b></td>";
			$labtech = "<td></td>";
			$doctor = "";
			$analyst = "";
			$noreg = "";
			$signature = "<td class='margin_right'></td>";
		}

		// Khusus untuk value Header
		if ($data[0] != null) {

			$accessnumber = $data[0]['SP_ACCESSNUMBER'];
			
			$sex = $data[0]['SEX'] == 1 ? "Male" : "Female";
			
			$rm_number = $data[0]['PATNUMBER'];
			$rm_number = \ltrim($rm_number, "0");

			$first_name = strtoupper($data[0]['FIRSTNAME']);
			$last_name = strtoupper($data[0]['NAME']);
			
			$birth_date = $data[0]['BIRTHDATE'];
			$birth_date = \DateTime::createFromFormat('Y-m-d H:i:s.u', $birth_date);
			if ($birth_date) { $birth_date = $birth_date->format('d F Y'); }

			if ($hostordernumber[0] == 'B' || $hostordernumber[0] == 'Z') {
				$branch = "PMG Bali";
			} elseif ($hostordernumber[0] == 'S' || $hostordernumber[0] == 'X') {
				$branch = "PMG Surabaya";
			} else {
				$branch = "Testing";
			}
			
			$collection_date = $data[0]['COLLECTIONDATE'];
			$dateTimeCol = \DateTime::createFromFormat('Y-m-d H:i:s.u', $collection_date);
			if ($dateTimeCol) {
				$collection_date = $dateTimeCol->format('d F Y H:i');
			}

			$result_date = end($resultData);
			$result_date = $result_date["RESDATE_FIX"];
			$dateTimeRes = \DateTime::createFromFormat('Y-m-d H:i:s.u', $result_date);
			if ($dateTimeRes) {

				// Ambil tahun dari tanggal
				$year = (int) $dateTimeRes->format('Y');

				// Jika tahun < 2000, kosongkan result_date
				if ($year < 2020) {
					$result_date = "";
				} else {
					$result_date = $dateTimeRes->format('d F Y H:i');
				}

				// $result_date = $dateTimeRes->format('d-m-Y H:i');
			}

			$company = $data[0]['AGENT'];
			$visittype = $data[0]['VISITTYPE'];
			
		} else {
			$sex ='';
			$accessnumber = "";
			$rm_number = "";
			$first_name = "";
			$last_name = "";
			$birth_date = "";
			$hostordernumber = "";
			$collection_date = "";
			$result_date = "";
			$branch = "";
			$company = "";
			$visittype = "";
		}
		
		$fullPage="";
		$headPage = "
		<div id='page'>
			<div id='pagetop' style='height:0.01cm'> </div>
	
			<div id='dinfo'>
	
				<table class='information t_center'>
					<tr>
						<th class='padmaColor' colspan='6' align='center'>CLINICAL LABORATORY</th>
					</tr>

					<tr>
						<td style='width:50%' align='left' class='left-pad'><pre><b>RM Number :</b> $rm_number</pre></td>
						<td style='width:50%' align='left' class='left-pad'><pre><b>Visit Number :</b> $hostordernumber</pre></td>
			
					</tr>
	
					<tr>
						<td align='left' class='left-pad'><pre><b>Name :</b> $first_name $last_name</pre></td>
						<td align='left' class='left-pad'><pre><b>Company :</b> $company</pre></td>
					</tr>
	
					<tr>
						<td align='left' class='left-pad'><pre><b>DOB :</b> $birth_date</pre></td>
						<td align='left' class='left-pad'><pre><b>Visit Type :</b> $visittype</pre></td>
					</tr>
					<tr>
						<td align='left' class='left-pad'><pre><b>Gender :</b> $sex</pre></td>
						<td align='left' class='left-pad'><pre><b>Order Date / Time :</b> $collection_date</pre></td>
					</tr>

					<tr>
						<td align='left' class='left-pad'><pre><b>Branch :</b> $branch</pre></td>
						<td align='left' class='left-pad'><pre><b>Result Date / Time :</b> $result_date</pre></td>
					</tr>
	
				</table>
			
			</div>

			<div id='dresult'>
				<br>
					<table class='result t_center'>
			";
			
		$resultTest ="";

		// Untuk Collection
		if ($data[1] != null) {			
			$colltext = '';
			$recvtext = '';
			$qcolldate = '';
			$qcolltime = '';
			$qrecvdate = '';
			$qrecvtime = '';
			foreach ($data[1] as $item) {
				$samp = $item['SHORTTEXT'];
				$colldate = $item['colldate'];
				$recvdate = $item['recvdate'];
				$colltime = $item['colltime'];
				$recvtime = $item['recvtime'];
				if($colldate !='') {
					if($colldate != $qcolldate) { $colltext .= "$colldate $colltime $samp"; $qcolldate = $colldate; $qcolltime = $colltime; }
					else {
						if($colltime != $qcolltime) { $colltext .= ", $colltime $samp"; $qcolltime = $colltime; }
						else { $colltext .= ", $samp"; }
					}
				}
				if($recvdate !='') {
					if($recvdate != $qrecvdate) { $recvtext .= "$recvdate $recvtime $samp"; $qrecvdate = $recvdate; $qrecvtime = $recvtime; }
					else {
						if($recvtime != $qrecvtime) { $recvtext .= ", $recvtime $samp"; $qrecvtime = $recvtime; }
						else { $recvtext .= ", $samp"; }
					}
				}
			}
		}
		
		$resultNoteandSpecimen = "
				<br>
	
				<table class='result t_center'>
					<tr>
						<th align='left' class='left-pad padmaColor'>Notes</th>
					</tr>
					<tr>
						<td class='left-pad'>
						".$note."
						</td>
					</tr>
				</table>
				
				<br>
				
				<table class='t_center table_collection' >
					<tr>
						<td width='15%'>Collection datetime : </td>
						<td>$colltext</td>
					</tr>
					<tr>
						<td>Reception datetime : </td>
						<td>$recvtext</td>
					</tr>
				</table>";
		$footerPage = "
			<div id='footer'>
				<table class='table_footer t_center'>
					<tr>
						<td></td>
						$signature
					</tr>
					<tr>
						".$enteredby
						.$verifiedby."
					</tr>
					<tr>
						".$labtech."
						<td align='right'>".$doctor."</td>
					</tr>
					<tr>
						<td>".$analyst."</td>
						<td align='right'>".$noreg."</td>
					</tr>
				</table>
			</div>";
		$lastDiv="</div>";

        $tempChapEng = "";
        $tempChapInd = "";

		$i=0;
		foreach ($resultData as $item) {

			// Jika tidak ada nama 
			if ($item['test_eng'] == null) {
				continue;
			}

			// Untuk Spasi Depth
			$space="";
			if ($item['RESULT'] != null) {
				$j=0;

				$space.="&nbsp;";
				for ($j=0; $j<=$item['DEPTH']; $j++) {
					$space .= "&nbsp;&nbsp;";
				}
				if ($item['DEPTH']==0){
					$space.="&nbsp;";
				}
				
			} else {

				for ($j=0; $j<=$item['DEPTH']; $j++) {
					$space .= "&nbsp;&nbsp;";
				}

			}

			// Untuk Penamaan Serum Khusus test
			if ($item["RESULT"] == null) {
				$serum_type = "";
			}else {
				$serum_type = $item["serum_type"];
			}

			$resflag = $item["RESFLAG"] == "N" ? '' : $item["RESFLAG"];
			
            if ($tempChapEng != $item['chap_eng']) {
                $tempChapEng = $item['chap_eng'];
                $tempChapInd = $item['chap_ind'];
                
                $i++;

				// Melebihi batas Kertas
				if($i % 27 == 0) {
					$resultTest .= "</table></div>";
					$fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;
					$i=0;
					$resultTest = "";
				}
				
				if($i==0){
					$i++;
				}
				// Untuk Chapter
				$resultTest .= "
				
					<colgroup>
						<col style='width: 35%;'>
						<col style='width: 19%;'>
						<col style='width: 1%;'>
						<col style='width: 12%;'>
						<col style='width: 20%;'>
						<col style='width: 12%;'>
					</colgroup>
					<tr style='border: none;'>
						<th colspan='6' style='border: none;'>
						</th>
					<tr>
					<tr class='padmaColor'>
						<th colspan='6' class='text-left left-pad'>
							$tempChapEng
						</th>
					</tr>
					<tr>
						<th>Parameter</th>
						<th class='khusus-kanan-h'>Result</th>
						<th class='khusus-kiri-h'></th>
						<th>Unit</th>
						<th>Normal Range</th>
						<th>Sample</th>
					</tr>
				";
            }

            // Melebihi batas Kertas
            if($i % 27 == 0 && $i!=0) {
                $resultTest .= "</table></div>";
                $fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;
                $i=0;
                $resultTest = "";
            }

            $i++;
            if ($item['RESTYPE'] == "CE"){
                $resvalue = $item['RESULT'];
            } else if ($item['RESTYPE'] == null) {
				$resvalue = $item['RESULT'];
			} else {
                $resvalue = $item['RESVALUE'];
            }

			$reff = $item["FIX_REFRANGE"];
			$refftext = $item["REFFTEXT"];
			if($refftext !='') {$reff = $refftext;}
			$unit = $item['UNIT'];
			$unittext = $item['UNITTEXT'];
			if($unittext !='') {$unit = $unittext;}
			
			// Untuk mewarnai value yang tidak beda dengan nilai normal
			$color = "";

			// Untuk Hema Tidak Perlu Merah
			if($item['CHAPID']==1) {
				$color = "";
			} elseif ($resflag == 'L' || $resflag == 'H') {
				// $resflag .= "&nbsp;&nbsp;";
				// $color = "red_font";

				// Pengecualian Khusus Untuk Test Berikut
				$excludedred = ["HBsAg", "Anti HIV", "VDRL/Anti TP", "Anti HCV", "Anti HBs", "HBs-Ab"];
				if (in_array($item['SHORTTEXT'], $excludedred)) {
					$color = "";
				} else { // Normal
					$color = "red_font";
				}
			}

			// Hanya Untuk Yang Kode Nya Adalah CODE/CM
			$range = $this->checkRange($item['RESULT'], $item['REFFTEXT']);
			if ($item['code_type'] == 6 && $item['REFFTEXT'] != null) {
				
				if ($range == true) { // Jika nilai masih dalam rentang nilai normal misal : 0 - 1
					
					$color = "";

				} elseif ($range == false) { // Jika nilai bukan merupakan rentang alias hanya code
					
					$excludedred = ["fibers", "fat"];
					if ( in_array(strtolower($item['SHORTTEXT']), $excludedred)) { // Khusus Shorttex Ini jika Positive maka tidak perlu merah

						$color = "";

					} else { //Jika Hasil positive atau reactive maka beri wanra merah
						$redWord = ["positive", "reactive"];
						if (in_array(strtolower($item['RESULT']), $redWord)) {
							$color = "red_font";
						}
					}
					
				} else { // Jika Rentang diatas nilai normal

					$color = "red_font";
					
				}
			}

			// Hanya Untuk Kondisi Ada Komentar Dibawah Result
			if ($item['RESCOMMENT'] != null) {
				$redWord = ["positive", "reactive", "pos", "reac"];
				if (in_array(strtolower($item['RESCOMMENT']), $redWord)) {
					
					// Pengecualian Khusus Untuk Test Berikut
					$excludedred = ["HBsAg", "Anti HIV", "VDRL/Anti TP", "Anti HCV", "Anti HBs", "HBs-Ab"];
					if (in_array($item['SHORTTEXT'], $excludedred)) {
						$color = "";
					} else { // Normal
						$color = "red_font";
					}

				}

				$comment = $item['RESCOMMENT'];
				// Kondisi Sangat Khusus 
				if ($item['RESCOMMENT'] == "NREAC") { 
					$comment = "Non Reactive";
				} else if ($item['RESCOMMENT'] == "REAC") { 
					$comment = "Reactive";
				}
				$rescomment = "<br><i>" . $comment . "</i>";
			
			} else {
				$rescomment = "";
			}

			$test = "";
			// Untuk Nama Test Apakah lebih dari 25 karaktera
			if ( strlen($item['test_eng']) > 25 || strlen($item['test_ind']) > 25) {
				$test = "<pre>" . $space . $item["test_eng"]."<br>$space<small><i>".$item["test_ind"]."</i></small></pre>";
			} else {
				$test = "<pre>" . $space . $item["test_eng"]." "."<small><i>".$item["test_ind"]."</i></small></pre>";
			}

			// Untuk Mengeluarkan Result 
			if ($item['code_type'] == 5) { //Jika dia adalah Komentar
				$resultTest .= "
					<tr>
						<td colspan='1' class=''>
							".$test."
						</td>
						<td colspan='3' class='left-pad ".$color."'>$resflag " . $resvalue . $rescomment ."</td>
						<td class='left-pad'>" . $serum_type . "</td>
					</tr>
				";
			} else if ($resvalue==null && $rescomment == null && $unit == null && $reff==null && $serum_type == null) { //Jika Ini adalah nama chapter
				$resultTest .= "
					<tr>
						<td colspan='6' class=''>
							".$test."
						</td>
					</tr>
				";
			} else {
				$resultTest .= "
					<tr>
						<td style='width: 35%;' colspan='1' class=''>
							".$test."
						</td>
						<td style='width: 19%;' class='right-pad khusus-kanan-d $color'>" . $resvalue . $rescomment ."</td>
						<td style='width: 2%;'  class='$color khusus-kiri-d'>" . "<pre>" .$resflag. "<pre>" . "</td>
						<td style='width: 12%;' class='left-pad'>" . "<pre>" .$unit. "<pre>" . "</td>
						<td style='width: 20%;' class='left-pad'>" . "<pre>" .$reff. "<pre>" . "</td>
						<td style='width: 12%;' class='left-pad'>" . $serum_type . "</td>
					</tr>
				";
			}
			
            // Melebihi batas Kertas
            if($i % 27 == 0 && $i != 0) {
                $resultTest .= "</table></div>";
                $fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;
                $i=0;
                $resultTest = "";
            }
	
		}

		$resultTest .= "
				</table>
				".$resultNoteandSpecimen."
				</div>";
		
		$fullPage .= $headPage.$resultTest.$footerPage.$lastDiv;

		return $fullPage;
	}

    public function printResultTest($access) {
		$cityid = session()->get('usercityid');
		$db = \Config\Database::connect();

		// Memisahkan Waktu yang ditampilkan pada laporan hasil
		$filter_query_result="";
		if ($cityid == 1) {
			$filter_query_result = " r.MAX_RESDATE AS RESULTDATE ";
		} elseif ($cityid == 2) {
			$filter_query_result = " FORMAT(DATEADD(HOUR, -1, r.MAX_RESDATE), 'yyyy-MM-dd HH:mm:ss.fff') AS RESULTDATE ";
		} else {
			$filter_query_result = " r.MAX_RESDATE AS RESULTDATE ";
		}
		// Untuk Header
		$sql = "SELECT 
					ctp.PATNUMBER,
					ctp.FIRSTNAME,
					ctp.LASTNAME AS NAME,
					p.BIRTHDATE, 
					ctr.REQNUMBER as HOSTORDERNUMBER,
					sr.COLLECTIONDATE, 
					sr.SP_ACCESSNUMBER, 
					p.SEX, 
					".$filter_query_result.",
					ctr.AGENT,
					ctr.VISITTYPE
				
				FROM PATIENTS p
				LEFT JOIN SP_REQUESTS sr ON p.PATID = sr.PATID
				LEFT JOIN cmod.dbo.CM_TM_REQUESTS ctr ON ctr.REFFID = sr.HOSTORDERNUMBER
				LEFT JOIN cmod.dbo.CM_TM_PATIENTS ctp ON ctp.PATID = ctr.PATID
				LEFT JOIN 
					(
						SELECT 
							MAX(RESDATE) AS MAX_RESDATE, 
							ACCESSNUMBER 
						FROM 
							[cmod].[dbo].[CM_RESULTS]
						WHERE 
							ACCESSNUMBER = '$access'
						GROUP BY 
							ACCESSNUMBER
					) r 
					ON sr.SP_ACCESSNUMBER = r.ACCESSNUMBER
				WHERE 
					sr.SP_ACCESSNUMBER = '$access'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$header = $results[0];

		// Memisahkan Waktu yang ditampilkan pada laporan hasil
		$filter_query_collection="";
		if ($cityid == 1) {
			$filter_query_collection = " FORMAT(ct.COLLECTIONDATE, 'HH:mm') AS colltime ";
		} elseif ($cityid == 2) {
			$filter_query_collection = " FORMAT(DATEADD(HOUR, -1, ct.COLLECTIONDATE), 'HH:mm') AS colltime ";
		} else {
			$filter_query_collection = " FORMAT(ct.COLLECTIONDATE, 'HH:mm') AS colltime ";
		}
		// Untuk Collection
		$sql = "SELECT 
					ds.FULLTEXT AS SHORTTEXT,
					FORMAT(ct.COLLECTIONDATE, 'dd-MM-yyyy') AS colldate, 
					FORMAT(tu.LABRECEPTIONDATE, 'dd-MM-yyyy') AS recvdate,
					FORMAT(tu.LABRECEPTIONDATE, 'HH:mm') AS recvtime,					
					".$filter_query_collection."
				FROM 
					SP_TUBES tu
				LEFT JOIN 
					DICT_SAMPLES_TYPES ds ON ds.SAMPCODE = tu.SAMPLETYPE
				LEFT JOIN 
					cmod.dbo.CM_TUBES ct ON ct.SAMPLETYPE = tu.SAMPLETYPE AND ct.ACCESSNUMBER = tu.SP_ACCESSNUMBER
				WHERE 
					tu.SP_ACCESSNUMBER = '$access'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$collection = $results;
		$data = [$header, $collection];

		// Memisahkan Waktu yang ditampilkan pada laporan hasil
		$filter_query_resdate="";
		if ($cityid == 1) {
			$filter_query_resdate = " cr.RESDATE as RESDATE_FIX, ";
		} elseif ($cityid == 2) {
			$filter_query_resdate = " FORMAT(DATEADD(HOUR, -1, cr.RESDATE), 'yyyy-MM-dd HH:mm:ss.fff') AS RESDATE_FIX, ";
		} else {
			$filter_query_resdate = " cr.RESDATE as RESDATE_FIX, ";
		}
		$sql = "SELECT 
				dc.CHAPID, 
				dc.FULLTEXT as chap_eng, 
				dc.FULLTEXT as chap_ind, 
				st.SHORTTEXT as serum_type,
				cdt.TEXT1 as test_eng, 
				cdt.TEXT2 as test_ind,
				COALESCE(dt.UNITS, cdt.UNIT) as UNITTEXT,
				cdt.REFFTEXT,
				t.DEPTH,
				t.NOTPRINTABLE,
				t.TESTORDER,
				t.RESTYPE as code_type,
				t.VALIDATIONINITIALS  as validator,
				dt.SHORTTEXT,
				RESULT = case when t.RESVALUE is null then tx.FULLTEXT else t.RESVALUE end,
				COALESCE(
					cr.refrange,
					CASE
						WHEN t.MINIMUM IS NOT NULL AND t.MAXIMUM IS NOT NULL THEN CONCAT(t.MINIMUM, ' - ', t.MAXIMUM)
						WHEN t.MINIMUM IS NOT NULL AND t.MAXIMUM IS NULL THEN CONCAT('>= ', t.MINIMUM)
						WHEN t.MAXIMUM IS NOT NULL AND t.MINIMUM IS NULL THEN CONCAT('<= ', t.MAXIMUM)
						ELSE ''
					END
				) AS FIX_REFRANGE,
				" . $filter_query_resdate . "
				cr.*
				from REQUESTS r 
				left join TESTS t on t.REQUESTID = r.REQUESTID 
				left join DICT_TESTS dt on dt.ENDVALIDDATE is null and t.TESTID=dt.TESTID
				left join DICT_TEXTS tx on tx.TEXTID=t.CODEDRESULTID
				left join DICT_CHAPTERS	dc on dc.CHAPID=dt.CHAPID and dc.ENDVALIDDATE is null
				left join DICT_TEST_SAMPLES ts on ts.TESTID=t.TESTID and dt.TESTID=ts.TESTID
				left join DICT_SAMPLES_TYPES st on st.SAMPTYPEID=ts.SAMPTYPEID
				left join cmod.dbo.CM_DICT_TESTS cdt on dt.TESTCODE=cdt.TESTCODE
				left join cmod.dbo.CM_RESULTS cr on cr.ACCESSNUMBER=r.ACCESSNUMBER and cr.TESTCODE=cdt.TESTCODE and cr.TESTCODE=dt.TESTCODE 
				-- and t.RESUPDDATE = cr.RESDATE
				-- and dt.SHORTTEXT <> 'EGFR'
				where r.ACCESSNUMBER='$access' 
				and t.NOTPRINTABLE is null 
				ORDER BY t.TESTORDER";
        $query = $db->query($sql);
        $results = $query->getResultArray();

		$data_pregnancy = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$tesscode = $item["TESTCODE"];
			$test_eng = $item["test_eng"];
			$printable = $item['NOTPRINTABLE'];
            return $serum_type == 'Urine' && ($tesscode == 'PPT' || $test_eng == "Pregnancy Test") && $printable !=1;
        });
		$data_urine_lengkap = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$tesscode = $item["TESTCODE"];
			$test_eng = $item["test_eng"];
			$chap_eng = $item["chap_eng"];
			$printable = $item['NOTPRINTABLE'];
            return $serum_type == 'Urine' && $tesscode != 'PPT' && $test_eng != "Pregnancy Test" && $chap_eng != "MICROBIOLOGY" && $printable !=1;
        });

		$data_urine_kultur = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$chap_eng = $item["chap_eng"];
			$printable = $item['NOTPRINTABLE'];
            return $serum_type == 'Urine' && $chap_eng == "MICROBIOLOGY" && $printable !=1;
        });
		$data_feces_stc2 = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$tesscode = $item["TESTCODE"];
			$printable = $item['NOTPRINTABLE'];
            return $serum_type == 'Feces' && in_array($tesscode, ['STC2', 'SCSAL', 'SCSHI']) && $printable !=1;
        });
		$data_feces_stc4 = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$tesscode = $item["TESTCODE"];
			$printable = $item['NOTPRINTABLE'];
            return $serum_type == 'Feces' && in_array($tesscode, ['STC4', 'FCSAL', 'FCSHI', 'FCVIB', 'FCESC']) && $printable !=1;
        });
		$data_feces_lengkap = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$tesscode = $item["TESTCODE"];
			$printable = $item['NOTPRINTABLE'];
            return $serum_type == 'Feces' && !in_array($tesscode, ['STC2', 'SCSAL', 'SCSHI', 'STC4', 'FCSAL', 'FCSHI', 'FCVIB', 'FCESC']) && $printable !=1;
        });

		$data_RCS = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$printable = $item['NOTPRINTABLE'];
            return $serum_type == 'Swab Tenggorokan' && $printable !=1;
        });

		$data_others = array_filter($results, function($item) {
            $serum_type = $item["serum_type"];
			$chapter_eng = $item['chap_eng'];
			$printable = $item['NOTPRINTABLE'];
			$tesscode = $item["TESTCODE"];
			
            return $serum_type != 'Feces' && $serum_type != 'Urine' && $chapter_eng != 'Note' && $serum_type != 'Swab Tenggorokan' && $printable !=1 && $tesscode!='EGFR';
        });

		$notes = array_filter($results, function($item) {
            $chap_id = $item["CHAPID"];
			$chap_eng = $item["chap_eng"];
            return $chap_id == 54 && $chap_eng == "Note";
        });
		// Mengambil elemen pertama dari hasil filter
		$notes = reset($notes); // Ambil elemen pertama
		$note = $notes["RESULT"] ?? "-"; // Ambil nilai RESULT, atau null jika tidak ada

        $fullPage = "";

		if ($data_others != null) {
            $fullPage .= $this->pdfViewerNew($data_others, $data, $note);
        }

		if ($data_RCS != null) {
            $fullPage .= $this->pdfViewerNew($data_RCS, $data, $note);
        }

		if ($data_urine_kultur != null) {
            $fullPage .= $this->pdfViewerNew($data_urine_kultur, $data, $note);
        }
		if ($data_pregnancy != null) {
            $fullPage .= $this->pdfViewerNew($data_pregnancy, $data, $note);
        }
		if ($data_urine_lengkap != null) {
            $fullPage .= $this->pdfViewerNew($data_urine_lengkap, $data, $note);
        }
		
        if ($data_feces_stc2 != null) {
            $fullPage .= $this->pdfViewerNew($data_feces_stc2, $data, $note);
        }
		if ($data_feces_stc4 != null) {
            $fullPage .= $this->pdfViewerNew($data_feces_stc4, $data, $note);
        }
		if ($data_feces_lengkap != null) {
            $fullPage .= $this->pdfViewerNew($data_feces_lengkap, $data, $note);
        }
        
        return view('result_report', ['data' => $fullPage, 'site' => $header['HOSTORDERNUMBER']]);
    }
    
}