<?php
require_once __DIR__ . '/db.php';

if (!function_exists('audit_log')) {
    /**
     * Minimal audit logger compatible with table `audit_log`:
     * (user_id, entity_type, entity_id, action, diff_json, at, ip)
     */
    function audit_log(PDO $pdo, ?int $userId, string $action, string $entityType, ?int $entityId, array $diff = []): void {
        try {
            $allowed = ['CREATE','UPDATE','DELETE','SUBMIT','APPROVE','REJECT'];
            $act = strtoupper($action);
            if (!in_array($act, $allowed, true)) $act = 'UPDATE';

            $ip = $_SERVER['REMOTE_ADDR'] ?? null;
            $st = $pdo->prepare("INSERT INTO audit_log (user_id, entity_type, entity_id, action, diff_json, ip) VALUES (?,?,?,?,?,?)");
            $st->execute([
                $userId,
                $entityType,
                (int)($entityId ?? 0),
                $act,
                json_encode($diff, JSON_UNESCAPED_UNICODE),
                $ip,
            ]);
        } catch (Throwable $e) {
            // Never break business flow because of audit.
        }
    }
}
