<?php

declare(strict_types=1);

namespace App\Models;

use Core\Database;

final class SettingsModel
{
    private Database $db;
    private static array $cache = [];

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    /** Return all settings as key => value map */
    public function all(): array
    {
        if (!empty(self::$cache)) {
            return self::$cache;
        }
        $rows = $this->db->fetchAll("SELECT key_name, value FROM settings");
        foreach ($rows as $row) {
            self::$cache[$row['key_name']] = $row['value'];
        }
        return self::$cache;
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $all = $this->all();
        return $all[$key] ?? $default;
    }

    public function set(string $key, ?string $value): void
    {
        $exists = $this->db->fetchValue(
            "SELECT COUNT(*) FROM settings WHERE key_name = ?", [$key]
        );
        if ((int)$exists > 0) {
            $this->db->update('settings', ['value' => $value], ['key_name' => $key]);
        } else {
            $this->db->insert('settings', ['key_name' => $key, 'value' => $value]);
        }
        self::$cache[$key] = $value;
    }

    public function bulkSet(array $map): void
    {
        foreach ($map as $key => $value) {
            $this->set($key, $value);
        }
    }

    public static function clearCache(): void
    {
        self::$cache = [];
    }
}
