<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

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

	public function index()	{
		$db = \Config\Database::connect();
		$sql = "select dc.CHAPCODE, dc.SHORTTEXT, cdc.TEXT1, cdc.TEXT2 from DICT_CHAPTERS dc
			left join cmod.dbo.CM_DICT_CHAPTERS cdc on dc.CHAPCODE=cdc.CHAPCODE
			where left(dc.SHORTTEXT,2)<>'CH'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['dictChapters'] = $results;
		
		return $this->respond($data, 200);
	}
	
	public function detail($chapcode)	{
		$data = array();
		$db = \Config\Database::connect();
		$sql = "select dc.CHAPCODE, dc.SHORTTEXT, cdc.TEXT1, cdc.TEXT2 from DICT_CHAPTERS dc
	left join cmod.dbo.CM_DICT_CHAPTERS cdc on dc.CHAPCODE=cdc.CHAPCODE 
	where dc.CHAPCODE='$chapcode'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(isset($results[0])) { $data = $results[0]; }
		return $this->respond($data, 200);
	}
	
	public function save() {
		$chapcode = $this->request->getPost('chapcode');
		$text1 = $this->request->getPost('text1');
		$text2 = $this->request->getPost('text2');
        
		$db = \Config\Database::connect();
		$sql = "MERGE INTO cmod.dbo.CM_DICT_CHAPTERS AS t
			USING ( VALUES ('$chapcode', '$text1', '$text2')
			) AS s (CHAPCODE, TEXT1, TEXT2) on t.CHAPCODE=s.CHAPCODE
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (CHAPCODE, TEXT1, TEXT2)
				VALUES (s.CHAPCODE, s.TEXT1, s.TEXT2)
			WHEN MATCHED THEN
				UPDATE set TEXT1=s.TEXT1, TEXT2=s.TEXT2;";
		//echo "<pre>$sql</pre>";
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalid Inputs'
			];
	       return $this->fail($response , 409);
        }
	}
}