<?php
/**
 * 在线状态：记录已登录用户最近活动，用于平台用户与个人主页在线灯。
 * 使用 storage/cache/online.json，避免为在线状态修改用户表结构。
 */

function online_presence_file()
{
    $dir = APP_ROOT . '/storage/cache';
    if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
        return '';
    }
    return $dir . '/online.json';
}

function online_threshold()
{
    return 180; // 3 分钟内有请求即视为在线
}

function online_read_map()
{
    $file = online_presence_file();
    if ($file === '' || !is_file($file)) {
        return [];
    }
    $fp = @fopen($file, 'rb');
    if (!$fp) {
        return [];
    }
    @flock($fp, LOCK_SH);
    $raw = '';
    while (!feof($fp)) {
        $raw .= fread($fp, 8192);
    }
    @flock($fp, LOCK_UN);
    fclose($fp);
    $map = json_decode($raw, true);
    return is_array($map) ? $map : [];
}

function online_write_map(array $map)
{
    $file = online_presence_file();
    if ($file === '') {
        return;
    }
    $json = json_encode($map, JSON_UNESCAPED_UNICODE);
    $tmp = $file . '.tmp-' . bin2hex(random_bytes(4));
    if (@file_put_contents($tmp, $json, LOCK_EX) !== false) {
        @rename($tmp, $file);
    } else {
        @unlink($tmp);
    }
}

function online_apply_change($uid, $remove = false)
{
    $file = online_presence_file();
    if ($file === '') {
        return;
    }
    $fp = @fopen($file, 'c+');
    if (!$fp) {
        return;
    }
    @flock($fp, LOCK_EX);
    $raw = '';
    while (!feof($fp)) {
        $raw .= fread($fp, 8192);
    }
    $map = json_decode($raw, true);
    if (!is_array($map)) {
        $map = [];
    }
    $now = time();
    $keep = $now - 900;
    foreach ($map as $id => $at) {
        if ((int) $at < $keep) {
            unset($map[$id]);
        }
    }
    if ($remove) {
        unset($map[(string) $uid]);
    } else {
        $map[(string) $uid] = $now;
    }
    rewind($fp);
    ftruncate($fp, 0);
    fwrite($fp, json_encode($map, JSON_UNESCAPED_UNICODE));
    fflush($fp);
    @flock($fp, LOCK_UN);
    fclose($fp);
}

function online_touch($uid)
{
    $uid = (int) $uid;
    if ($uid <= 0) {
        return;
    }
    $now = time();
    if (!empty($_SESSION['_km_online_at']) && $now - (int) $_SESSION['_km_online_at'] < 35) {
        return;
    }
    $_SESSION['_km_online_at'] = $now;
    online_apply_change($uid, false);
}

function online_forget($uid)
{
    $uid = (int) $uid;
    if ($uid > 0) {
        online_apply_change($uid, true);
    }
    unset($_SESSION['_km_online_at']);
}

function online_user_ids($seconds = null)
{
    $seconds = $seconds === null ? online_threshold() : (int) $seconds;
    $now = time();
    $ids = [];
    foreach (online_read_map() as $id => $at) {
        if ((int) $at >= $now - $seconds) {
            $ids[] = (int) $id;
        }
    }
    sort($ids, SORT_NUMERIC);
    return $ids;
}

function online_is_online($uid, $seconds = null)
{
    $uid = (int) $uid;
    if ($uid <= 0) {
        return false;
    }
    $seconds = $seconds === null ? online_threshold() : (int) $seconds;
    $map = online_read_map();
    return !empty($map[(string) $uid]) && (int) $map[(string) $uid] >= time() - $seconds;
}

function online_count()
{
    return count(online_user_ids());
}
