<?php

class AuditLogger
{
    public static function log(?int $userId, string $action, ?string $moduleKey = null, ?string $description = null): void
    {
        try {
            $db = Database::getConnection();
            $stmt = $db->prepare(
                "INSERT INTO audit_log (user_id, action, module_key, description, ip_address)
                 VALUES (:user_id, :action, :module_key, :description, :ip)"
            );
            $stmt->execute([
                'user_id'     => $userId,
                'action'      => $action,
                'module_key'  => $moduleKey,
                'description' => $description,
                'ip'          => $_SERVER['REMOTE_ADDR'] ?? null,
            ]);
        } catch (\Throwable $e) {
            // Never let audit logging break the main request
            error_log('AuditLogger failed: ' . $e->getMessage());
        }
    }
}
