<?php

namespace App\Http\Middleware;

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

class EnsureUserHasRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next, string $roles): Response
    {
        $user = $request->user();

        // Support multiple roles separated by comma or pipe
        $allowed = preg_split('/[|,]/', $roles);
        $allowed = array_filter(array_map('trim', $allowed));

        if (! $user || (count($allowed) > 0 && ! in_array($user->role, $allowed, true))) {
            abort(403, 'Anda tidak memiliki akses ke halaman ini.');
        }

        return $next($request);
    }
}
