false, 'ERROR' => 'method_not_allowed'], 405); } $channelId = (int) ($_GET['ChannelID'] ?? 0); $agentAddress = trim($_GET['AgentAddress'] ?? ''); if ($channelId <= 0) jsonResponse(['OK' => false, 'ERROR' => 'channel_id_required']); $channel = queryOne("SELECT ID FROM Hub_Channels WHERE ID = ?", [$channelId]); if (!$channel) jsonResponse(['OK' => false, 'ERROR' => 'channel_not_found']); $memberCount = (int) (queryOne( "SELECT COUNT(*) as cnt FROM Hub_ChannelMembers WHERE ChannelID = ?", [$channelId] )['cnt'] ?? 0); $messageCount = (int) (queryOne( "SELECT COUNT(*) as cnt FROM Hub_Messages WHERE ChannelID = ? AND IsDeleted = 0", [$channelId] )['cnt'] ?? 0); $pinnedCount = (int) (queryOne( "SELECT COUNT(*) as cnt FROM Hub_PinnedPosts WHERE ChannelID = ?", [$channelId] )['cnt'] ?? 0); $unreadCount = 0; if ($agentAddress !== '') { $membership = queryOne( "SELECT LastViewedAt FROM Hub_ChannelMembers WHERE ChannelID = ? AND AgentAddress = ?", [$channelId, $agentAddress] ); if ($membership && $membership['LastViewedAt']) { $unreadCount = (int) (queryOne( "SELECT COUNT(*) as cnt FROM Hub_Messages WHERE ChannelID = ? AND IsDeleted = 0 AND CreatedAt > ?", [$channelId, $membership['LastViewedAt']] )['cnt'] ?? 0); } elseif ($membership) { // Never viewed — all messages are unread $unreadCount = $messageCount; } } jsonResponse([ 'OK' => true, 'Stats' => [ 'ChannelID' => $channelId, 'MemberCount' => $memberCount, 'MessageCount' => $messageCount, 'PinnedCount' => $pinnedCount, 'UnreadCount' => $unreadCount, ], ]);