<?php

namespace App\Http\Middleware;

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

class CheckCompanyActive
{
    public function handle(Request $request, Closure $next): Response
    {
        if (!auth('web')->check()) {
            return $next($request);
        }

        $user    = auth('web')->user();
        $company = $user->company;

        if (!$company) {
            auth('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            return redirect()->route('login')
                ->withErrors(['company_code' => 'Your company account could not be found.']);
        }

        if ($company->status === 'suspended') {
            auth('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            return redirect()->route('login')
                ->withErrors(['company_code' => 'Your company account has been suspended. Please contact support.']);
        }

        if ($company->status === 'expired') {
            auth('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            return redirect()->route('login')
                ->withErrors(['company_code' => 'Your company subscription has expired. Please contact support.']);
        }

        // Auto-detect and update expired subscriptions
        $subscription = $company->subscription;
        if ($subscription && $subscription->isExpired()) {
            $company->update(['status' => 'expired']);
            auth('web')->logout();
            $request->session()->invalidate();
            $request->session()->regenerateToken();
            return redirect()->route('login')
                ->withErrors(['company_code' => 'Your subscription has expired. Please renew to continue.']);
        }

        return $next($request);
    }
}
