<?php
/**
 * TOPBD API — Live Ranking Leaderboard Endpoint
 */

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/ranking.php';

$timeFilter = $_GET['time'] ?? 'all_time';
$category = $_GET['cat'] ?? 'all';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = (int)get_setting('pagination_size', '50');

$rankings = RankingEngine::getRankings($timeFilter, $category, $page, $perPage);
$top = RankingEngine::getTopListing();
$totalGen = RankingEngine::getTotalGenerated();
$visitors = RankingEngine::getLiveVisitors((int)get_setting('visitor_timeout_seconds', '180'));

json_response([
    'success' => true,
    'timeFilter' => $timeFilter,
    'category' => $category,
    'rankings' => $rankings['listings'],
    'total' => $rankings['total'],
    'totalPages' => $rankings['totalPages'],
    'currentPage' => $rankings['currentPage'],
    'topListing' => $top,
    'totalGenerated' => $totalGen,
    'activeVisitors' => $visitors,
]);
