diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 302b3c5..4b74546 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -9,9 +9,15 @@ $routes->get('/', 'Pages::home'); $routes->get('/loginsby', 'Auths::loginSBY'); $routes->get('/logindps', 'Auths::loginDPS'); //$routes->get('/tests', 'Auths::tests'); -$routes->post('/api/requests/', 'API_Requests::requests'); -$routes->get('/api/requests/orm/(:any)', 'API_Requests::orm/$1'); -$routes->get('/api/requests/oc/(:any)/(:any)', 'API_Requests::oc/$1/$2'); -$routes->get('/api/results/(:any)', 'API_Results::results_send/$1'); -$routes->get('/api/results_preview/(:any)', 'API_Results::results_preview/$1'); +$routes->post('/api/requests/', 'API_TM::requests'); +$routes->get('/api/requests/orm/(:any)', 'API_TM::orm/$1'); +$routes->get('/api/requests/oc/(:any)/(:any)', 'API_TM::oc/$1/$2'); +$routes->get('/api/results/(:any)', 'API_TM::results_send/$1'); +$routes->get('/api/results_preview/(:any)', 'API_TM::results_preview/$1'); +// dashboard message from TM +// dashboard request TM - TD +// resend orm +// resend result +// send oc +// send new master \ No newline at end of file diff --git a/app/Controllers/API_Results.php b/app/Controllers/API_Results.php deleted file mode 100644 index 47c3a5b..0000000 --- a/app/Controllers/API_Results.php +++ /dev/null @@ -1,223 +0,0 @@ -query($sql); - $results = $query->getResultArray(); - - $visitnumber = $results[0]['REQNUMBER']; - $reffid = $results[0]['HOSTORDERNUMBER']; - $location = $results[0]['LOC']; - $payer_name = $results[0]['AGENT']; - $company = $results[0]['COMPANY']; - $createdt = gmdate('Y-m-d\TH:i:s.v\Z'); - $patnumber = substr($results[0]['PATNUMBER'],-9); - $firstname = $results[0]['NAME']; - $lastname = $results[0]['FIRSTNAME']; - $dob = $results[0]['BIRTHDATE']; - $sex = $results[0]['SEX']; - $phone = $results[0]['TELEPHON']; - $visitdesc = $results[0]['VISITDESC']; - $visittype = $results[0]['VISITTYPE']; - $visitdt = $results[0]['COLLECTIONDATE']; - $agent = $results[0]['AGENT']; - if($agent != '') {$bagent = true;} - else {$bagent=false;} - $doctor = $results[0]['DOC']; - $bw = $results[0]['BW']; - $bh = $results[0]['BH']; - - - $json = [ - "reference_id" => "$reffid", - "created" => "$createdt", - "company_name" => $company, - "branch" => $location, - "visit_number" => $visitnumber, - "patient" => [ - "rm_number" => $patnumber, - "patient_first_name" => $firstname, - "patient_last_name" => $lastname, - "patient_dob" => $dob, - "patient_sex" => $sex, - "patient_phone" => $phone, - "visit_number" => $visitnumber, - "visit_description"=> $visitdesc, - "visit_date_time" => $visitdt, - "agent_name" => $agent, - "agent" => $bagent, - "treating_doctor" => $doctor, - "visit_type" => $visittype, - "anthropometry" => [ - "weight" => $bw, - "height" => $bh, - ], - ], - "test_results" => [], - "collects" => [], - "receives" => [] - ]; - - $sql = "select dc.CHAPID, t.DEPTH as depth_test, dc.FULLTEXT as chap_eng, dc.FULLTEXT as chap_ind, st.FULLTEXT as serum_type, - cdt.TEXT1 as test_eng, cdt.TEXT2 as test_ind, cdt.UNIT as UNITTEXT, cdt.REFFTEXT, t.NOTPRINTABLE, cr.RESSTATUS, - 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, ct.REFFTESTID, m.HISCODE, m.LISCODE, - tub.TUBENAME, cr.REFRANGE, dt.TESTCODE, t.TESTORDER, dt.UNITS -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 -left join cmod.dbo.CM_DICT_MAPPINGS m on m.LISCODE=cr.TESTCODE -left join cmod.dbo.CM_TM_REQUESTS cq on cq.REFFID=r.EXTERNALORDERNUMBER -left join cmod.dbo.CM_TM_TESTS ct on ct.HISCODE=m.HISCODE and ct.REQID=cq.REQID -left join cmod.dbo.CM_DICT_TUBES tub on tub.TUBEID=m.TUBEID -where r.ACCESSNUMBER='$accessnumber' and t.NOTPRINTABLE is null ORDER BY t.TESTORDER"; - $query = $db->query($sql); - $test_results = $query->getResultArray(); - $d0=-1; $d1=-1; $d2=-1; $d3=-1; - foreach ($test_results as $result) { - $refftestid = trim($result['REFFTESTID']); - $testorder = $result['TESTORDER']; - if($refftestid == '') { $refftestid = $accessnumber . str_pad($testorder,3,0, STR_PAD_LEFT); } - $hiscode = $result['HISCODE']; - $tubename = $result['TUBENAME']; - $depth = $result['depth_test']; - $liscode = $result['LISCODE']; - $testcode = $result['TESTCODE']; - $testname = $result['test_eng']; - $sampletype = $result['serum_type']; - $chapter = $result['chap_eng']; - $testresult = $result['RESULT']; - $unit = $result['UNITS']; - $unittext = $result['UNITTEXT']; - $testunit = $unit; - if($unittext != '') { $testunit = $unittext; } - $refrange = $result['REFRANGE']; - $refftext = $result['REFFTEXT']; - $resstatus = $result['RESSTATUS']; - if($resstatus == 'F') { $testsum = 'APPROVE'; } - elseif($resstatus == 'C') { $testsum = 'PENDING'; } - else { $testsum = null; } - if($refftext != '') { $testreff = $refftext; } - else { $testreff = $refrange; } - if($liscode == '') {$liscode = $testcode;} - $data = [ - "test_ref_id"=> "$refftestid", - "hiscode"=> "$hiscode", - "liscode"=> "$liscode", - "service_name"=> "$testname", - "test_medium"=> "$sampletype", - "test_container"=> "$tubename", - "chapter_type"=> "$chapter", - "test_result"=> "$testresult", - "test_unit"=> "$testunit", - "test_reff" => "$testreff", - "test_summary"=> "$testsum", - //"debug" => "d0=$d0 d1=$d1 d2=$d2", - ]; - if ( $depth == 0 || $depth == '' ) { // depth 0 - $d0++; - $d1=-1; - $json['test_results'][] = $data; - } else if ($depth == 1) { // depth 1 - $d1++; - $d2=-1; - $json['test_results'][$d0]['subtest_results'][] = $data; - } else if ($depth == 2) { // depth 2 - $d2++; - $d3=-1; - $json['test_results'][$d0]['subtest_results'][$d1]['subtest_results'][] = $data; - } - } - - $sql = "SELECT ds.SHORTTEXT, - FORMAT(tu.COLLECTIONDATE, 'dd-MM-yyyy') AS RECVDATE, - FORMAT(tu.COLLECTIONDATE, 'HH:mm') AS RECVTIME, - FORMAT(ct.COLLECTIONDATE, 'dd-MM-yyyy') AS COLLDATE, - FORMAT(ct.COLLECTIONDATE, 'HH:mm') AS COLLTIME -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 = '$accessnumber';"; - $query = $db->query($sql); - $samples = $query->getResultArray(); - foreach ($samples as $data) { - $sample = $data['SHORTTEXT']; - $recvdate = $data['RECVDATE']; - $recvtime = $data['RECVTIME']; - $colldate = $data['COLLDATE']; - $colltime = $data['COLLTIME']; - $json['collects'][] = [ "sample" => "$sample", "colldate" => "$colldate", "colltime" => "$colltime" ]; - $json['receives'][] = [ "sample" => "$sample", "recvdate" => "$recvdate", "recvtime" => "$recvtime" ]; - } - return $json; - } - - public function results_send($accessnumber) { - //$TM_url = "https://api-transmedic1.transmedic.co.id/api/webhook/lis"; - $TMSby_url = "http://10.10.4.123:8001/api/webhook/lis"; - $TMBali_url = "http://10.10.12.90:8001/api/webhook/lis?tenant=PadmaBali"; - $TMBali_bearerToken = file_get_contents('tokens/pbmc_dps.txt'); - $TMSby_bearerToken = file_get_contents('tokens/pbmc_sby.txt'); - - $client = \Config\Services::curlrequest(); - - $json = $this->create_json($accessnumber); - $location = $json['branch']; - if($location == 'PBMC Surabaya') { - $token = $TMSby_bearerToken; - $url = $TMSby_url; - $headers = [ - "Content-Type" => "application/json", - "Authorization" => "Bearer $token", - "appCode" => "2" - ]; - } else { - $token = $TMBali_bearerToken; - $url = $TMBali_url; - $headers = [ "Content-Type" => "application/json" ]; - } - - try { - $response = $client->request('POST', $url, [ - "headers" => $headers, - "body" => json_encode($json), - "verify" => false - ]); - - if ($response->getStatusCode() == 200) { - print_r($response); - } else { - print_r($response); - } - - } catch (\Exception $e) { - echo "
$token \n".json_encode($json)."\n";
-            echo "Error: " . $e->getMessage();
-            log_message('error', 'API request exception: ' . $e->getMessage());
-        }
-    }
-	
-	public function results_preview($accessnumber) {
-		$json = $this->create_json($accessnumber);
-		return $this->respond($json);
-	}
-
-}
\ No newline at end of file
diff --git a/app/Controllers/API_Requests.php b/app/Controllers/API_TM.php
similarity index 50%
rename from app/Controllers/API_Requests.php
rename to app/Controllers/API_TM.php
index e142598..95e21d1 100644
--- a/app/Controllers/API_Requests.php
+++ b/app/Controllers/API_TM.php
@@ -4,7 +4,64 @@ namespace App\Controllers;
 use CodeIgniter\RESTful\ResourceController;
 use CodeIgniter\I18n\Time;
 
-class API_Requests extends ResourceController {
+class API_TM extends ResourceController {
+	
+	public function sendHL7Message($host, $port, $message, $timeout = 5) {
+		try {
+			// Create a TCP/IP socket
+			$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
+			if ($socket === false) {
+				throw new Exception("socket_create() failed: " . socket_strerror(socket_last_error()));
+			}
+
+			// Set socket options (timeout)
+			socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $timeout, "usec" => 0));
+			socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => $timeout, "usec" => 0));
+
+			// Connect to the remote host
+			$result = socket_connect($socket, $host, $port);
+			if ($result === false) {
+				throw new Exception("socket_connect() failed: " . socket_strerror(socket_last_error($socket)));
+			}
+
+			// Add MLLP framing (Minimal Lower Layer Protocol)
+			$mllpMessage = chr(0x0B) . $message . chr(0x1C) . chr(0x0D);
+
+			// Send the message
+			$bytesSent = socket_write($socket, $mllpMessage, strlen($mllpMessage));
+			if ($bytesSent === false) {
+				throw new Exception("socket_write() failed: " . socket_strerror(socket_last_error($socket)));
+			}
+			if($bytesSent != strlen($mllpMessage)){
+				throw new Exception("socket_write() only sent $bytesSent bytes out of ". strlen($mllpMessage));
+			}
+
+			// Read the acknowledgement (optional but recommended)
+			$ack = socket_read($socket, 8192); // Adjust buffer size as needed
+			if ($ack === false) {
+				// Handle cases where no ACK is received within the timeout
+				throw new Exception("socket_read() failed or timed out: " . socket_strerror(socket_last_error($socket)));
+			}
+
+			//Close the socket
+			socket_close($socket);
+
+			//Basic ACK check. More robust parsing is recommended.
+			if (strpos($ack, "MSA") !== false) {
+				return true; // Success (basic ACK check)
+			} else {
+				error_log("Unexpected ACK: " . $ack); // Log the unexpected ACK
+				return false; // Failure (unexpected ACK)
+			}
+
+		} catch (Exception $e) {
+			error_log("HL7 Sending Error: " . $e->getMessage()); // Log the error
+			if(isset($socket)){
+				socket_close($socket); // Ensure socket closure on error
+			}
+			return false; // Indicate failure
+		}
+	}
 	
 	public function requests() {
 		$db = \Config\Database::connect();
@@ -192,60 +249,251 @@ class API_Requests extends ResourceController {
 		
 	}
 	
-	public function sendHL7Message($host, $port, $message, $timeout = 5) {
-		try {
-			// Create a TCP/IP socket
-			$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
-			if ($socket === false) {
-				throw new Exception("socket_create() failed: " . socket_strerror(socket_last_error()));
+	
+	
+	public function create_result_json($accessnumber) {
+		$db = \Config\Database::connect();
+		$sql = "select r.HOSTORDERNUMBER, r.SP_HOSPNUMBER, cr.REQNUMBER, cr.LOC, cr.COMPANY, cr.AGENT, cr.VISITDESC, cr.VISITTYPE,
+	p.PATNUMBER, p.NAME, p.FIRSTNAME, p.BIRTHDATE, p.SEX, p.TELEPHON, r.COLLECTIONDATE, cr.AGENT, cr.DOC, cr.BW, cr.BH
+from SP_REQUESTS r
+	left join cmod.dbo.CM_TM_REQUESTS cr on cr.REFFID=r.HOSTORDERNUMBER
+	left join PATIENTS p on p.PATID=r.PATID
+where r.SP_ACCESSNUMBER='$accessnumber'";
+		$query = $db->query($sql);
+		$results = $query->getResultArray();
+
+		$visitnumber = $results[0]['REQNUMBER'];
+		$reffid = $results[0]['HOSTORDERNUMBER'];
+		$location = $results[0]['LOC'];
+		$payer_name = $results[0]['AGENT'];
+		$company = $results[0]['COMPANY'];
+		$createdt = gmdate('Y-m-d\TH:i:s.v\Z');
+		$patnumber = substr($results[0]['PATNUMBER'],-9);
+		$firstname = $results[0]['NAME'];
+		$lastname = $results[0]['FIRSTNAME'];
+		$dob = $results[0]['BIRTHDATE'];
+		$sex = $results[0]['SEX'];
+		$phone = $results[0]['TELEPHON'];
+		$visitdesc = $results[0]['VISITDESC'];
+		$visittype = $results[0]['VISITTYPE'];
+		$visitdt = $results[0]['COLLECTIONDATE'];
+		$agent = $results[0]['AGENT'];
+		if($agent != '') {$bagent = true;}
+		else {$bagent=false;}
+		$doctor = $results[0]['DOC'];
+		$bw = $results[0]['BW'];
+		$bh = $results[0]['BH'];
+		
+		
+		$json = [
+			"reference_id" => "$reffid",
+			"created" => "$createdt", 
+			"company_name" => $company,
+			"branch" => $location,
+			"visit_number" => $visitnumber,
+			"patient" => [
+				"rm_number" => $patnumber,
+				"patient_first_name" => $firstname,
+				"patient_last_name" => $lastname,
+				"patient_dob" => $dob,
+				"patient_sex" => $sex,
+				"patient_phone" => $phone,
+				"visit_number" => $visitnumber,
+				"visit_description"=> $visitdesc,
+				"visit_date_time" => $visitdt,
+				"agent_name" => $agent,
+				"agent" => $bagent,
+				"treating_doctor" => $doctor,
+				"visit_type" => $visittype,
+				"anthropometry" => [
+					"weight" => $bw,
+					"height" => $bh, 
+				],
+			],
+			"test_results" => [],
+			"collects" => [],
+			"receives" => []
+		];
+
+		$sql = "select dc.CHAPID, t.DEPTH as depth_test, dc.FULLTEXT as chap_eng, dc.FULLTEXT as chap_ind, st.FULLTEXT as serum_type, 
+  cdt.TEXT1 as test_eng, cdt.TEXT2 as test_ind, cdt.UNIT as UNITTEXT, cdt.REFFTEXT, t.NOTPRINTABLE, cr.RESSTATUS,
+  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, ct.REFFTESTID, m.HISCODE, m.LISCODE, 
+  tub.TUBENAME, cr.REFRANGE, dt.TESTCODE, t.TESTORDER, dt.UNITS, cr.RESDATE, cr.USERVAL
+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
+left join cmod.dbo.CM_DICT_MAPPINGS m on m.LISCODE=cr.TESTCODE
+left join cmod.dbo.CM_TM_REQUESTS cq on cq.REFFID=r.EXTERNALORDERNUMBER
+left join cmod.dbo.CM_TM_TESTS ct on ct.HISCODE=m.HISCODE and ct.REQID=cq.REQID
+left join cmod.dbo.CM_DICT_TUBES tub on tub.TUBEID=m.TUBEID
+where r.ACCESSNUMBER='$accessnumber' and t.NOTPRINTABLE is null ORDER BY t.TESTORDER";
+        $query = $db->query($sql);
+        $test_results = $query->getResultArray();
+		$d0=-1; $d1=-1; $d2=-1; $d3=-1;
+		foreach ($test_results as $result) {
+			$refftestid = trim($result['REFFTESTID']);
+			$testorder = $result['TESTORDER'];
+			if($refftestid == '') { $refftestid = $accessnumber . str_pad($testorder,3,0, STR_PAD_LEFT); }
+			$hiscode = $result['HISCODE'];
+			$tubename = $result['TUBENAME'];
+			$depth = $result['depth_test'];
+			$liscode = $result['LISCODE'];
+			$testcode = $result['TESTCODE'];
+			$testname = $result['test_eng'];
+			$sampletype = $result['serum_type'];
+			$chapter = $result['chap_eng'];
+			$testresult = $result['RESULT'];
+			$unit = $result['UNITS'];
+			$unittext = $result['UNITTEXT'];
+			$testunit = $unit;
+			if($unittext != '') { $testunit = $unittext; }
+			$refrange = $result['REFRANGE'];
+			$refftext = $result['REFFTEXT'];
+			$resstatus = $result['RESSTATUS'];
+			if($resstatus == 'F') { $testsum = 'APPROVE'; }
+			elseif($resstatus == 'C') { $testsum = 'PENDING'; }
+			else { $testsum = null; }
+			if($refftext != '') { $testreff = $refftext; }
+			else { $testreff = $refrange; }
+			if($liscode == '') {$liscode = $testcode;}
+			$resdate = $result['RESDATE'];
+			if($resdate == "1900-01-01 00:00:00.000") { $resdate =''; }
+			$userval = $result['USERVAL'];
+			$data = [
+				"test_ref_id"=> "$refftestid",
+				"hiscode"=> "$hiscode",
+				"liscode"=> "$liscode",
+				"service_name"=> "$testname",
+				"test_medium"=> "$sampletype",
+				"test_container"=> "$tubename",
+				"chapter_type"=> "$chapter", 
+				"test_result"=> "$testresult",
+				"test_unit"=> "$testunit",
+				"test_reff" => "$testreff",
+				"test_summary"=> "$testsum",
+				"resdate"=> "$resdate",
+				"userval"=> "$userval",
+				//"debug" => "d0=$d0 d1=$d1 d2=$d2",
+			];			
+			if ( $depth == 0 || $depth == '' ) { // depth 0
+				$d0++;
+				$d1=-1;
+				$json['test_results'][] = $data;
+			} else if ($depth == 1) {  // depth 1 
+				$d1++;
+				$d2=-1;
+				$json['test_results'][$d0]['subtest_results'][] = $data;
+			} else if ($depth == 2) {  // depth 2 
+				$d2++;
+				$d3=-1;
+				$json['test_results'][$d0]['subtest_results'][$d1]['subtest_results'][] = $data;
 			}
-
-			// Set socket options (timeout)
-			socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $timeout, "usec" => 0));
-			socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => $timeout, "usec" => 0));
-
-			// Connect to the remote host
-			$result = socket_connect($socket, $host, $port);
-			if ($result === false) {
-				throw new Exception("socket_connect() failed: " . socket_strerror(socket_last_error($socket)));
-			}
-
-			// Add MLLP framing (Minimal Lower Layer Protocol)
-			$mllpMessage = chr(0x0B) . $message . chr(0x1C) . chr(0x0D);
-
-			// Send the message
-			$bytesSent = socket_write($socket, $mllpMessage, strlen($mllpMessage));
-			if ($bytesSent === false) {
-				throw new Exception("socket_write() failed: " . socket_strerror(socket_last_error($socket)));
-			}
-			if($bytesSent != strlen($mllpMessage)){
-				throw new Exception("socket_write() only sent $bytesSent bytes out of ". strlen($mllpMessage));
-			}
-
-			// Read the acknowledgement (optional but recommended)
-			$ack = socket_read($socket, 8192); // Adjust buffer size as needed
-			if ($ack === false) {
-				// Handle cases where no ACK is received within the timeout
-				throw new Exception("socket_read() failed or timed out: " . socket_strerror(socket_last_error($socket)));
-			}
-
-			//Close the socket
-			socket_close($socket);
-
-			//Basic ACK check. More robust parsing is recommended.
-			if (strpos($ack, "MSA") !== false) {
-				return true; // Success (basic ACK check)
-			} else {
-				error_log("Unexpected ACK: " . $ack); // Log the unexpected ACK
-				return false; // Failure (unexpected ACK)
-			}
-
-		} catch (Exception $e) {
-			error_log("HL7 Sending Error: " . $e->getMessage()); // Log the error
-			if(isset($socket)){
-				socket_close($socket); // Ensure socket closure on error
-			}
-			return false; // Indicate failure
 		}
+		
+		$sql = "SELECT ds.SHORTTEXT, 
+	FORMAT(tu.COLLECTIONDATE, 'dd-MM-yyyy') AS RECVDATE, 
+	FORMAT(tu.COLLECTIONDATE, 'HH:mm') AS RECVTIME, 
+	FORMAT(ct.COLLECTIONDATE, 'dd-MM-yyyy') AS COLLDATE,
+	FORMAT(ct.COLLECTIONDATE, 'HH:mm') AS COLLTIME
+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 = '$accessnumber';";
+        $query = $db->query($sql);
+        $samples = $query->getResultArray();
+		foreach ($samples as $data) {
+			$sample = $data['SHORTTEXT'];
+			$recvdate = $data['RECVDATE'];
+			$recvtime = $data['RECVTIME'];
+			$colldate = $data['COLLDATE'];
+			$colltime = $data['COLLTIME'];
+			$json['collects'][] = [ "sample" => "$sample", "colldate" => "$colldate", "colltime" => "$colltime" ];
+			$json['receives'][] = [ "sample" => "$sample", "recvdate" => "$recvdate", "recvtime" => "$recvtime" ];
+		}
+		return $json;
+	}
+	
+	public function sendjson( $method, $url, $message ) {
+		try { 
+			$response = $client->request($method, $url, $message);
+			
+            if ($response->getStatusCode() == 200) { 
+				print_r($response);
+            } else {
+				print_r($response);
+            }
+			
+        } catch (\Exception $e) {
+			echo "
$token \n".json_encode($json)."\n";
+            echo "Error: " . $e->getMessage();
+            log_message('error', 'API request exception: ' . $e->getMessage());
+        }
+	}
+	public function results_send($accessnumber) {
+		//$TM_url = "https://api-transmedic1.transmedic.co.id/api/webhook/lis";
+		$TMSby_url = "http://10.10.4.123:8001/api/webhook/lis";
+		$TMBali_url = "http://10.10.12.90:8001/api/webhook/lis?tenant=PadmaBali";
+		$TMBali_bearerToken = file_get_contents('tokens/pbmc_dps.txt');
+		$TMSby_bearerToken = file_get_contents('tokens/pbmc_sby.txt');
+		
+		$client = \Config\Services::curlrequest();
+		
+		$json = $this->create_result_json($accessnumber);
+		$location = $json['branch'];
+		if($location == 'PBMC Surabaya') { 
+			$token = $TMSby_bearerToken; 
+			$url = $TMSby_url;
+			$headers = [ 
+				"Content-Type" => "application/json",
+				"Authorization" => "Bearer $token",
+				"appCode" => "2"
+			];
+		} else { 
+			$token = $TMBali_bearerToken; 
+			$url = $TMBali_url;
+			$headers = [ "Content-Type" => "application/json" ];
+		}
+		
+		$method = "POST";
+		
+		$message = [
+			"headers" => $headers,
+			"body" => json_encode($json),
+			"verify" => false
+		];
+		
+		$this->sendjson($method, $url, $message);
+		/*
+		try { 
+			$response = $client->request('POST', $url, [
+				"headers" => $headers,
+				"body" => json_encode($json),
+				"verify" => false
+			]);
+			
+            if ($response->getStatusCode() == 200) { 
+				print_r($response);
+            } else {
+				print_r($response);
+            }
+			
+        } catch (\Exception $e) {
+			echo "
$token \n".json_encode($json)."\n";
+            echo "Error: " . $e->getMessage();
+            log_message('error', 'API request exception: ' . $e->getMessage());
+        }
+		*/
+    }
+	
+	public function results_preview($accessnumber) {
+		$json = $this->create_result_json($accessnumber);
+		return $this->respond($json);
 	}
 }