<?php

use App\Models\Tenant;
use App\Models\Tenant\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

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

// Get all active tenants
$tenants = Tenant::where('status', 'active')->get();

if ($tenants->isEmpty()) {
    echo "No active tenants found.\n";
    exit(1);
}

$validTenant = null;

foreach ($tenants as $tenant) {
    echo "Checking Tenant: {$tenant->name} (ID: {$tenant->id}, DB: {$tenant->database_name})... ";
    
    try {
        Config::set('database.connections.tenant.database', $tenant->database_name);
        DB::purge('tenant');
        DB::reconnect('tenant');
        DB::connection('tenant')->getPdo(); // Try to connect
        echo "Connected! ✅\n";
        $validTenant = $tenant;
        break;
    } catch (\Exception $e) {
        echo "Failed to connect (DB might not exist). ❌\n";
    }
}

if (!$validTenant) {
    echo "Could not connect to any tenant database.\n";
    exit(1);
}

echo "\nUpdating settings for Tenant: {$validTenant->name} (ID: {$validTenant->id})\n";
DB::setDefaultConnection('tenant');

$faker = Faker\Factory::create();

// Generate Random Settings
$newSettings = [
    'store_name' => $faker->company . ' Store',
    'currency' => $faker->currencyCode,
    'currency_symbol' => '$', 
    'timezone' => $faker->timezone,
    'theme_color' => $faker->hexColor,
    'loyalty_enabled' => $faker->boolean ? '1' : '0',
    'loyalty_conversion_rate' => (string)rand(50, 200),
    'report_header' => "Report for " . date('Y') . " - " . $faker->word,
    'report_footer' => "Generated by " . $faker->company,
];

echo "\n--- Applying New Settings ---\n";
foreach ($newSettings as $key => $value) {
    Setting::set($key, $value);
    echo "Set [$key] = $value\n";
}

echo "\n--- Verifying Saved Settings ---\n";
$allMatch = true;
foreach ($newSettings as $key => $value) {
    $stored = Setting::get($key);
    if ($stored === $value) {
        echo "✅ $key: $stored\n";
    } else {
        echo "❌ $key: Expected '$value', got '$stored'\n";
        $allMatch = false;
    }
}

if ($allMatch) {
    echo "\n🎉 Success! All settings updated and verified.\n";
} else {
    echo "\n⚠️  Some settings failed verification.\n";
}
