<?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';

if (!isset($conn) || !($conn instanceof mysqli)) {
  respond(500, ['error' => 'DB not available']);
}

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

$userId = (int)($_SESSION['user_id'] ?? 0);
if ($userId <= 0) {
  // legacy fallback (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']);
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);
$role     = trim((string)($body['role'] ?? 'member'));

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

$allowedRoles = ['admin', 'member'];
if (!in_array($role, $allowedRoles, true)) respond(400, ['error' => 'Invalid role']);

// Optional: block adding yourself as member via admin endpoint (remove if not desired)
// if ($memberId === $userId) respond(400, ['error' => 'You cannot modify your own role here']);

try {
  // Optional: verify room exists
  $roomChk = $conn->prepare("SELECT id FROM pth_staff_rooms WHERE id = ? LIMIT 1");
  if (!$roomChk) throw new Exception("Prepare failed (roomChk): " . $conn->error);

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

  $roomRes = $roomChk->get_result();
  if (!$roomRes || $roomRes->num_rows === 0) {
    respond(404, ['error' => 'Room not found']);
  }

  /**
   * Optional guard: prevent making the room have 0 admins.
   * This matters if you're *updating* an existing admin to 'member'.
   */
  $existingRole = null;
  $existing = $conn->prepare("
    SELECT role
    FROM pth_staff_room_members
    WHERE room_id = ? AND user_id = ?
    LIMIT 1
  ");
  if (!$existing) throw new Exception("Prepare failed (existing): " . $conn->error);

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

  $existingRes = $existing->get_result();
  if ($existingRes && $existingRes->num_rows > 0) {
    $row = $existingRes->fetch_assoc();
    $existingRole = (string)($row['role'] ?? '');
  }

  if ($existingRole === 'admin' && $role !== 'admin') {
    $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);

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

  // Add or update membership
  $stmt = $conn->prepare("
    INSERT INTO pth_staff_room_members (room_id, user_id, role, joined_at)
    VALUES (?, ?, ?, CURRENT_TIMESTAMP())
    ON DUPLICATE KEY UPDATE role = VALUES(role)
  ");
  if (!$stmt) throw new Exception("Prepare failed (upsert): " . $conn->error);

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

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