<?php
class AuditLog
{
    public static function log(
        string $action,
        string $module,
        string $entityType,
        ?int $entityId,
        string $description,
        $oldValues = null,
        $newValues = null
    ): void {
        try {
            $db = Database::getInstance();
            $db->insert('audit_log', [
                'user_id'        => Auth::id(),
                'action_type'    => $action,
                'module'         => $module,
                'entity_type'    => $entityType,
                'entity_id'      => $entityId,
                'description'    => mb_substr($description, 0, 1000),
                'ip_address'     => $_SERVER['REMOTE_ADDR'] ?? null,
                'user_agent'     => isset($_SERVER['HTTP_USER_AGENT']) ? mb_substr($_SERVER['HTTP_USER_AGENT'], 0, 500) : null,
                'request_method' => $_SERVER['REQUEST_METHOD'] ?? null,
                'request_url'    => isset($_SERVER['REQUEST_URI']) ? mb_substr($_SERVER['REQUEST_URI'], 0, 500) : null,
                'old_values'     => $oldValues ? json_encode($oldValues, JSON_UNESCAPED_UNICODE) : null,
                'new_values'     => $newValues ? json_encode($newValues, JSON_UNESCAPED_UNICODE) : null,
                'severity'       => 'info',
            ]);
        } catch (\Exception $e) {
            Logger::error('Audit log failed: ' . $e->getMessage());
        }
    }
}