<?php
declare(strict_types=1);

function audit_log(
    PDO $pdo,
    array $actor,
    string $action,
    string $targetType,
    ?int $targetId,
    array $metadata = []
): void {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO audit_logs (
                actor_id,
                actor_email,
                actor_role,
                action,
                target_type,
                target_id,
                company_id,
                company_name,
                rsp_id,
                rsp_name,
                ip_address,
                metadata
            ) VALUES (
                :actor_id,
                :actor_email,
                :actor_role,
                :action,
                :target_type,
                :target_id,
                :company_id,
                :company_name,
                :rsp_id,
                :rsp_name,
                :ip_address,
                :metadata
            )
        ");

        $stmt->execute([
            ':actor_id'     => (int)$actor['id'],
            ':actor_email'  => (string)$actor['email'],
            ':actor_role'   => (string)$actor['role_key'],
            ':action'       => $action,
            ':target_type'  => $targetType,
            ':target_id'    => $targetId,
            ':company_id'   => $actor['company_id'] ?? null,
            ':company_name' => $actor['company_name'] ?? null,
            ':rsp_id'       => $actor['rsp_id'] ?? null,
            ':rsp_name'     => $actor['rsp_name'] ?? null,
            ':ip_address'   => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            ':metadata'     => json_encode($metadata, JSON_THROW_ON_ERROR)
        ]);
    } catch (Throwable $ignored) {
        // Audit logging must never break core logic
    }
}
