<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class API_Users extends ResourceController {
	protected $format = 'json';
	
	public function index()	{
		$db = \Config\Database::connect();

		$usercityid = session()->get('usercityid');
		if($usercityid==1){$filterquery=" AND uc.CITYID = 1";}
		else if($usercityid==2){$filterquery=" AND uc.CITYID = 2";}
		else{$filterquery=" ";}

		$sql = "select u.USERID, u.USERNAME, uc.CITYNAME ,u1.USERROLEID, ur.USERROLENAME 
				from cmod.dbo.CM_USERS u1 
				full join USERS u on u.USERID=u1.USERID
				left join cmod.dbo.CM_USERS us on us.USERID=u.USERID
				left join cmod.dbo.CM_USERSCITY uc on uc.CITYID=us.CITYID
				left join cmod.dbo.CM_USERROLES ur on ur.USERROLEID=u1.USERROLEID
				where ( u.LOCKEDACCOUNT is null or u.LOCKEDACCOUNT=0 ) $filterquery";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		
		$data['users'] = $results;
        return $this->respond($data,200);
	}
	
	public function savePass() {
		$db = \Config\Database::connect();
		$userid = $this->request->getPost('userid');
		$pass = $this->request->getPost('pass');
		$password = password_hash($pass,PASSWORD_DEFAULT);
		$sql = "update cmod.dbo.CM_USERS set PASSWORD='$password' where USERID='$userid'";
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalids'
			];
	       return $this->fail($response , 409);
        }
	}
	
	public function saveRole() {
		$db = \Config\Database::connect();
		$userid = $this->request->getPost('userid');
		$userroleid = $this->request->getPost('userroleid');
		$sql = "if (not exists (select * from cmod.dbo.CM_USERS where USERID='$userid')) BEGIN
		INSERT INTO cmod.dbo.CM_USERS(USERID, USERROLEID, CREATEDATE) VALUES
			('$userid','$userroleid', GETDATE())
	END ELSE BEGIN
		UPDATE cmod.dbo.CM_USERS set USERROLEID='$userroleid' where USERID='$userid'
	END";
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalids'
			];
	       return $this->fail($response , 409);
        }
	}
}