<?php
/// file: app/Models/SiteSetting.php

declare(strict_types=1);

namespace App\Models;

use App\Core\Database;
use PDO;

final class SiteSetting
{
    public static function get(string $key, ?string $default = null): ?string
    {
        $st = Database::pdo()->prepare('SELECT setting_value FROM site_settings WHERE setting_key = ? LIMIT 1');
        $st->execute([$key]);
        $v = $st->fetchColumn();
        return $v !== false && $v !== null ? (string) $v : $default;
    }

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

    /** @return array<string, string> */
    public static function allAssoc(): array
    {
        $st = Database::pdo()->query('SELECT setting_key, setting_value FROM site_settings');
        $rows = $st->fetchAll(PDO::FETCH_KEY_PAIR);
        return is_array($rows) ? $rows : [];
    }
}
