<?php

namespace App\Http\Middleware;

use App\Models\SiteSetting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckActiveSubscription
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (! SiteSetting::paymentModeEnabled()) {
            return $next($request);
        }

        if ($this->shouldBypassSubscriptionCheck($request)) {
            return $next($request);
        }

        $user = $request->user();

        if (! $user) {
            return redirect()->route('login');
        }

        if ($user->isAdmin()) {
            return $next($request);
        }

        if (SiteSetting::allowFreeAccess()) {
            return $next($request);
        }

        if ($user->hasActiveSubscription()) {
            return $next($request);
        }

        if ($user->isWithinFreeTrial(SiteSetting::freeTrialDays())) {
            return $next($request);
        }

        if ($user->hasSubscriptionGracePeriod(SiteSetting::subscriptionGraceDays())) {
            return $next($request);
        }

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'An active subscription is required to access this feature.',
            ], 402);
        }

        return redirect()
            ->route('pricing')
            ->with('error', 'Please choose a subscription plan to continue using ViZuTrade.');
    }

    private function shouldBypassSubscriptionCheck(Request $request): bool
    {
        return $request->routeIs('pricing')
            || $request->routeIs('login')
            || $request->routeIs('register')
            || $request->routeIs('logout')
            || $request->routeIs('password.*')
            || $request->routeIs('admin.*')
            || $request->is('/')
            || $request->is('payments')
            || $request->is('payments/*');
    }
}
