<?php

namespace App\Http\Middleware;

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

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next, ...$roles): Response
    {
        if (!$request->user() || !($request->user() instanceof \App\Models\AdminUser)) {
            return redirect()->route('admin.login');
        }

        foreach ($roles as $role) {
            if ($request->user()->hasRole($role)) {
                return $next($request);
            }
        }

        if ($request->ajax()) {
            return response()->json(['error' => 'Unauthorized.'], 403);
        }

        return redirect()->route('admin.dashboard')->with('error', 'You do not have permission to access this section.');
    }
}
