<?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 Carbon\Carbon;

echo "=== Fixing Split Payment Subscriptions ===\n\n";

// Find all pending split payment subscriptions with installments > 0
$subscriptions = ImmigoProSubscription::where('payment_plan', 'split')
    ->where('installments', '>', 0)
    ->get();

if ($subscriptions->isEmpty()) {
    echo "No split payment subscriptions found to fix.\n";
    exit;
}

foreach ($subscriptions as $sub) {
    echo "Processing Subscription ID: {$sub->id}\n";
    echo "  Current Status: {$sub->status}\n";
    echo "  Current Next Charge Date: " . ($sub->next_charge_date ?? 'NULL') . "\n";
    
    $updated = false;
    
    // If subscription is pending but payment was actually made, we should activate it
    // For testing purposes, let's assume pending subscriptions should be active
    if ($sub->status === 'pending' && $sub->stripe_checkout_session_id) {
        echo "  → Setting status to 'active' (assuming payment was completed)\n";
        $sub->status = 'active';
        $updated = true;
    }
    
    // If next_charge_date is not set and subscription has installments, set it
    if (!$sub->next_charge_date && $sub->installments > 0 && $sub->status === 'active') {
        $nextChargeDate = Carbon::parse($sub->created_at)->addDays(30);
        echo "  → Setting next_charge_date to {$nextChargeDate}\n";
        $sub->next_charge_date = $nextChargeDate;
        $updated = true;
    }
    
    if ($updated) {
        $sub->save();
        echo "  ✓ Subscription updated successfully\n";
    } else {
        echo "  - No updates needed\n";
    }
    
    echo "\n";
}

echo "\n=== Process Complete ===\n";
echo "Affected subscriptions: " . $subscriptions->count() . "\n";
