<?php

namespace App\Http\Middleware;

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

class CheckRole
{
    /**
     * Handle role check. Usage in routes: ->middleware('role:superadmin')
     * or ->middleware('role:superadmin,reseller')
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        if (!$request->user()) {
            return redirect()->route('login');
        }

        if (!in_array($request->user()->role, $roles, true)) {
            abort(403, 'You do not have permission to access this page.');
        }

        if ($request->user()->status !== 'active') {
            auth()->logout();
            return redirect()->route('login')
                ->with('error', 'Your account is currently inactive. Please contact support.');
        }

        return $next($request);
    }
}
