<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckRole
{
    public function handle(Request $request, Closure $next, $role)
    {
        // Check if user is logged in
        if (!session()->has('role_id')) {
            return redirect()->route('login')->with('error', 'Please login first.');
        }

        // Map numeric role IDs to role names
        $roleMap = [
            1 => 'Admin',
            2 => 'User',          
        ];

        // Get the current user's role name
        $currentRoleName = $roleMap[session('role_id')] ?? 'Unknown';

        // Deny access if roles do not match
        if (strtolower($currentRoleName) !== strtolower($role)) {
            abort(403, 'Unauthorized Access.');
        }

        // Allow access
        return $next($request);
    }
}
