<?php

namespace App\Models;

use CodeIgniter\Model;

class SystemSettingModel extends Model
{
    protected $table = 'system_settings';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useAutoIncrement = true;
    protected $protectFields = true;
    protected $allowedFields = [
        'setting_key',
        'setting_value',
    ];
    protected $useTimestamps = true;

    public function getMap(): array
    {
        $map = [];

        foreach ($this->findAll() as $row) {
            $map[(string) $row['setting_key']] = $row['setting_value'];
        }

        return $map;
    }

    public function setValue(string $key, ?string $value): void
    {
        $existing = $this->where('setting_key', $key)->first();

        if ($existing === null) {
            $this->insert([
                'setting_key' => $key,
                'setting_value' => $value,
            ]);

            return;
        }

        $this->update($existing['id'], [
            'setting_value' => $value,
        ]);
    }

    public function setMany(array $values): void
    {
        foreach ($values as $key => $value) {
            $this->setValue((string) $key, $value === null ? null : (string) $value);
        }
    }
}
