<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

/**
 * Records one admin/security-relevant action. Keep $action as a short,
 * stable slug (e.g. "participant.access_granted") so entries stay
 * filterable; put anything variable in $metadata.
 */
function app_audit_log(
    PDO $pdo,
    ?int $tenantId,
    ?int $actorUserId,
    string $action,
    string $subjectType,
    ?int $subjectId,
    array $metadata = []
): void {
    $stmt = $pdo->prepare(
        'INSERT INTO audit_log (tenant_id, actor_user_id, action, subject_type, subject_id, metadata_json, ip)
         VALUES (?, ?, ?, ?, ?, ?, ?)'
    );
    $stmt->execute([
        $tenantId,
        $actorUserId,
        $action,
        $subjectType,
        $subjectId,
        $metadata !== [] ? json_encode($metadata, JSON_UNESCAPED_UNICODE) : null,
        $_SERVER['REMOTE_ADDR'] ?? null,
    ]);
}

/**
 * @return list<array{id: int, actor_user_id: ?int, actor_name: ?string, action: string, subject_type: string, subject_id: ?int, metadata_json: ?string, ip: ?string, created_at: string}>
 */
function app_fetch_audit_log(PDO $pdo, int $tenantId, int $limit = 100): array
{
    $limit = max(1, min($limit, 500));
    $stmt = $pdo->prepare(
        "SELECT a.id, a.actor_user_id, u.display_name AS actor_name, a.action, a.subject_type, a.subject_id, a.metadata_json, a.ip, a.created_at
         FROM audit_log a
         LEFT JOIN users u ON u.id = a.actor_user_id
         WHERE a.tenant_id = ?
         ORDER BY a.created_at DESC, a.id DESC
         LIMIT {$limit}"
    );
    $stmt->execute([$tenantId]);

    return $stmt->fetchAll();
}
