<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RoleMiddleware
{
    public function handle(Request $request, Closure $next, ...$roles)
    {
        $user = $request->user();

        if (!$user) {
            abort(403);
        }

        // allow: role:admin,candidate  (comma string) OR role:admin candidate (variadic)
        $allowed = [];
        foreach ($roles as $r) {
            foreach (explode(',', $r) as $rr) {
                $allowed[] = trim($rr);
            }
        }

        if (!in_array($user->role, $allowed, true)) {
            abort(403); // (404 না, 403 better)
        }

        return $next($request);
    }
}
