<?php
function audit_log(string $action, string $entity_type, $entity_id = null, $old_data = null, $new_data = null): void {
  try {
    $uid = intval($_SESSION['uid'] ?? 0) ?: null;
    $ip = $_SERVER['REMOTE_ADDR'] ?? null;
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? null;

    $oldJson = $old_data === null ? null : json_encode($old_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $newJson = $new_data === null ? null : json_encode($new_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    db_exec("INSERT INTO audit_logs (user_id,action,entity_type,entity_id,old_data,new_data,ip,user_agent,created_at)
             VALUES (?,?,?,?,?,?,?,?,?)",
      [$uid, $action, $entity_type, $entity_id, $oldJson, $newJson, $ip, $ua, now_dt()]
    );
  } catch (Throwable $e) {
    // fail-safe: do not break app on audit failures
  }
}
