<?php
/**
 * Audit logger – writes structured entries to the `osce_logs` table.
 *
 * audit_log($pdo, 'login_success', ['username' => 'admin']);
 * audit_log($pdo, 'grade_save', ['attempt_id' => 17, 'candidate_id' => 8]);
 */

function audit_log(PDO $pdo, string $event, array $context = []): void
{
    try {
        $user = isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null;
        $role = $_SESSION['role'] ?? null;
        $ip   = $_SERVER['REMOTE_ADDR'] ?? '';
        $ua   = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 250);
        $msg  = json_encode([
            'ctx' => $context,
            'ip'  => $ip,
            'ua'  => $ua,
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        // Role enum tolerated: 'candidate','examiner','admin' (legacy schema)
        // We map super_admin->admin and facility->examiner for the column.
        $colRole = match ($role) {
            'super_admin' => 'admin',
            'facility'    => 'examiner',
            default       => null,
        };

        $stmt = $pdo->prepare("
            INSERT INTO osce_logs (event_type, user_role, user_id, message)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([substr($event, 0, 50), $colRole, $user, $msg]);
    } catch (Throwable $e) {
        // Never let audit failures break the application.
        error_log('audit_log failed: ' . $e->getMessage());
    }
}
