<?php

namespace App\Models;

use CodeIgniter\Model;

class CompanySettingModel extends Model
{
    protected $table         = 'company_settings';
    protected $primaryKey    = 'id';
    protected $allowedFields = ['company_id', 'setting_group', 'setting_key', 'setting_value',
        'created_at', 'updated_at', 'deleted_at'];

    public function getSetting(int $companyId, string $group, string $key): ?string
    {
        $row = $this->where('company_id', $companyId)
                    ->where('setting_group', $group)
                    ->where('setting_key', $key)
                    ->first();
        return $row['setting_value'] ?? null;
    }

    public function saveSetting(int $companyId, string $group, string $key, mixed $value): void
    {
        $existing = $this->where('company_id', $companyId)
                         ->where('setting_group', $group)
                         ->where('setting_key', $key)
                         ->first();
        if ($existing) {
            $this->update($existing['id'], ['setting_value' => (string)$value]);
        } else {
            $this->insert([
                'company_id'    => $companyId,
                'setting_group' => $group,
                'setting_key'   => $key,
                'setting_value' => (string)$value,
            ]);
        }
    }

    public function getAllForCompany(int $companyId): array
    {
        $rows   = $this->where('company_id', $companyId)->findAll();
        $result = [];
        foreach ($rows as $row) {
            $result[$row['setting_group']][$row['setting_key']] = $row['setting_value'];
        }
        return $result;
    }

    public function getGroup(int $companyId, string $group): array
    {
        $rows   = $this->where('company_id', $companyId)->where('setting_group', $group)->findAll();
        $result = [];
        foreach ($rows as $row) {
            $result[$row['setting_key']] = $row['setting_value'];
        }
        return $result;
    }
}
