<?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.
 * 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 (remove if not needed)
  $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']);

$raw = file_get_contents('php://input');
$body = json_decode($raw ?: '', true);
if (!is_array($body)) respond(400, ['error' => 'Invalid JSON body']);

$roomId   = (int)($body['roomId'] ?? 0);
$memberId = (int)($body['userId'] ?? 0);

if ($roomId <= 0 || $memberId <= 0) respond(400, ['error' => 'roomId and userId required']);

// Optional: prevent admin removing themselves accidentally (common UX issue)
if ($memberId === $userId) respond(400, ['error' => 'You cannot remove yourself']);

try {
  // Optional guard: ensure the user is currently a member of the room (or exists)
  $chk = $conn->prepare("SELECT 1 FROM pth_staff_room_members WHERE room_id = ? AND user_id = ? LIMIT 1");
  if (!$chk) throw new Exception("Prepare failed (chk): " . $conn->error);

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

  $chkRes = $chk->get_result();
  if (!$chkRes || $chkRes->num_rows === 0) {
    respond(404, ['error' => 'Member not found in room']);
  }

  // Optional guard: block removing the last admin in the room
  // If your "role" column uses something else, adjust 'admin' accordingly.
  $adminCountStmt = $conn->prepare("
    SELECT COUNT(*) AS admins
    FROM pth_staff_room_members
    WHERE room_id = ? AND role = 'admin'
  ");
  if (!$adminCountStmt) throw new Exception("Prepare failed (adminCount): " . $conn->error);

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

  $adminCountRes = $adminCountStmt->get_result();
  $adminsRow = $adminCountRes ? $adminCountRes->fetch_assoc() : null;
  $adminCount = (int)($adminsRow['admins'] ?? 0);

  $memberRoleStmt = $conn->prepare("
    SELECT role
    FROM pth_staff_room_members
    WHERE room_id = ? AND user_id = ?
    LIMIT 1
  ");
  if (!$memberRoleStmt) throw new Exception("Prepare failed (memberRole): " . $conn->error);

  $memberRoleStmt->bind_param("ii", $roomId, $memberId);
  if (!$memberRoleStmt->execute()) throw new Exception("Execute failed (memberRole): " . $memberRoleStmt->error);

  $memberRoleRes = $memberRoleStmt->get_result();
  $memberRoleRow = $memberRoleRes ? $memberRoleRes->fetch_assoc() : null;
  $memberRole = (string)($memberRoleRow['role'] ?? '');

  if ($memberRole === 'admin' && $adminCount <= 1) {
    respond(400, ['error' => 'Cannot remove the last admin from the room']);
  }

  $stmt = $conn->prepare("DELETE FROM pth_staff_room_members WHERE room_id = ? AND user_id = ?");
  if (!$stmt) throw new Exception("Prepare failed (delete): " . $conn->error);

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

  respond(200, ['ok' => true]);
} catch (Throwable $e) {
  error_log("remove member failed: " . $e->getMessage());
  respond(500, ['error' => 'Failed to remove member']);
}
