<?php

namespace App\Models;

use App\Core\Model;

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

    public static function get(string $key, string $default = ''): string
    {
        $row = static::findWhere(['setting_key' => $key]);
        return $row ? $row['setting_value'] : $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,
            ]);
        }
    }

    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;
    }
}
