<?php
// lib/audit.php

function ip_to_binary(?string $ip): ?string {
    if (!$ip) return null;
    $bin = @inet_pton($ip);
    return $bin === false ? null : $bin;
}

/**
 * Log a request-scoped event.
 *
 * @param PDO   $pdo
 * @param array $user  Current user session array (may be null for public events)
 * @param array $req   Request row (must contain id, organisation_id, company_id)
 * @param string $action
 * @param array $meta  Extra data; JSON encoded
 */
function log_request_event(PDO $pdo, ?array $user, array $req, string $action, array $meta = []): void {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO request_audit_log
              (organisation_id, company_id, request_id, user_id, action, meta_json, ip, created_at)
            VALUES (?,?,?,?,?,?,?,NOW())
        ");
        $stmt->execute([
            (int)$req['organisation_id'],
            (int)$req['company_id'],
            (int)$req['id'],
            isset($user['id']) ? (int)$user['id'] : null,
            $action,
            $meta ? json_encode($meta, JSON_UNESCAPED_SLASHES) : null,
            ip_to_binary($_SERVER['REMOTE_ADDR'] ?? null),
        ]);
    } catch (Throwable $e) {
        // Intentionally swallow: logging must never break main flow
    }
}
