<?php

require __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

use App\Models\ImmigoProSubscription;
use App\Models\User;

echo "=== Testing Installment Payment API ===\n\n";

// Find an active subscription with installments
$subscription = ImmigoProSubscription::where('status', 'active')
    ->where('installments', '>', 0)
    ->where('paid_installments', '<', \DB::raw('installments'))
    ->first();

if (!$subscription) {
    echo "No active subscriptions with unpaid installments found.\n";
    exit;
}

echo "Subscription found:\n";
echo "  ID: {$subscription->id}\n";
echo "  User ID: {$subscription->user_id}\n";
echo "  Package: {$subscription->package_name}\n";
echo "  Payment Plan: {$subscription->payment_plan}\n";
echo "  Total Installments: {$subscription->installments}\n";
echo "  Paid Installments: {$subscription->paid_installments}\n";
echo "  Next Installment: " . ($subscription->paid_installments + 1) . "\n";
echo "  Monthly Amount: \${$subscription->monthly_amount}\n";
echo "  Next Charge Date: " . ($subscription->next_charge_date ?? 'Not set') . "\n";

$user = User::find($subscription->user_id);
if ($user) {
    echo "\nUser Info:\n";
    echo "  Name: {$user->first_name} {$user->last_name}\n";
    echo "  Email: {$user->email}\n";
    echo "  Stripe Customer ID: " . ($user->stripe_customer_id ?? 'Not set') . "\n";
}

echo "\nPayment Method:\n";
echo "  Stripe Payment Method ID: " . ($subscription->stripe_payment_method_id ?? 'Not set') . "\n";

if (!$subscription->stripe_payment_method_id) {
    echo "\n⚠️  WARNING: No payment method on file!\n";
    echo "The user won't be able to pay the installment until a payment method is saved.\n";
}

echo "\n=== API Endpoint ===\n";
echo "POST /api/v1/immigopro-subscriptions/{$subscription->id}/pay-installment\n";
echo "\nRequest Body:\n";
echo json_encode([
    'installment_number' => $subscription->paid_installments + 1,
    'success_url' => 'http://localhost:5178/client/dashboard?payment=success',
    'cancel_url' => 'http://localhost:5178/client/dashboard?payment=cancelled',
], JSON_PRETTY_PRINT);

echo "\n\n=== Ready to Test ===\n";
echo "The Pay Now button should now work on the dashboard!\n";
