<?php
class Config
{
    private static ?array $cache = null;

    public static function get(string $key, $default = null)
    {
        if (self::$cache === null) {
            self::load();
        }
        return self::$cache[$key] ?? $default;
    }

    public static function set(string $key, $value): void
    {
        if (self::$cache === null) {
            self::load();
        }
        self::$cache[$key] = $value;
    }

    public static function all(): array
    {
        if (self::$cache === null) {
            self::load();
        }
        return self::$cache;
    }

    public static function getGroup(string $group): array
    {
        try {
            $db = Database::getInstance();
            $rows = $db->fetchAll(
                "SELECT config_key, config_value, config_type FROM sys_config WHERE config_group = ?",
                [$group]
            );
            $result = [];
            foreach ($rows as $row) {
                $result[$row['config_key']] = self::castValue($row['config_value'], $row['config_type']);
            }
            return $result;
        } catch (\Exception $e) {
            return [];
        }
    }

    private static function load(): void
    {
        self::$cache = [];
        try {
            $db = Database::getInstance();
            $rows = $db->fetchAll("SELECT config_key, config_value, config_type FROM sys_config");
            foreach ($rows as $row) {
                self::$cache[$row['config_key']] = self::castValue($row['config_value'], $row['config_type']);
            }
        } catch (\Exception $e) {
            // DB not available yet, empty cache
        }
    }

    private static function castValue($value, string $type)
    {
        return match ($type) {
            'integer' => (int) $value,
            'decimal' => (float) $value,
            'boolean' => in_array(strtolower($value), ['true', '1', 'yes']),
            'json'    => json_decode($value, true),
            default   => $value,
        };
    }

    public static function clearCache(): void
    {
        self::$cache = null;
    }
}