<?php

// Test the /api/plans endpoint for test@clxpro.in user
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 "=== TESTING /api/plans ENDPOINT ===\n\n";

$user = DB::table('users')->where('email', 'test@clxpro.in')->first();

if (!$user) {
    echo "❌ User not found!\n";
    exit(1);
}

echo "User: {$user->name} (ID: {$user->id})\n";
echo "Current Plan ID: " . ($user->current_plan_id ?? 'NULL') . "\n";
echo "Membership Type: " . ($user->membership_type ?? 'NULL') . "\n\n";

// Simulate API response
$plans = DB::table('user_plans')
    ->where('status', 'Active')
    ->orderBy('price', 'asc')
    ->get();

$apiResponse = [
    'plans' => [],
    'current_plan_id' => $user->current_plan_id,
    'currency_symbol' => '₹'
];

echo "API Response will be:\n";
echo "{\n";
echo "  \"current_plan_id\": " . ($user->current_plan_id ?? 'null') . ",\n";
echo "  \"currency_symbol\": \"₹\",\n";
echo "  \"plans\": [\n";

foreach ($plans as $i => $plan) {
    $comma = $i < count($plans) - 1 ? ',' : '';
    echo "    {\n";
    echo "      \"id\": {$plan->id},\n";
    echo "      \"name\": \"{$plan->plan_name}\",\n";
    echo "      \"price\": {$plan->price}\n";
    echo "    }{$comma}\n";
    
    $apiResponse['plans'][] = [
        'id' => $plan->id,
        'name' => $plan->plan_name,
        'price' => $plan->price
    ];
}

echo "  ]\n";
echo "}\n\n";

// Show what Flutter will do
echo "=== FLUTTER APP LOGIC ===\n\n";
echo "The app will compare each plan['id'] with current_plan_id:\n\n";

foreach ($plans as $plan) {
    $isCurrent = $plan->id == $user->current_plan_id;
    $comparison = "{$plan->id} == " . ($user->current_plan_id ?? 'NULL');
    $result = $isCurrent ? 'TRUE ✓' : 'FALSE';
    $buttonText = $isCurrent ? 'Current Plan ✓' : "Upgrade to {$plan->plan_name}";
    
    echo "Plan: {$plan->plan_name}\n";
    echo "  Comparison: {$comparison} = {$result}\n";
    echo "  Button will show: [{$buttonText}]\n\n";
}

if (!$user->current_plan_id) {
    echo "⚠️  PROBLEM FOUND!\n";
    echo "current_plan_id is NULL in database!\n";
    echo "This is why all plans show 'Upgrade to...' instead of 'Current Plan ✓'\n\n";
    echo "Fixing it now...\n";
    
    $defaultPlan = DB::table('user_plans')->where('is_default', true)->first();
    if ($defaultPlan) {
        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 "✅ Fixed! User now has plan ID: {$defaultPlan->id}\n";
        echo "✅ Please logout and login again in the app!\n";
    }
}
