<?php

namespace App\Http\Middleware;

use App\Support\Tenancy;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Subscription gate for tenant dashboards.
 *  trialing/active → pass
 *  grace           → pass; views receive a banner flag (new bookings are
 *                    blocked at the action level from M2 on)
 *  suspended/none  → everything redirects to the billing screen
 */
class EnsureSubscriptionIsActive
{
    public function handle(Request $request, Closure $next): Response
    {
        // Billing + logout must stay reachable in every state.
        if ($request->routeIs('tenant.billing', 'tenant.billing.*', 'logout')) {
            return $next($request);
        }

        $subscription = app(Tenancy::class)->get()?->subscription;

        if ($subscription?->isActive()) {
            return $next($request);
        }

        if ($subscription?->inGrace()) {
            view()->share('subscriptionInGrace', true);
            view()->share('graceEndsAt', $subscription->grace_ends_at);

            return $next($request);
        }

        return redirect()
            ->route('tenant.billing')
            ->with('error', __('Your subscription has expired. Renew to regain access.'));
    }
}
