<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class DictTests extends ResourceController {
	protected $format = 'json';

	public function index()	{
		$db = \Config\Database::connect();
		$sql = "select TESTCODE, TEXT1, TEXT2 from cmod.dbo.CM_DICT_TESTS";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['dictTests'] = $results;
		
		return $this->respond($data, 200);
	}
	
	public function search()	{
		$db = \Config\Database::connect();
		$testcode = $this->request->getPost('testcode');
		$shorttext = $this->request->getPost('shorttext');
		$sql = "select dt.TESTCODE, dt.SHORTTEXT, cdt.TEXT1, cdt.TEXT2, cdt.UNIT, cdt.REFFTEXT from DICT_TESTS dt 
	left join cmod.dbo.CM_DICT_TESTS cdt on dt.TESTCODE=cdt.TESTCODE";
		// Initialize a WHERE clause
		$where= '';

		// Check if either testcode or shorttext is provided
		if (!empty($testcode) || !empty($shorttext)) {
			$where= ' WHERE ';
			if (!empty($testcode)) { $where .= "dt.TESTCODE like '%$testcode%'"; }
			if (!empty($shorttext)) {
				if (!empty($testcode)) { $where .= ' OR '; }
				$where .= "LOWER(dt.SHORTTEXT) LIKE '%$shorttext%'";
			}
		}
		$sql .= $where;
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['dictTests'] = $results;
		
		return $this->respond($data, 200);
	}
	
	public function detail($testcode)	{
		$data = array();
		$db = \Config\Database::connect();
		$sql = "select * from cmod.dbo.CM_DICT_TESTS where TESTCODE='$testcode'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(isset($results[0])) { $data = $results[0]; }
		return $this->respond($data, 200);
	}
	
	public function save() {
		$update = $this->request->getPost('update');
		$testcode = $this->request->getPost('testcode');
		$text1 = $this->request->getPost('text1');
		$text2 = $this->request->getPost('text2');
		$unit = $this->request->getPost('unit');
		$refftext = $this->request->getPost('refftext');
        
		$db = \Config\Database::connect();
		$sql = "INSERT INTO cmod.dbo.CM_DICT_TESTS (TESTCODE, TEXT1, TEXT2, REFFTEXT, LOGDATE ) VALUES ('$testcode', '$text1', '$text2', '$refftext' GETDATE())"; 
		$sql = "UPDATE cmod.dbo.CM_DICT_TESTS set TEXT1='$text1', TEXT2='$text2', REFFTEXT='$refftext', LOGDATE=GETDATE() where TESTCODE='$testcode'"; 
		
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalid Inputs'
			];
	       return $this->fail($response , 409);
        }
	}
}