<?php

namespace App\Models\Control;

use CodeIgniter\Model;

/**
 * Control DB. Raw key/value access to `platform_settings` — see
 * CreatePlatformSettingsTable. Application code should use
 * App\Libraries\PlatformSettings instead of this model directly, the same
 * relationship App\Models\TenantSettingModel has with App\Libraries\Settings.
 */
class PlatformSettingModel extends Model
{
    protected $table         = 'platform_settings';
    protected $primaryKey    = 'id';
    protected $returnType    = 'object';
    protected $useTimestamps = true;

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

    public function getValue(string $key): ?string
    {
        $row = $this->where('key', $key)->first();

        return $row->value ?? null;
    }

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

        if ($existing === null) {
            $this->insert(['key' => $key, 'value' => $value]);
        } else {
            $this->update($existing->id, ['value' => $value]);
        }
    }
}
