<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  mixed ...$roles  // Accept multiple roles
     * @return mixed
     */
    public function handle(Request $request, Closure $next, ...$roles)
    {
        $user = Auth::user();

        if (!$user) {
            // Not logged in
            return redirect()->route('login');
        }

        // Check if user has any of the required roles
        foreach ($roles as $role) {
            if ($user->roles()->where('role', $role)->exists()) {
                return $next($request);
            }
        }

        // If no matching role found, deny access
       // abort(403, 'Unauthorized');
		
		return redirect('/')->with('error', 'Access denied.');
    }
}