<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\I18n\Time;

class API_Requests extends ResourceController {
	
	public function requests() {
		$db = \Config\Database::connect();
		$raw = $this->request->getVar();
		
		// log to cm_tm_logs
		$data = json_encode($raw);
		$sql = "INSERT INTO cmod.dbo.CM_TM_LOGS (URL, METHOD, BODY, LOGDATE) VALUES ('API/REQUESTS', 'POST', '$data', GETDATE())";
		$db->query($sql);
		
		$data = array();
		$qdata = (array)$raw;
		$qpat = (array)$qdata['patient'];
		
		//patdata
		$rm = $qpat['rm_number'];
		$firstname = $qpat['patient_first_name'];
		$lastname = $qpat['patient_last_name'];
		$dob = $qpat['patient_dob'];
		$dob = str_replace("-","",$dob);
		$sex = $qpat['patient_sex'];
		$phone = $qpat['patient_phone'];
		
		$sql = "select PATID from cmod.dbo.CM_TM_PATIENTS where PATNUMBER='$rm'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(!isset($results[0])) { 
			$sql = "INSERT INTO cmod.dbo.CM_TM_PATIENTS (PATNUMBER, FIRSTNAME, LASTNAME, BIRTHDATE, SEX, PHONE ) VALUES ('$rm', '$firstname', '$lastname', '$dob', '$sex', '$phone' )"; 
			$db->query($sql);
			$patid = $db->insertID();
		} else { 
			$patid = $results[0]['PATID'];
			$sql = "UPDATE cmod.dbo.CM_TM_PATIENTS SET FIRSTNAME='$firstname', LASTNAME='$lastname', BIRTHDATE='$dob', SEX='$sex', PHONE='$phone' where PATID='$patid'"; 
			$db->query($sql);
		}
		
		//reqdata
		$reffid = $qdata['reference_id'];
		$company_name = $qdata['company_name'];
		$loc = $qdata['branch'];
		
		$visitnum = $qpat['visit_number'];
		$visitdesc = $qpat['visit_description'];
		$visitdt = $qpat['visit_date_time'];
		$agent = $qpat['agent'];
		$agentname = $qpat['agent_name'];
		$visittype = $qpat['visit_type'];
		$doc = $qpat['treating_doctor'];
		
		$createdt = $qdata['created'];
		$qant = (array)$qpat['anthropometry'];
		$bw = $qant['weight'];
		$bh = $qant['height'];
		
		/*
		$time = Time::createFromFormat('Y-m-d\TH:i:s.u\Z', $utcdt, 'UTC'); //2024-10-19T00:47:06.424654Z
		$time = $time->setTimezone('Asia/Shanghai');
		$orderdt = $time->toDateTimeString();	
		*/
		$sql = "select REQID from cmod.dbo.CM_TM_REQUESTS where REFFID='$reffid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(!isset($results[0])) { 
			$sql = "INSERT INTO cmod.dbo.CM_TM_REQUESTS (REFFID, REQNUMBER, REQDESC, REQTYPE, REQDATE, AGENT, DOC, LOC, PATID, COMPANY, LOGDATE, BW, BH) 
				VALUES ('$reffid', '$visitnum', '$visitdesc', '$visittype', '$visitdt', '$agentname', '$doc', '$loc', '$patid', '$company_name', '$createdt', '$bw', '$bh' )"; 
			$db->query($sql);
			$reqid = $db->insertID();
		} else { 
			$reqid = $results[0]['REQID'];
			$sql = "UPDATE cmod.dbo.CM_TM_REQUESTS SET REQNUMBER='$visitnum', REQDESC='$visitdesc', REQTYPE='$visittype', REQDATE='$visitdt', AGENT='$agentname', DOC='$doc', LOC='$loc', PATID='$patid', LOGDATE='$createdt', BW='$bw', BH='$bh' where REQID='$reqid'"; 
			$db->query($sql);
		}	
		
		// tests
		$tests = json_decode(json_encode($qpat['tests']), true);;
		$string = '';
		foreach($tests as $test) {
			$testcode = $test['service_id'];
			$testreffid = $test['test_ref_id'];
			if(isset($test['status'])) { $teststatus = $test['status'];}
			else { $teststatus = ''; }
			$string .= "( '$testreffid', '$reqid', '$testcode', '$teststatus' ),";
		}
		$string = rtrim($string, ',');
		//$sql = "INSERT INTO cmod.dbo.CM_TM_TESTS(REFFID, REQID, HISCODE) VALUES $string";
		$sql = "INSERT INTO cmod.dbo.CM_TM_TESTS (REFFTESTID, REQID, HISCODE, TESTSTATUS) 
			SELECT S.REFFTESTID, S.REQID, S.HISCODE, S.TESTSTATUS FROM ( VALUES $string ) AS S (REFFTESTID, REQID, HISCODE, TESTSTATUS)
			WHERE NOT EXISTS ( SELECT 1 FROM cmod.dbo.CM_TM_TESTS T WHERE T.REQID = S.REQID AND T.HISCODE = S.HISCODE );";
		$db->query($sql);

		$sql = "UPDATE cmod.dbo.CM_TM_TESTS SET TESTSTATUS = S.TESTSTATUS
			FROM cmod.dbo.CM_TM_TESTS T
			INNER JOIN ( VALUES $string ) AS S (REFFTESTID, REQID, HISCODE, TESTSTATUS)
			ON T.REQID = S.REQID AND T.HISCODE = S.HISCODE;";
		$db->query($sql);
		
		//sendORM
		$this->orm($reqid);
		
		return $this->respond(201);
		/*
		if( $db->query($sql) )  {
			return $this->respond(201);
		} else {
			$response = [
				'errors' => $db->errors(), 'message' => 'Invalid Messages'
			];
	       return $this->fail($response , 409);
        }
		*/
	}
	
	public function orm($reqid) {
		$db = \Config\Database::connect();
		$sql = "select r.REFFID, r.LOC, p.PATNUMBER, p.FIRSTNAME, p.LASTNAME, p.BIRTHDATE, p.SEX, r.REQNUMBER, r.REQDATE, r.AGENT, r.DOC, r.BW, r.BH
		from cmod.dbo.CM_TM_REQUESTS r
		left join cmod.dbo.CM_TM_PATIENTS p on p.PATID=r.PATID
		where r.REQID='$reqid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$res = $results[0];
		
		$reffid = $res['REFFID'];
		$patnumber = $res['PATNUMBER'];
		$loc = $res['LOC'];
		$doc = $res['DOC'];
		$firstname = $res['FIRSTNAME'];
		$lastname = $res['LASTNAME'];
		$dob = $res['BIRTHDATE'];
		$sex = $res['SEX'];
		$hosp = $res['REQNUMBER'];
		$reqdate = $res['REQDATE'];
		$time = Time::createFromFormat('Y-m-d\TH:i:s.u\Z', $reqdate, 'UTC'); //2024-10-19T00:47:06.424654Z
		$agent = $res['AGENT'];
		$bw = $res['BW'];
		$bh = $res['BH'];
		
		// LOC
		if($loc == "PBMC Bali") { 
			$loc = "PADMA"; $doc = "PBDPS"; 
			$time = $time->setTimezone('Asia/Shanghai');
			$reqdate= date_format($time, 'YmdHi');	
		} else { 
			$loc = "PBSBY"; $doc = "PBSBY";
			$time = $time->setTimezone('Asia/Jakarta');
			$reqdate= date_format($time, 'YmdHi');	
		}
		
		$orm = "MSH|^~\&|PBMC|TM|TDNL||||ORM^O01^|||2.3||||\r";
		$orm .= "PID|1||$patnumber^^^^PATNUMBER||$firstname^$lastname^^^^^L||$dob|$sex||^|^^||||||^||||||||||||||||\r";
		$orm .= "PV1|||$loc^^^||||$doc|$doc||||||||||||||||||||||||||||||||||||$reqdate||||||||||\r";
		
		$sql = "select t.TESTSTATUS, m.LISCODE from cmod.dbo.CM_TM_TESTS t
			left join cmod.dbo.CM_DICT_MAPPINGS m on m.HISCODE=t.HISCODE
			where t.REQID='$reqid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$i = 1;
		foreach($results as $qdata) {
			$liscode = $qdata['LISCODE'];
			$status = $qdata['TESTSTATUS'];
			if($liscode != '') {
				if($status!=1 || $status !=2) {$status="NW";} else {$status="CA";}
				$orm .= "ORC|$status|$reffid||$reffid|||^^^$reqdate|||||$doc|$loc||$reqdate|||||||||\r";
				$orm .= "OBR|$i|||$liscode|||||||R|||||$doc|||||||||||||||||||||||||\r";
				$i++;
				if($liscode=="EGFR") {
					$orm .= "OBX||NM|BW||$bw|\r";
				}
			}
		}
		
		echo "<pre>$orm";
		//sendHL7Message($host, $port, $message, $timeout = 5);
		//$this->sendHL7Message( "localhost", "8101", $orm, $timeout = 5);
		//$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		
	}
	
	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
		}
	}
}
