<?php

namespace App\Models;

class AppSettingModel extends BaseModel
{
    protected $table      = 'app_settings';
    protected $primaryKey = 'id';

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

    protected $useSoftDeletes = false;

    public function getAll(int $churchId): array
    {
        $rows = $this->where('church_id', $churchId)->findAll();
        $out  = [];
        foreach ($rows as $row) {
            $out[$row['key']] = $row['value'];
        }
        return $out;
    }

    public function setKey(int $churchId, string $key, string $value): void
    {
        $existing = $this->where('church_id', $churchId)->where('key', $key)->first();
        if ($existing) {
            $this->update($existing['id'], ['value' => $value]);
        } else {
            $this->insert([
                'uuid'      => \App\Libraries\UuidHelper::generate(),
                'church_id' => $churchId,
                'key'       => $key,
                'value'     => $value,
            ]);
        }
    }
}
