<?php

namespace App\Http\Middleware;

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

/**
 * Verifica que la suscripción de la empresa esté vigente. Si la suscripción
 * venció hace más de los días de gracia, se redirige a la pantalla de pago.
 */
class EnsurePlanIsActive
{
    public function handle(Request $request, Closure $next): Response
    {
        $company = Tenant::current();

        if (! $company) {
            return $next($request);
        }

        $subscription = $company->activeSubscription;

        if (! $subscription || ! $subscription->status->isActive()) {
            return $this->redirectToBilling($request);
        }

        $end = $subscription->current_period_end;
        if ($end && $end->lt(now()->subDays(config('reservapro.grace_days', 3)))) {
            return $this->redirectToBilling($request);
        }

        return $next($request);
    }

    protected function redirectToBilling(Request $request): Response
    {
        if ($request->expectsJson()) {
            abort(402, 'Suscripción inactiva o vencida.');
        }

        return redirect()->route('tenant.billing.expired');
    }
}
