<?php
// app/Models/Setting.php
// إعدادات المنصة (مفتاح/قيمة)

class Setting {
    private static array $cache = [];

    public static function get(string $key, ?string $default = null): ?string {
        if (array_key_exists($key, self::$cache)) return self::$cache[$key];
        $s = db()->prepare('SELECT setting_value FROM settings WHERE setting_key=?');
        $s->execute([$key]);
        $v = $s->fetchColumn();
        self::$cache[$key] = ($v === false) ? $default : $v;
        return self::$cache[$key];
    }

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

    public static function all(): array {
        $rows = db()->query('SELECT setting_key, setting_value FROM settings')->fetchAll();
        $out = [];
        foreach ($rows as $r) $out[$r['setting_key']] = $r['setting_value'];
        return $out;
    }
}
