<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

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

	public function index()	{
		$db = \Config\Database::connect();
		$sql = "select * from cmod.dbo.CM_USERROLES";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userroles'] = $results;
		
		return $this->respond($data, 200);
	}
	
	public function detail($userroleid)	{
		$db = \Config\Database::connect();
		$sql = "select * from cmod.dbo.CM_USERROLES where USERROLEID='$userroleid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data = $results[0];
		return $this->respond($data, 200);
	}
	
	public function save($userroleid) {
		$userrolename = $this->request->getPost('userrolename');
        
		$db = \Config\Database::connect();
		if($userroleid == 0) { // new
			$sql = "INSERT INTO cmod.dbo.CM_USERROLES(USERROLENAME, CREATEDATE) VALUES ('$userrolename', GETDATE())"; 
		} else { //update
			$sql = "UPDATE cmod.dbo.CM_USERROLES set USERROLENAME='$userrolename' where USERROLEID='$userroleid'"; 
		}
		
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalid Inputs'
			];
	       return $this->fail($response , 409);
        }
	}
}