<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

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

	public function index()	{
		$db = \Config\Database::connect();
		$sql = "select * from cmod.dbo.CM_DICT_TUBES";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['dictTubes'] = $results;
		
		return $this->respond($data, 200);
	}
	
	public function detail($tubeid)	{
		$data = array();
		$db = \Config\Database::connect();
		$sql = "select TUBECODE, TUBENAME from cmod.dbo.CM_DICT_TUBES where TUBEID='$tubeid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(isset($results[0])) { $data = $results[0]; }
		return $this->respond($data, 200);
	}
	
	public function save() {
		$tubecode = $this->request->getPost('tubecode');
		$tubename = $this->request->getPost('tubename');
		$tubeid = $this->request->getPost('tubeid');
        
		$db = \Config\Database::connect();
		if($tubeid == 0) { 
			$sql = "insert into cmod.dbo.CM_DICT_TUBES (TUBECODE, TUBENAME) VALUES ( '$tubecode', '$tubename' )";
		} else {
			$sql = "update cmod.dbo.CM_DICT_TUBES set TUBECODE='$tubecode', TUBENAME='$tubename' where TUBEID='$tubeid'";
		}
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalid Inputs'
			];
	       return $this->fail($response , 409);
        }
	}
}