<?php

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

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

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

echo "\n=== Activating Pending Subscriptions ===\n\n";

// Find all pending subscriptions with session IDs
$subscriptions = Subscription::where('status', 'pending')
    ->whereNotNull('stripe_session_id')
    ->get();

if ($subscriptions->isEmpty()) {
    echo "No pending subscriptions found.\n";
    exit(0);
}

foreach ($subscriptions as $subscription) {
    echo "Processing Subscription ID: {$subscription->id}\n";
    echo "  User ID: {$subscription->user_id}\n";
    echo "  Package: {$subscription->package_name}\n";
    echo "  Session ID: {$subscription->stripe_session_id}\n";
    
    // Calculate subscription period
    $currentPeriodStart = now();
    $interval = $subscription->interval ?? 'month';
    $currentPeriodEnd = match($interval) {
        'month' => now()->addMonth(),
        'year' => now()->addYear(),
        'week' => now()->addWeek(),
        default => now()->addMonth(),
    };
    
    // Update subscription
    $subscription->update([
        'status' => 'active',
        'activated_at' => now(),
        'current_period_start' => $currentPeriodStart,
        'current_period_end' => $currentPeriodEnd,
        'expires_at' => $currentPeriodEnd,
    ]);
    
    echo "  ✓ Activated successfully\n";
    echo "  Period: {$currentPeriodStart} to {$currentPeriodEnd}\n\n";
}

echo "=== All pending subscriptions activated ===\n";
