<?php

namespace App\Http\Middleware;

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

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

        $user = auth()->user();
        $subscription = $user->subscription;

        // If no subscription or not on trial, allow access
        if (!$subscription || !$subscription->isTrialExpired()) {
            return $next($request);
        }

        // Trial expired - check if card was saved
        if ($subscription->hasCardSaved()) {
            // Card was saved, auto-billing will handle it
            return $next($request);
        }

        // Trial expired and no card saved - redirect to payment completion
        if (!$request->is('trial-payment', 'trial-payment/*', 'api/*')) {
            return redirect()->route('trial-payment.show')->with('trial_expired', true);
        }

        return $next($request);
    }
}
