0) { service('staffDirectorySync')->syncUser($userId); model(UserAccessProfileModel::class)->syncUser($userId); } } catch (\Throwable $e) { log_message('error', 'UserRoleModel role-derived sync failed: ' . $e->getMessage()); } return $data; } protected function syncStaffDirectoryAfterDelete(array $data): array { try { service('staffDirectorySync')->syncAll(); model(UserAccessProfileModel::class)->syncAll(); } catch (\Throwable $e) { log_message('error', 'UserRoleModel role-derived delete sync failed: ' . $e->getMessage()); } return $data; } /** * ✅ Fetch all role names assigned to a specific user * * @param int $userId * @return array Array of roles, e.g., [['name' => 'parent'], ['name' => 'teacher']] */ public function create() { $users = $this->db->table('users') ->select('users.*') ->join('user_roles', 'user_roles.user_id = users.id') ->join('roles', 'roles.id = user_roles.role_id') ->whereNotIn('roles.name', ['parent', 'teacher']) ->groupBy('users.id') // prevent duplicates if user has multiple roles ->get() ->getResultArray(); return view('expenses/create', ['users' => $users]); } /** * 🔁 Deprecated: Use getAllRolesByUserId instead * Get the first role name by user ID * * @param int $userId * @return string|null */ public function getRolesByUserId(int $userId): array { $roles = $this->select('roles.name as role_name') ->join('roles', 'roles.id = user_roles.role_id') ->where('user_roles.user_id', $userId) ->get() ->getResultArray(); // Always return an array return is_array($roles) ? $roles : []; } /** * ✅ Insert or update a role assignment * * @param int $userId * @param int $roleId * @return bool|int */ public function updateOrInsertRole($userId, $roleId) { // Check if this exact (user_id, role_id) already exists $exists = $this->where([ 'user_id' => $userId, 'role_id' => $roleId ])->first(); if ($exists) { // Already exists, nothing to do return true; } // Otherwise, insert new user-role mapping return $this->insert([ 'user_id' => $userId, 'role_id' => $roleId, 'updated_by' => session()->get('user_id') ]); } }