<?php
// Start the session to track users
session_start();

// Database connection
$host = 'localhost'; // Your DB host
$db = 'u950110925_onlinenow'; // Your DB name
$user = 'u950110925_onlinenow'; // Your DB username
$pass = 'Socks333###'; // Your DB password

// Connect to the database
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);

// Set session ID (if no session, it starts a new one)
$session_id = session_id();

// Time limit for online users (e.g., 60 seconds)
$time_limit = 60;

// Current timestamp
$current_time = time();

// Check if the user already exists in the table
$stmt = $pdo->prepare("SELECT * FROM online_users WHERE session_id = :session_id");
$stmt->execute(['session_id' => $session_id]);
$user = $stmt->fetch();

if ($user) {
    // Update the last activity time if the user exists
    $stmt = $pdo->prepare("UPDATE online_users SET last_activity = NOW() WHERE session_id = :session_id");
    $stmt->execute(['session_id' => $session_id]);
} else {
    // Insert the user if they don't exist and increment the "all_time_today" count
    $stmt = $pdo->prepare("INSERT INTO online_users (session_id, last_activity, all_time_today) VALUES (:session_id, NOW(), 1)");
    $stmt->execute(['session_id' => $session_id]);

    // Increment the all-time online count for today
    $stmt = $pdo->prepare("UPDATE online_users SET all_time_today = all_time_today + 1 WHERE DATE(last_activity) = CURDATE()");
    $stmt->execute();
}

// Remove users who have been inactive for longer than the time limit
$stmt = $pdo->prepare("DELETE FROM online_users WHERE last_activity < (NOW() - INTERVAL :time_limit SECOND)");
$stmt->execute(['time_limit' => $time_limit]);

// Get the current number of online users
$stmt = $pdo->query("SELECT COUNT(*) AS online_count FROM online_users");
$result = $stmt->fetch(PDO::FETCH_ASSOC);

// Get the total number of users online today
$stmt_all_time = $pdo->query("
    SELECT MAX(all_time_today) AS total_today
    FROM online_users
    WHERE DATE(last_activity) = CURDATE()
");
$result_all_time = $stmt_all_time->fetch(PDO::FETCH_ASSOC);

// Output the current online count and total users for today as JSON
echo json_encode([
    'online_count' => $result['online_count'],
    'total_today' => $result_all_time['total_today']
]);
