<?php

namespace App\Policies;

use App\Models\SupportRequest;
use App\Models\User;

class SupportRequestPolicy
{
    public function viewAny(User $user): bool
    {
        return $user !== null;
    }

    public function view(User $user, SupportRequest $request): bool
    {
        return $request->user_id === $user->id || $this->isAdmin($user);
    }

    public function create(User $user): bool
    {
        return $user !== null;
    }

    private function isAdmin(User $user): bool
    {
        $roles = $user->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->toArray();

        foreach (['administrator', 'admin', 'principal', 'vice_principal', 'vice-principal'] as $role) {
            if (in_array($role, $roles, true)) {
                return true;
            }
        }

        return false;
    }
}
