<?php
/**
 * TOPBD API — Heartbeat Visitor Tracker Endpoint
 */

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

$sessionId = session_id();
if (empty($sessionId)) {
    session_start();
    $sessionId = session_id();
}

$db = get_db();
$ip = get_client_ip();
$ua = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 250);

// Upsert active session
$stmt = $db->prepare("INSERT INTO visitors (session_id, ip_address, user_agent, last_seen) 
                      VALUES (?, ?, ?, NOW()) 
                      ON DUPLICATE KEY UPDATE last_seen = NOW(), ip_address = VALUES(ip_address)");
$stmt->execute([$sessionId, $ip, $ua]);

$visitors = RankingEngine::getLiveVisitors((int)get_setting('visitor_timeout_seconds', '180'));

json_response([
    'success' => true,
    'visitors' => $visitors
]);
