<?php

namespace App\Http\Controllers;

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

class PaymentCancelController extends Controller
{
    /**
     * Show the payment cancellation page
     */
    public function show(Request $request)
    {
        // Get the session token from Polar if available
        $sessionToken = $request->get('customer_session_token');

        Log::info('PaymentCancelController: Cancellation page accessed', [
            'user_id' => auth()->id(),
            'session_token' => $sessionToken ? substr($sessionToken, 0, 20) . '...' : 'none',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        // Look for any recent subscriptions for this user
        $recentSubscription = null;
        if (auth()->check()) {
            $recentMinutes = 15; // Look for subscriptions in last 15 minutes
            $recentSubscription = Subscription::where('user_id', auth()->id())
                ->where('created_at', '>=', now()->subMinutes($recentMinutes))
                ->whereIn('status', ['pending_payment', 'incomplete', 'cancelled'])
                ->orderBy('created_at', 'desc')
                ->first();

            if ($recentSubscription) {
                Log::info('PaymentCancelController: Found recent subscription', [
                    'user_id' => auth()->id(),
                    'subscription_id' => $recentSubscription->id,
                    'status' => $recentSubscription->status,
                    'provider' => $recentSubscription->provider,
                ]);
            }
        }

        return view('payment.cancel', [
            'sessionToken' => $sessionToken,
            'recentSubscription' => $recentSubscription,
        ]);
    }
}