<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class API_HISOrders extends ResourceController {
	protected $format = 'json';
    
	public function index() {

		// Mengetahui Apakah User Login adalah Bali atau Surabaya
		$cityid = session()->get('usercityid');
		if ($cityid == 1) {
			$filter_query = " AND o.VISITNUMBER LIKE 'BV%' ";
		} elseif ($cityid == 2) {
			$filter_query = " AND o.VISITNUMBER LIKE 'SV%' ";
		} else {
			$filter_query = " ";
		}

		$db = \Config\Database::connect();
		$date1 = $this->request->getPost('date1');
		$date2 = $this->request->getPost('date2');
		$sql = "select o.ORDERID, o.LOC, o.VISITNUMBER, o.VISITDATE, o.PAYERNAME, o.TREATDOC, p.PATNUMBER, p.SEX, p.PATNAME,
			TESTS=stuff(( select ', '+t.HISCODE from
			( select t.HISCODE from cmod.dbo.CM_HIS_TESTS t 
				where t.ORDERID=o.ORDERID and t.TESTSTATUS is null
			) as T
			for xml path('')),1,1,'')
			from cmod.dbo.CM_HIS_ORDERS o 
			left join cmod.dbo.CM_HIS_PATIENTS p on p.PATID=o.PATID
			where o.VISITDATE between '$date1 00:00' and '$date2 23:59' " . $filter_query;
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['data'] = $results;
        return $this->respond($data,200);
    }
	
	public function detail($orderid) {
		$db = \Config\Database::connect();
		$sql = "select * from cmod.dbo.CM_HIS_ORDERS o where o.ORDERID='$orderid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['orders'] = $results;
		$sql = "select * from cmod.dbo.CM_HIS_TESTS where ORDERID='$orderid' and TESTSTATUS is null";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['tests'] = $results;
        return $this->respond($data,200);
    }
	
	public function save() {
		$db = \Config\Database::connect();
		//Object { patid: "9", visitnumber: "9989", visitdate: "2024-12-13", treatdoc: "alam", payername: "mala", tests: (2) […] }
		$orderid = $this->request->getPost('orderid');
		$patid = $this->request->getPost('patid');
		$loc = $this->request->getPost('loc');
		$visitnumber = $this->request->getPost('visitnumber');
		$visitdate = $this->request->getPost('visitdate');
		$treatdoc = $this->request->getPost('treatdoc');
		$payername = $this->request->getPost('payername');
		$tests = $this->request->getPost('tests');
		// $reffid = $this->request->getPost('reffid');
		
		if($orderid == '0') { 
			$sql = "INSERT INTO cmod.dbo.CM_HIS_ORDERS (PATID, LOC, VISITNUMBER, VISITDATE, TREATDOC, PAYERNAME) 
				VALUES ('$patid', '$loc', '$visitnumber', '$visitdate', '$treatdoc', '$payername')";
		} else { 
			$sql = "UPDATE cmod.dbo.CM_HIS_ORDERS set PATID='$patid', LOC='$loc', VISITNUMBER='$visitnumber', VISITDATE='$visitdate',
				TREATDOC='$treatdoc', PAYERNAME='$payername' where ORDERID='$orderid'";  
		}
		
		// query HIS_ORDERS
		if( $db->query($sql) )  { 
			if($orderid == '0') { // new order
				$orderid = $db->insertID(); 
				$test = '';
				foreach($tests as $qtest) { $test .= "('$orderid', '$qtest'),"; }
				$test = rtrim($test, ",");
				$sql = "INSERT into cmod.dbo.CM_HIS_TESTS(ORDERID,HISCODE) VALUES $test";
			} else { // update
				$test = '';
				foreach($tests as $qtest) { $test .= "('$orderid', '$qtest'),"; }
				$test = rtrim($test, ",");				
				$sql = "MERGE INTO cmod.dbo.CM_HIS_TESTS AS t
					USING ( VALUES 
						$test
					) AS s (ORDERID, HISCODE) on s.ORDERID=t.ORDERID and s.HISCODE=t.HISCODE
					WHEN MATCHED THEN
						UPDATE SET TESTSTATUS=null
					WHEN NOT MATCHED BY TARGET THEN
						INSERT (ORDERID, HISCODE)
						VALUES (s.ORDERID, s.HISCODE)
					WHEN NOT MATCHED BY SOURCE and t.ORDERID='$orderid' THEN
						UPDATE SET TESTSTATUS=1;";
			}
			
			// done
			if( $db->query($sql) )  { 
				return $this->respond(['message' => 'Save Success', 'sql' => $sql],201);
			} else {
				$response = [
					'errors' => $db->errors(),
					'message' => 'Query test error',
					'sql' => $sql
				];
				return $this->fail($response , 409);
			}
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Query order error'
			];
			return $this->fail($response , 409);
        }
	}
	
	public function resend($visitnumber) {
		$db = \Config\Database::connect();
		$sql = "update cmod.dbo.CM_HIS_ORDERS set ISTAKEN=null where VISITNUMBER='$visitnumber'";
        if( $db->query($sql) )  { 
			return $this->respond(['message' => 'Update Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Query error'
			];
			return $this->fail($response , 409);
		}
	}
}
