<?php
declare(strict_types=1);

require_once __DIR__ . '/_cors.php';
header('Content-Type: application/json; charset=utf-8');

function respond(int $status, array $payload): void {
  http_response_code($status);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

/**
 * Require exactly ONE of the known session cookies.
 * This prevents session-namespace confusion when multiple cookies are present.
 */
function requireSingleSessionName(): string {
  $cookies = ['PHPSESSADM', 'PHPSESSCLI', 'PHPSESSAFF'];
  $present = [];

  foreach ($cookies as $c) {
    if (!empty($_COOKIE[$c])) $present[] = $c;
  }

  if (count($present) !== 1) {
    respond(401, ['error' => 'Not authenticated']);
  }

  return $present[0];
}

require_once __DIR__ . '/conn.php';

$sessionName = requireSingleSessionName();
session_name($sessionName);
session_start();

// Normalize user id + admin flag
$userId = (int)($_SESSION['user_id'] ?? 0);
if ($userId <= 0) {
  // fallback for legacy sessions (if you truly need it)
  $userId = (int)($_SESSION['SESS_MEMBER_ID'] ?? 0);
}

$isAdmin = (int)($_SESSION['is_admin'] ?? 0);

if ($userId <= 0) respond(401, ['error' => 'Not authenticated']);

// IMPORTANT: do NOT let session name bypass admin checks
if ($isAdmin !== 1) respond(403, ['error' => 'Admin access required']);

$roomId = isset($_GET['roomId']) ? (int)$_GET['roomId'] : 0;
if ($roomId <= 0) respond(400, ['error' => 'roomId is required']);

try {
  $stmt = $conn->prepare("
    SELECT
      rm.user_id   AS userId,
      u.name       AS name,
      u.email      AS email,
      rm.role      AS role,
      rm.joined_at AS addedAt
    FROM pth_staff_room_members rm
    JOIN `user` u ON u.id = rm.user_id
    WHERE rm.room_id = ?
    ORDER BY rm.joined_at DESC, rm.id DESC
  ");
  if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);

  $stmt->bind_param("i", $roomId);
  if (!$stmt->execute()) throw new Exception("Execute failed: " . $stmt->error);

  $res = $stmt->get_result();
  if (!$res) throw new Exception("get_result failed");

  respond(200, ['members' => $res->fetch_all(MYSQLI_ASSOC)]);
} catch (Throwable $e) {
  // Avoid leaking internal details to clients; log instead
  error_log("get room members failed: " . $e->getMessage());
  respond(500, ['error' => 'Failed to fetch room members']);
}
