<?php

namespace App\Http\Middleware;

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

class EnsureSubscriptionIsActive
{
    /**
     * Handle an incoming request.
     * Redirect to the correct activation flow if the user is not active.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        // Admin always bypass
        if ($user && $user->isAdmin()) {
            return $next($request);
        }

        if ($user && !$user->isActive()) {
            // Determine the correct "Required" route based on role
            $routeName = $user->isLeasing() ? 'leasing.plans.index' : 'member.plans.index';
            
            // If the user already has a pending payment, redirect to the payment status/show page
            $hasPendingSub = $user->subscriptions()->where('subscription_status', 'inactive')->exists();
            if ($hasPendingSub) {
                $routeName = $user->isLeasing() ? 'leasing.payment.show' : 'member.payment.show';
            }

            // Avoid infinite loops if already on these activation pages
            $activationRoutes = [
                'payment.required',
                'leasing.plans.index', 'leasing.plans.select', 'leasing.payment.show', 'leasing.payment.store',
                'member.plans.index', 'member.plans.select', 'member.payment.show', 'member.payment.store',
                'payment.checkout', 'payment.store'
            ];

            if ($request->routeIs($activationRoutes)) {
                return $next($request);
            }

            return redirect()->route($routeName)->with('error', 'Layanan Anda belum aktif. Silakan pilih paket atau selesaikan pembayaran.');
        }

        return $next($request);
    }
}
