<?php
// helpers/audit.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/auth.php';

function audit_log(
    string $action,
    string $entity,
    ?string $entityId = null,
    ?string $details = null
): void {
    try {
        $pdo = db();
        $user = current_user();

        $stmt = $pdo->prepare("
            INSERT INTO audit_logs
              (user_id, action, entity, entity_id, details, ip_address)
            VALUES
              (:user_id, :action, :entity, :entity_id, :details, :ip)
        ");

        $stmt->execute([
            ':user_id'   => $user['id'] ?? null,
            ':action'    => $action,
            ':entity'    => $entity,
            ':entity_id' => $entityId,
            ':details'   => $details,
            ':ip'        => $_SERVER['REMOTE_ADDR'] ?? null,
        ]);
    } catch (Throwable $e) {
        // Never break the app because of audit logging
    }
}
