<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     *
        * Handle an incoming request and authorize it based on user role(s).
        *
        * @param  \Illuminate\Http\Request  $request  The incoming HTTP request.
        * @param  \Closure  $next  The next middleware or request handler.
        * @param  mixed  ...$roles  A variable list of roles that are authorized to access the route.
        * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
        */
public function handle(Request $request, Closure $next, ...$roles)
{
    // Retrieve the authenticated user from the request
    $user = $request->user();

    // Check if user is not authenticated or their role is not among the allowed roles
    if (!$user || !in_array($user->role, $roles)) {
        // Return a 403 Forbidden response if access is denied
        return response()->json(['error' => 'Unauthorized. Access denied.'], Response::HTTP_FORBIDDEN);
    }

    // Allow the request to proceed to the next middleware/controller
    return $next($request);
   }
}

