<?php

declare(strict_types=1);

function log_admin_action(
    PDO $pdo,
    array $user,
    string $module,
    string $action,
    ?int $record_id = null,
    ?array $old_data = null,
    ?array $new_data = null
): void {

    try {

        $stmt = $pdo->prepare("
            INSERT INTO admin_audit_logs
            (
                user_id,
                role_key,
                module_key,
                action_type,
                record_id,
                old_data,
                new_data,
                endpoint,
                ip_address
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            $user['id'],
            $user['role'],
            $module,
            $action,
            $record_id,
            $old_data ? json_encode($old_data) : null,
            $new_data ? json_encode($new_data) : null,
            $_SERVER['REQUEST_URI'] ?? null,
            $_SERVER['REMOTE_ADDR'] ?? null
        ]);

    } catch (Throwable $e) {
        // Fail silently (audit must never block main action)
    }
}