<?php

namespace App\Libraries;

use App\Models\AuditLogModel;

class AuditLogger
{
    public static function log(
        string $action,
        string $tableName,
        string $recordUuid,
        ?array $oldValues = null,
        ?array $newValues = null,
        ?int   $churchId  = null,
        ?int   $userId    = null
    ): void {
        $ctx = ChurchContext::getInstance();

        $resolvedChurchId = $churchId ?? $ctx->getChurchId();
        $resolvedUserId   = $userId   ?? ($ctx->getUser()['id'] ?? null);

        $request = service('request');

        try {
            $model = new AuditLogModel();
            $model->insert([
                'church_id'   => $resolvedChurchId,
                'user_id'     => $resolvedUserId,
                'action'      => $action,
                'table_name'  => $tableName,
                'record_uuid' => $recordUuid,
                'old_values'  => $oldValues  ? json_encode($oldValues)  : null,
                'new_values'  => $newValues  ? json_encode($newValues)  : null,
                'ip_address'  => $request->getIPAddress(),
                'user_agent'  => $request->getUserAgent()->getAgentString(),
                'created_at'  => date('Y-m-d H:i:s'),
            ]);
        } catch (\Throwable $e) {
            log_message('error', 'AuditLogger failed: ' . $e->getMessage());
        }
    }
}
