<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/rbac.php";

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

if (!hasPermission("view_admin")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "forbidden"]);
    exit;
}

$limit = (int)($_GET["limit"] ?? 200);
if ($limit <= 0 || $limit > 1000) {
    $limit = 200;
}

$stmt = $pdo->prepare("
    SELECT a.id, a.user_id, a.action, u.email
    FROM audit_log a
    LEFT JOIN users u ON u.id = a.user_id
    ORDER BY a.id DESC
    LIMIT ?
");
$stmt->bindValue(1, $limit, PDO::PARAM_INT);
$stmt->execute();

echo json_encode([
    "success" => true,
    "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)
]);
