<?php

namespace App\Models;

use CodeIgniter\Model;

class AuditLogModel extends Model
{
    protected $table = 'audit_log';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useAutoIncrement = true;
    protected $protectFields = true;
    protected $allowedFields = ['entity', 'entity_id', 'action', 'user_id', 'payload_json', 'ip'];
    protected $useTimestamps = true;
    protected $updatedField = '';

    public function record(string $entity, ?int $entityId, string $action, array $payload = []): void
    {
        $this->insert([
            'entity' => $entity,
            'entity_id' => $entityId,
            'action' => $action,
            'user_id' => session('auth_user')['id'] ?? null,
            'payload_json' => $payload === [] ? null : json_encode($payload, JSON_UNESCAPED_UNICODE),
            'ip' => service('request')->getIPAddress(),
        ]);
    }
}
