<?php

declare(strict_types=1);

class Settings
{
    private static ?array $cache = null;

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

    public static function getInt(string $key, int $default = 0): int
    {
        $value = self::get($key, (string)$default);
        return (int)$value;
    }

    public static function getBool(string $key, bool $default = false): bool
    {
        $value = self::get($key, $default ? '1' : '0');
        return $value === '1' || $value === 'true' || $value === 'yes';
    }

    public static function load(): void
    {
        self::$cache = [];
        try {
            $pdo = Database::pdo();
            $stmt = $pdo->query('SELECT setting_key, setting_value FROM settings');
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $row) {
                $key = (string)($row['setting_key'] ?? '');
                $value = (string)($row['setting_value'] ?? '');
                if ($key !== '') {
                    self::$cache[$key] = $value;
                }
            }
        } catch (Throwable $e) {
            self::$cache = [];
        }
    }

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

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