<?php

namespace App\Http\Controllers;

use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;

class PaymentSuccessController extends Controller
{
    // Middleware is now registered in bootstrap/app.php for Laravel 12

    /**
     * Show payment confirmation page after successful checkout
     */
    public function show(Request $request): View
    {
        $user = $request->user();
        $sessionToken = $request->get('customer_session_token');

        Log::info('PaymentSuccessController: Showing payment confirmation', [
            'user_id' => $user->id,
            'session_token' => $sessionToken,
        ]);

        // Get the most recent subscription for this user created in the last 15 minutes
        // This ensures we're checking the subscription from the current payment session
        $recentMinutes = 15;
        $subscription = Subscription::where('user_id', $user->id)
            ->where('created_at', '>=', now()->subMinutes($recentMinutes))
            ->whereIn('status', ['pending_payment', 'incomplete', 'trialing', 'active']) // Likely statuses for new subscriptions
            ->orderBy('created_at', 'desc')
            ->first();

        // If no recent subscription found, fall back to the most recent one overall
        if (! $subscription) {
            Log::info('PaymentSuccessController: No recent subscription found, falling back to most recent', [
                'user_id' => $user->id,
                'minutes_checked' => $recentMinutes,
            ]);

            $subscription = Subscription::where('user_id', $user->id)
                ->orderBy('created_at', 'desc')
                ->first();
        }

        Log::info('PaymentSuccessController: Subscription selected for status checking', [
            'user_id' => $user->id,
            'subscription_id' => $subscription?->id,
            'provider_subscription_id' => $subscription?->provider_subscription_id,
            'provider' => $subscription?->provider,
            'status' => $subscription?->status,
            'created_at' => $subscription?->created_at,
            'is_recent' => $subscription && $subscription->created_at->diffInMinutes(now()) <= $recentMinutes,
        ]);

        return view('payment.success', [
            'user' => $user,
            'subscription' => $subscription,
            'sessionToken' => $sessionToken,
        ]);
    }
}
