<?php

namespace App\Http\Middleware;

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

class CheckRole
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next, string $role): Response
    {
        $userData = session('user_data');

        // Cek apakah user sudah login
        if (!$userData) {
            return redirect()->route('login');
        }

        // Cek apakah role sesuai
        if (!isset($userData['role']) || $userData['role'] !== $role) {
            abort(403, 'Akses ditolak. Anda tidak memiliki izin untuk mengakses halaman ini.');
        }

        return $next($request);
    }
}