<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

/**
 * legacy route filter `auth:admin` for print requests admin views
 * (approximated via elevated staff roles; extend if you use permission-based gates).
 */
class EnsurePrintRequestsAdminAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var User|null $user */
        $user = Auth::user();
        if (! $user) {
            return response()->json(['message' => 'Unauthorized.'], 401);
        }

        $roles = $user->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->toArray();

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

        return response()->json(['message' => 'Forbidden.'], 403);
    }
}
