<?php
declare(strict_types=1);

/** Writes audit_log. Never throws - a logging failure must not break a request. */
final class Audit
{
    public static function log(string $action, ?string $entityType = null,
                               ?int $entityId = null, ?array $changes = null): void
    {
        try {
            Database::run(
                'INSERT INTO audit_log (user_id, action, entity_type, entity_id, changes, ip)
                 VALUES (:uid, :a, :et, :eid, :c, :ip)',
                [
                    'uid' => $_SESSION['user_id'] ?? null,
                    'a'   => $action,
                    'et'  => $entityType,
                    'eid' => $entityId,
                    'c'   => $changes === null ? null : json_encode($changes, JSON_UNESCAPED_UNICODE),
                    'ip'  => client_ip_binary(),
                ]
            );
        } catch (Throwable $e) {
            error_log('[audit] ' . $e->getMessage());
        }
    }

    /** Field-level diff, keeping only what changed. */
    public static function diff(array $before, array $after): array
    {
        $changes = [];
        foreach ($after as $k => $new) {
            $old = $before[$k] ?? null;
            if ((string) $old !== (string) $new) {
                $changes[$k] = ['from' => $old, 'to' => $new];
            }
        }
        return $changes;
    }
}
