<?php

declare(strict_types=1);

namespace App\Models;

use CodeIgniter\Model;

class BookingSmtpConfigModel extends Model
{
    protected $table            = 'booking_smtp_config';
    protected $primaryKey       = 'config_key';
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $allowedFields    = [
        'config_key',
        'config_value',
    ];
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $validationRules  = [];

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

    public function getValue(string $key, mixed $default = null): mixed
    {
        $row = $this->find($key);
        if ($row === null) {
            return $default;
        }
        return $row['config_value'];
    }

    public function setValue(string $key, mixed $value): bool
    {
        $existing = $this->find($key);
        if ($existing === null) {
            return (bool) $this->insert([
                'config_key'   => $key,
                'config_value' => $value,
            ]);
        }
        return (bool) $this->update($key, ['config_value' => $value]);
    }
}
