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

function audit_log_list(): void {
    require_admin();
    $action = str_param('action');
    $date   = str_param('date');
    $limit  = int_param('limit', 50, 1, 200);

    $where  = [];
    $params = [];

    if ($action) {
        $where[]          = 'action = :action';
        $params[':action'] = $action;
    }
    if ($date) {
        $where[]        = 'DATE(created_at) = :date';
        $params[':date'] = $date;
    }

    $sql = "SELECT * FROM hv_audit_log";
    if ($where) $sql .= ' WHERE ' . implode(' AND ', $where);
    $sql .= " ORDER BY created_at DESC LIMIT :limit";

    $stmt = db()->prepare($sql);
    foreach ($params as $k => $v) $stmt->bindValue($k, $v);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();

    json_ok(['items' => $stmt->fetchAll()]);
}
