<?php

namespace App\Http\Middleware;

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

class RoleMiddleware
{
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        if (!Auth::check()) {
            return redirect()->route('login');
        }

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

        if (!in_array($userRole, $roles)) {
            // Redirect ke dashboard yang sesuai dengan role mereka
            return match ($userRole) {
                'admin'  => redirect()->route('admin.dashboard'),
                'guru'   => redirect()->route('guru.dashboard'),
                'kepsek' => redirect()->route('kepsek.dashboard'),
                default  => redirect()->route('login'),
            };
        }

        return $next($request);
    }
}
