<?php
namespace App\Models;
use CodeIgniter\Model;

class CustomFieldValueModel extends Model
{
    protected $table         = 'custom_field_values';
    protected $primaryKey    = 'id';
    protected $allowedFields  = ['company_id','entity_type','entity_id','field_def_id','value','created_at','updated_at','deleted_at'];

    public function forEntity(int $companyId, string $entityType, int $entityId): array
    {
        $rows = $this->where('company_id', $companyId)->where('entity_type', $entityType)->where('entity_id', $entityId)->findAll();
        $result = [];
        foreach ($rows as $r) { $result[$r['field_def_id']] = $r['value']; }
        return $result;
    }

    public function upsert(int $companyId, string $entityType, int $entityId, int $fieldDefId, mixed $value): void
    {
        $existing = $this->where('entity_type', $entityType)->where('entity_id', $entityId)->where('field_def_id', $fieldDefId)->first();
        if ($existing) { $this->update($existing['id'], ['value' => (string)$value]); }
        else { $this->insert(['company_id' => $companyId, 'entity_type' => $entityType, 'entity_id' => $entityId, 'field_def_id' => $fieldDefId, 'value' => (string)$value]); }
    }
}
