<?php
session_start();
require '../db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$roomId = intval($_GET['room_id'] ?? 0);

if (!$roomId) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid room ID']);
    exit;
}

try {
    // Получить всех пользователей, которые отправляли сообщения в этой комнате
    $stmt = $pdo->prepare("
        SELECT DISTINCT 
            u.id,
            u.username,
            u.avatar,
            u.role,
            u.email,
            u.last_seen,
            CASE 
                WHEN u.last_seen >= DATE_SUB(NOW(), INTERVAL 5 MINUTE) THEN 1
                ELSE 0
            END as is_online
        FROM users u
        INNER JOIN messages m ON u.id = m.user_id
        WHERE m.room_id = ? AND m.is_deleted = 0
        ORDER BY is_online DESC, u.username ASC
    ");
    $stmt->execute([$roomId]);
    $members = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'status' => 'success',
        'members' => $members,
        'count' => count($members)
    ]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
