<?php

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

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

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

echo "====================================\n";
echo "Backfill License Keys for ImmigoPro Subscriptions\n";
echo "====================================\n\n";

// Find all active/completed subscriptions without license keys
$subscriptions = ImmigoProSubscription::whereIn('status', ['active', 'completed'])
    ->whereNull('license_key')
    ->orWhere('license_key', '')
    ->get();

echo "Found " . $subscriptions->count() . " subscriptions without license keys\n\n";

if ($subscriptions->isEmpty()) {
    echo "✓ All subscriptions already have license keys!\n";
    exit(0);
}

foreach ($subscriptions as $subscription) {
    echo "Processing subscription #" . $subscription->id . " (User ID: " . $subscription->user_id . ")\n";
    
    // Generate unique license key
    do {
        $key = 'IMGPRO-' . 
               strtoupper(substr(md5(uniqid(rand(), true)), 0, 4)) . '-' .
               strtoupper(substr(md5(uniqid(rand(), true)), 0, 4)) . '-' .
               strtoupper(substr(md5(uniqid(rand(), true)), 0, 4));
        
        $exists = ImmigoProSubscription::where('license_key', $key)->exists();
    } while ($exists);
    
    // Update subscription
    $subscription->update(['license_key' => $key]);
    
    echo "  ✓ Generated license key: " . $key . "\n";
    echo "  Status: " . $subscription->status . "\n";
    echo "  Package: " . $subscription->package_name . "\n";
    echo "  Payment Plan: " . $subscription->payment_plan . "\n\n";
}

echo "====================================\n";
echo "✓ Successfully backfilled " . $subscriptions->count() . " license keys\n";
echo "====================================\n";
