<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RoleMiddleware
{
    /**
     * Check whether the authenticated user
     * has one of the required roles.
     */
    public function handle(
        Request $request,
        Closure $next,
        ...$roles
    ): Response {
        // User must be logged in
        if (!auth()->check()) {
            return redirect()->route('login');
        }

        $user = auth()->user();

        $userRole = strtolower(trim($user->role->role_name ?? ''));

        $allowedRoles = collect($roles)
            ->map(fn ($role) => strtolower(trim($role)))
            ->toArray();

        if (!in_array($userRole, $allowedRoles)) {
            abort(403, 'You are not authorized to access this page.');
        }

        return $next($request);
    }
}