<?php

namespace App\Models;

use CodeIgniter\Model;

class PengaturanModel extends Model
{
    protected $table            = 'pengaturan';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['pengaturan_key', 'pengaturan_value'];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    /**
     * Get setting value by key
     */
    public function getValue(string $key, $default = null)
    {
        $setting = $this->where('pengaturan_key', $key)->first();
        return $setting ? $setting['pengaturan_value'] : $default;
    }

    /**
     * Set setting value by key
     */
    public function setValue(string $key, ?string $value)
    {
        $setting = $this->where('pengaturan_key', $key)->first();
        if ($setting) {
            $this->update($setting['id'], ['pengaturan_value' => $value]);
        } else {
            $this->insert(['pengaturan_key' => $key, 'pengaturan_value' => $value]);
        }
    }
}
