<?php
  
  namespace Api\Controllers;
  
  use Api\Core\Controller;
  use Api\Services\UserService;
  use PDO;
  
  class UserRoleController extends Controller
  {
    public function index($user) {
      $user = UserService::getByID($user);
      if (!$user) api()->notFound('USER_NOT_FOUND', 'User not found!');
      
      $roles = db()->prepare("SELECT R.id, R.name, R.slug, R.priority, R.discordRoleID, AR.expiryDate FROM AccountRoles AR INNER JOIN Roles R ON R.id = AR.roleID WHERE AR.accountID = ?");
      $roles->execute([$user['id']]);
      $roles = $roles->fetchAll(PDO::FETCH_ASSOC);
      
      response()->json($roles);
    }
		
		public function store($user) {
			validate([
				'roleID' => 'required',
				'expiryDate' => 'nullable|date:Y-m-d H:i:s',
			]);
			
			$user = UserService::getByID($user);
			if (!$user) api()->notFound('USER_NOT_FOUND', 'User not found!');
			
			if (input('expiryDate') == null) {
				set_input('expiryDate', '1000-01-01 00:00:00');
			}
			
			$role = db()->prepare("SELECT * FROM Roles WHERE id = ?");
			$role->execute([input('roleID')]);
			$role = $role->fetch(PDO::FETCH_ASSOC);
			
			if (!$role) api()->notFound('ROLE_NOT_FOUND', 'Role not found!');
			
			$insertRole = db()->prepare('INSERT INTO AccountRoles (accountID, roleID, expiryDate) VALUES (?, ?, ?)');
			$insertRole->execute([$user['id'], input('roleID'), input('expiryDate')]);
			
			api()->success();
		}
		
		public function update($user, $id) {
			validate([
				'roleID' => 'required',
				'expiryDate' => 'nullable|date:Y-m-d H:i:s',
			]);
			
			$user = UserService::getByID($user);
			if (!$user) api()->notFound('USER_NOT_FOUND', 'User not found!');
			
			if (input('expiryDate') == null) {
				set_input('expiryDate', '1000-01-01 00:00:00');
			}
			
			$role = db()->prepare("SELECT * FROM AccountRoles WHERE accountID = ? AND roleID = ?");
			$role->execute([$user['id'], $id]);
			$role = $role->fetch(PDO::FETCH_ASSOC);
			
			if (!$role) api()->notFound('ROLE_NOT_FOUND', 'Role not found!');
			
			$updateRole = db()->prepare('UPDATE AccountRoles SET roleID = ?, expiryDate = ? WHERE accountID = ? AND roleID = ?');
			$updateRole->execute([input('roleID'), input('expiryDate'), $user['id'], $id]);
			
			api()->success();
		}
		
		public function destroy($user, $id) {
			$user = UserService::getByID($user);
			if (!$user) api()->notFound('USER_NOT_FOUND', 'User not found!');
			
			$role = db()->prepare("SELECT * FROM AccountRoles WHERE accountID = ? AND roleID = ?");
			$role->execute([$user['id'], $id]);
			$role = $role->fetch(PDO::FETCH_ASSOC);
			
			if (!$role) api()->notFound('ROLE_NOT_FOUND', 'Role not found!');
			
			$deleteRole = db()->prepare('DELETE FROM AccountRoles WHERE accountID = ? AND roleID = ?');
			$deleteRole->execute([$user['id'], $id]);
			
			api()->success();
		}
  }