<?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\ImmigoProInstallmentPayment;
use App\Models\PaymentGateway;
use Stripe\Stripe;
use Stripe\PaymentIntent;

$subId = $argv[1] ?? null;

if (!$subId) {
    echo "Usage: php backfill_installment_payments.php <subscription_id>\n";
    exit(1);
}

$subscription = ImmigoProSubscription::find($subId);

if (!$subscription) {
    echo "Subscription not found\n";
    exit(1);
}

// Load Stripe
$gateway = PaymentGateway::where('provider', 'stripe')->first();
$secretKey = $gateway->is_live_mode ? $gateway->live_secret_key : $gateway->test_secret_key;
Stripe::setApiKey($secretKey);

echo "\n========================================\n";
echo "Backfilling Installment Payments\n";
echo "========================================\n";
echo "Subscription ID: {$subscription->id}\n";
echo "Package: {$subscription->package_name}\n";
echo "Payment Plan: {$subscription->payment_plan}\n";
echo "Paid Installments: {$subscription->paid_installments}/{$subscription->installments}\n\n";

// Get all payment intents for this subscription
echo "Fetching payment intents from Stripe...\n";
$paymentIntents = PaymentIntent::all([
    'limit' => 100,
]);

$savedCount = 0;

foreach ($paymentIntents->data as $pi) {
    // Check if this payment intent is for our subscription
    if (isset($pi->metadata->subscription_id) && 
        $pi->metadata->subscription_id == $subId && 
        isset($pi->metadata->installment_number) &&
        $pi->status === 'succeeded') {
        
        $installmentNumber = $pi->metadata->installment_number;
        
        // Check if we already have this payment recorded
        $existing = ImmigoProInstallmentPayment::where('subscription_id', $subId)
            ->where('installment_number', $installmentNumber)
            ->first();
        
        if ($existing) {
            echo "  Installment {$installmentNumber} already recorded (ID: {$existing->id})\n";
            continue;
        }
        
        // Create payment record
        $amount = $pi->amount / 100; // Convert from cents
        ImmigoProInstallmentPayment::create([
            'subscription_id' => $subscription->id,
            'installment_number' => $installmentNumber,
            'amount' => $amount,
            'stripe_payment_intent_id' => $pi->id,
            'status' => 'completed',
            'paid_at' => \Carbon\Carbon::createFromTimestamp($pi->created),
        ]);
        
        echo "  ✓ Saved installment {$installmentNumber} - \${$amount} (PI: {$pi->id})\n";
        $savedCount++;
    }
}

echo "\n========================================\n";
echo "✓ Backfill complete!\n";
echo "Saved {$savedCount} installment payment records\n";
echo "========================================\n";
