<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * SettingsModel — key-value app settings.
 */
class SettingsModel extends Model
{
    protected $table       = 'settings';
    protected $primaryKey  = 'id';
    protected $returnType  = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = ['key', 'value'];

    private array $cache = [];

    public function getSetting(string $key, mixed $default = null): mixed
    {
        if (! isset($this->cache[$key])) {
            $row = $this->where('key', $key)->first();
            $this->cache[$key] = $row ? $row['value'] : $default;
        }
        return $this->cache[$key];
    }

    public function setSetting(string $key, mixed $value): void
    {
        $existing = $this->where('key', $key)->first();
        if ($existing) {
            $this->update($existing['id'], ['value' => $value]);
        } else {
            $this->insert(['key' => $key, 'value' => $value]);
        }
        $this->cache[$key] = $value;
    }

    public function getAllSettings(): array
    {
        $rows   = $this->findAll();
        $result = [];
        foreach ($rows as $row) {
            $result[$row['key']] = $row['value'];
        }
        return $result;
    }
}
