<?php

// Assign default plan to all existing users who don't have one
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

use Illuminate\Support\Facades\DB;

echo "=== ASSIGNING DEFAULT PLAN TO EXISTING USERS ===\n\n";

// Get the default plan
$defaultPlan = DB::table('user_plans')->where('is_default', true)->first();

if (!$defaultPlan) {
    echo "❌ No default plan found! Please set a plan as default first.\n";
    exit(1);
}

echo "Default Plan: {$defaultPlan->plan_name} (ID: {$defaultPlan->id})\n\n";

// Find users without a plan
$usersWithoutPlan = DB::table('users')
    ->whereNull('current_plan_id')
    ->get();

echo "Found {$usersWithoutPlan->count()} users without a plan\n\n";

if ($usersWithoutPlan->isEmpty()) {
    echo "✅ All users already have a plan assigned!\n";
} else {
    echo "Assigning default plan to users...\n";
    
    foreach ($usersWithoutPlan as $user) {
        DB::table('users')
            ->where('id', $user->id)
            ->update([
                'current_plan_id' => $defaultPlan->id,
                'plan_expires_at' => now()->addDays($defaultPlan->validity_days),
                'membership_type' => $defaultPlan->plan_name,
                'updated_at' => now()
            ]);
        
        echo "  ✅ {$user->name} (ID: {$user->id}) → {$defaultPlan->plan_name}\n";
    }
    
    echo "\n✅ Successfully assigned default plan to {$usersWithoutPlan->count()} users!\n";
}

// Summary
echo "\n=== SUMMARY ===\n";
$totalUsers = DB::table('users')->count();
$usersWithPlan = DB::table('users')->whereNotNull('current_plan_id')->count();
echo "Total Users: {$totalUsers}\n";
echo "Users with Plan: {$usersWithPlan}\n";
echo "Users without Plan: " . ($totalUsers - $usersWithPlan) . "\n";

echo "\n✅ All set! Users will now see their current plan in the mobile app.\n";
