<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle(Request $request, Closure $next, string $role)
    {
        $user = Auth::user();

        if (!$user || !$user->is_active) {
            Auth::logout();
            return redirect()->route('login')->with('error', 'আপনার একাউন্টটি সাময়িকভাবে বন্ধ আছে।');
        }

        if ($user->role !== $role) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Unauthorized role access denied.'], 403);
            }
            return redirect()->route('dashboard')->with('error', 'এই পেজটি দেখার অনুমতি আপনার নেই।');
        }

        return $next($request);
    }
}
