<?php
class Setting {
    private $pdo;

    public function __construct() {
        $this->pdo = $GLOBALS['pdo'];
    }

    public function get($key, $default = null) {
        $stmt = $this->pdo->prepare("SELECT value FROM settings WHERE `key` = ? LIMIT 1");
        if ($stmt->execute([$key]) && ($row = $stmt->fetch())) {
            return $row['value'];
        }
        return $default;
    }

    public function set($key, $value) {
        $stmt = $this->pdo->prepare("INSERT INTO settings (`key`,`value`,`updated_at`) VALUES (?,?,NOW()) ON DUPLICATE KEY UPDATE value = VALUES(value), updated_at = NOW()");
        return $stmt->execute([$key, $value]);
    }

    public function all() {
        $stmt = $this->pdo->query("SELECT `key`,`value` FROM settings");
        $out = [];
        foreach ($stmt->fetchAll() as $row) { $out[$row['key']] = $row['value']; }
        return $out;
    }
}

function get_setting($key, $default = null) {
    static $cache = null;
    if ($cache === null) {
        try { $model = new Setting(); $cache = $model->all(); } catch (Exception $e) { $cache = []; }
    }
    return array_key_exists($key, $cache) ? $cache[$key] : $default;
}
