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

    public static function getAll(): array {
        if (self::$cache === null) {
            $rows = Database::get()->query(
                'SELECT setting_key, setting_value FROM app_settings'
            )->fetchAll();
            self::$cache = array_column($rows, 'setting_value', 'setting_key');
        }
        return self::$cache;
    }

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

    public static function set(string $key, string $value): void {
        Database::get()->prepare(
            'INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?)
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)'
        )->execute([$key, $value]);
        self::$cache = null;
    }

    public static function setMany(array $data): void {
        $db = Database::get();
        $stmt = $db->prepare(
            'INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?)
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)'
        );
        foreach ($data as $key => $value) {
            $stmt->execute([$key, $value]);
        }
        self::$cache = null;
    }

    public static function getAllWithMeta(): array {
        return Database::get()->query(
            'SELECT setting_key, setting_value, description FROM app_settings ORDER BY setting_key'
        )->fetchAll();
    }
}
