<?php

namespace App\Models;

use CodeIgniter\Model;

class SettingModel extends Model
{
    protected $table = "settings";
    protected $primaryKey = "id";
    protected $returnType = "array";
    protected $allowedFields = ["setting_key", "setting_value", "is_secret"];
    protected $useTimestamps = true;

    public function value(string $key, $default = null)
    {
        $row = $this->where("setting_key", $key)->first();
        return $row ? $row["setting_value"] : $default;
    }

    public function values(array $defaults = []): array
    {
        $values = $defaults;
        foreach ($this->findAll() as $row) {
            $values[$row["setting_key"]] = $row["setting_value"];
        }
        return $values;
    }

    public function setValue(
        string $key,
        ?string $value,
        bool $secret = false
    ): void {
        $row = $this->where("setting_key", $key)->first();
        $data = [
            "setting_key" => $key,
            "setting_value" => $value,
            "is_secret" => $secret ? 1 : 0,
        ];

        if ($row) {
            $this->update($row["id"], $data);
            return;
        }

        $this->insert($data);
    }
}
