<?php

namespace App\Models;

use App\Core\Model;

class Setting extends Model
{
    protected static string $table = 'iw_settings';

    /** In-memory cache – loaded once per request, eliminated repeated DB queries. */
    private static ?array $cache = null;

    public static function get(string $key, string $default = ''): string
    {
        if (self::$cache === null) {
            self::$cache = self::getAllAsMap();
        }
        return self::$cache[$key] ?? $default;
    }

    public static function set(string $key, string $value, string $group = 'general'): void
    {
        $existing = static::findWhere(['setting_key' => $key]);
        if ($existing) {
            static::updateById($existing['id'], ['setting_value' => $value]);
        } else {
            static::create([
                'setting_key'   => $key,
                'setting_value' => $value,
                'setting_group' => $group,
            ]);
        }
        // Invalidate cache so next get() reflects the change
        self::$cache = null;
    }

    public static function getByGroup(string $group): array
    {
        return static::where(['setting_group' => $group], 'setting_key', 'ASC');
    }

    public static function getAllAsMap(): array
    {
        $rows = static::all();
        $map = [];
        foreach ($rows as $row) {
            $map[$row['setting_key']] = $row['setting_value'];
        }
        return $map;
    }
}
