public function hasPermission(string $permission, ?Model $model = null, string $userForeignKey = 'user_id'): bool
    {
        // Check model's ownership
        if ($model && $model->{$userForeignKey} == $this->id) {
            return true;
        }

        // Check user's own permissions
        if ($this->permissions->pluck('code')->contains($permission)) {
            return true;
        }

        // Check user's groups permissions
        return $this->groups()->with('permissions')->get()->map->permissions->flatten()
                                                                            ->pluck('code')
                                                                            ->contains($permission);
    }