<?php
require_once __DIR__ . '/config.php';
$me = must_auth();
ensure_app_schema();

// Heartbeat: refresh the caller's own last_seen each time they fetch the online
// list (the client does this every few seconds). Previously last_seen was only
// updated on login/typing/logout, so a user who was only reading would appear
// offline to everyone after 30s even though the app was open and active.
// This does not touch typing flags.
try {
    db()->prepare("INSERT INTO presence (username, last_seen, is_typing, typing_to)
                   VALUES (?, UTC_TIMESTAMP(), 0, '')
                   ON DUPLICATE KEY UPDATE last_seen=UTC_TIMESTAMP()")
       ->execute(array($me));
} catch (Exception $e) {}

$st = db()->prepare("SELECT p.username,
                            IF(u.display_name='',u.username,u.display_name) AS display_name,
                            DATE_FORMAT(p.last_seen,'%Y-%m-%dT%H:%i:%sZ') AS last_seen,
                            COALESCE(NULLIF(p.timezone,''),u.timezone) AS timezone,
                            COALESCE(NULLIF(p.country,''),u.country) AS country,
                            u.avatar, u.about,
                            IF(p.last_seen>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL 30 SECOND),1,0) AS online
                     FROM presence p
                     JOIN users u ON u.username=p.username
                     WHERE p.username!=?
                     ORDER BY p.last_seen DESC");
$st->execute(array($me));
ok(array('users' => $st->fetchAll()));
