<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, ...$roles): Response
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        $user = Auth::user();
        $userRole = $user->role;

        // Check if user has any of the required roles
        if (empty($userRole) || !in_array($userRole, $roles)) {
            // For API/AJAX requests, return generic 403 without exposing role requirements
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json([
                    'message' => 'Access denied.'
                ], 403);
            }
            
            // For web requests, silently redirect to dashboard
            // This prevents exposing that the route exists but requires specific role
            return redirect()->route('dashboard')->with('error', 'You do not have permission to access that page.');
        }

        return $next($request);
    }
}
