<?php

namespace Modules\ProductCompat\Entities\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * Tiny key/value settings store (pc_settings) with per-request caching and a
 * graceful fallback before the table exists. UI-editable values (Icecat
 * username, API keys, automation toggles) live here and override config/env.
 */
class Settings
{
    protected static ?array $cache = null;

    public static function all(): array
    {
        if (static::$cache !== null) {
            return static::$cache;
        }
        if (! Schema::hasTable('pc_settings')) {
            return static::$cache = [];
        }

        return static::$cache = DB::table('pc_settings')->pluck('value', 'key')->toArray();
    }

    public static function get(string $key, $default = null)
    {
        $all = static::all();
        $val = $all[$key] ?? null;

        return ($val === null || $val === '') ? $default : $val;
    }

    public static function bool(string $key, bool $default = false): bool
    {
        $v = static::get($key, $default ? '1' : '0');

        return in_array((string) $v, ['1', 'true', 'on', 'yes'], true);
    }

    public static function set(string $key, $value): void
    {
        if (! Schema::hasTable('pc_settings')) {
            return;
        }
        DB::table('pc_settings')->updateOrInsert(
            ['key' => $key],
            ['value' => is_array($value) ? json_encode($value) : (string) $value, 'updated_at' => now(), 'created_at' => now()]
        );
        static::$cache = null; // bust cache
    }
}
