<?php

namespace App\Http\Middleware;

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

class EmployerMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = auth()->check() ? auth()->user() : session('user');
        $role = is_array($user) ? ($user['role'] ?? null) : ($user->role ?? null);
        $subStatus = is_array($user) ? ($user['subscription_status'] ?? 'none') : ($user->subscription_status ?? 'none');

        if (!$user || $role !== 'employer') {
            return redirect()->route('employer.login');
        }

        if ($subStatus !== 'active' && !$request->routeIs('employer.subscription')) {
            return redirect()->route('employer.subscription')->with('error', 'Please purchase a subscription to access the portal.');
        }

        return $next($request);
    }
}
