<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class API_Results extends ResourceController {

	public function create_json($accessnumber) {
		$db = \Config\Database::connect();
		$sql = "select r.HOSTORDERNUMBER, r.SP_HOSPNUMBER, 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]['SP_HOSPNUMBER'];
		$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'],-8);
		$firstname = $results[0]['FIRSTNAME'];
		$lastname = $results[0]['NAME'];
		$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,
			"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" => []
		];

		$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' 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'];
			if($unittext != '') { $testunit = $unit; }
			else { $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;
			}
			
		}
		return $json;
	}
	
	public function results_send($accessnumber) {
		$TM_url = "https://api-transmedic1.transmedic.co.id/api/webhook/lis";
		$TMBali_bearerToken = "4418|eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOm51bGwsImF1ZCI6ImFwaS10cmFuc21lZGljMS50cmFuc21lZGljLmNvLmlkIiwiaWF0IjoxNzM4MzE0NjU5LCJleHAiOjE3Mzg0MDEwNTksInN1YiI6bnVsbCwianRpIjoiMDBhNmUzN2ItNTA1Zi00ZDA0LWE1MjktMjU0NjE4ZGQ1ODE1IiwiZGF0YSI6eyJ1c2VybmFtZSI6InBibWNfYmFsaSIsInBhc3N3b3JkIjoiSjhlMjlYakxtRENGdVFuayJ9fQ.Zu5Ph4nbuJb9ySH4nv_7qABAzKLJxVspMM7PuzVda0k";
		$TMSby_bearerToken = "4417|eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOm51bGwsImF1ZCI6ImFwaS10cmFuc21lZGljMS50cmFuc21lZGljLmNvLmlkIiwiaWF0IjoxNzM4MzE0NTYwLCJleHAiOjE3Mzg0MDA5NjAsInN1YiI6bnVsbCwianRpIjoiNWI5NDM4OGItOThlOC00ZTZkLTg3YzMtMGVjNTgzNDUzYWM3IiwiZGF0YSI6eyJ1c2VybmFtZSI6InBibWNfc3VyYWJheWEiLCJwYXNzd29yZCI6InBnY1dmZHdYM3FFdDl6YUMifX0.eXX5EDqyusZ3xNey20L5A6dKGgKmf73Bk7-UBLJu45o";
		
		$client = \Config\Services::curlrequest();
		
		$json = $this->create_json($accessnumber);
		$location = $json['branch'];
		if($location == 'PBMC Surabaya') { $token = $TMSby_bearerToken; }
		else { $token = $TMBali_bearerToken; }
		//return $this->respond($json,200);
		
		//print_r(json_encode($json));
		
		try { 
			$response = $client->request('POST', $TM_url, [
				"headers" => [
					"Content-Type" => "application/json",
					"Authorization" => "Bearer $token",
					"AppCode" => "2"
				],
				"body" => json_encode($json),
				"verify" => false
			]);
			
            if ($response->getStatusCode() == 200) { 
				print_r($response);
            } else {
				print_r($response);
            }
			
        } catch (\Exception $e) {
            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);
	}

}