<?php
require_once 'controllers/AuditController.php';
require_once 'helpers/audit_trail.php';

$auditController = new AuditController();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $uri === '/log-audit') {
    $input = json_decode(file_get_contents("php://input"), true);

    if (!$input) {
        header('Content-Type: application/json');
        echo json_encode(["message" => "Invalid JSON payload"]);
        exit;
    }

    $response = $auditController->logApiRequest($input);
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && $uri === '/get-audit-trail') {
    $filters = [
        'user_id' => $_GET['user_id'] ?? null,
        'user_type' => $_GET['user_type'] ?? null,
        'endpoint' => $_GET['endpoint'] ?? null,
        'method' => $_GET['method'] ?? null,
        'status_code' => $_GET['status_code'] ?? null,
        'start_date' => $_GET['start_date'] ?? null,
        'end_date' => $_GET['end_date'] ?? null,
    ];

    $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 20;

    $response = $auditController->getAuditLogs(array_filter($filters), $page, $limit);

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}