<?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;
}
function pickSessionName(): ?string {
  if (!empty($_COOKIE['PHPSESSADM'])) return 'PHPSESSADM';
  if (!empty($_COOKIE['PHPSESSCLI'])) return 'PHPSESSCLI';
  if (!empty($_COOKIE['PHPSESSAFF'])) return 'PHPSESSAFF';
  return null;
}

require_once __DIR__ . '/conn.php'; // expects $db (PDO)

/** Session */
$sessionName = pickSessionName();
if (!$sessionName) respond(401, ['error' => 'Not authenticated']);
session_name($sessionName);
session_start();

$userId = (int)($_SESSION['user_id'] ?? 0);
if ($userId <= 0) $userId = (int)($_SESSION['SESS_MEMBER_ID'] ?? 0);
$isAdmin = (int)($_SESSION['is_admin'] ?? 0);

if ($userId <= 0) respond(401, ['error' => 'Not authenticated']);
if ($sessionName !== 'PHPSESSADM' && $isAdmin !== 1) {
  respond(403, ['error' => 'Admin access required']);
}

/** Input */
$body = json_decode(file_get_contents('php://input') ?: '', 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']);
}
if (!in_array($role, ['admin','member'], true)) {
  respond(400, ['error' => 'Invalid role']);
}

try {

  /** Ensure room exists */
  $r = $db->prepare("
    SELECT id, room_type, scope_level
    FROM pth_party_room
    WHERE id = :rid
    LIMIT 1
  ");
  $r->execute([':rid' => $roomId]);
  $room = $r->fetch(PDO::FETCH_ASSOC);

  if (!$room) respond(404, ['error' => 'Room not found']);

  /**
   * Only allow role updates for membership-based rooms
   * (DM or custom rooms).
   * Hierarchy rooms should not rely on room_members roles.
   */
  if ($room['room_type'] !== 'dm' && $room['scope_level'] !== 'custom') {
    respond(403, ['error' => 'Role changes not allowed for hierarchy rooms']);
  }

  /** Ensure member exists */
  $check = $db->prepare("
    SELECT role
    FROM pth_party_room_members
    WHERE room_id = :rid AND user_id = :uid
    LIMIT 1
  ");
  $check->execute([
    ':rid' => $roomId,
    ':uid' => $memberId
  ]);
  $existing = $check->fetch(PDO::FETCH_ASSOC);

  if (!$existing) respond(404, ['error' => 'Member not found in room']);

  /**
   * Prevent removing last admin
   */
  if ($existing['role'] === 'admin' && $role !== 'admin') {
    $countAdmins = $db->prepare("
      SELECT COUNT(*)
      FROM pth_party_room_members
      WHERE room_id = :rid AND role = 'admin'
    ");
    $countAdmins->execute([':rid' => $roomId]);
    $adminCount = (int)$countAdmins->fetchColumn();

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

  /** Update role */
  $update = $db->prepare("
    UPDATE pth_party_room_members
    SET role = :role
    WHERE room_id = :rid AND user_id = :uid
  ");
  $update->execute([
    ':role' => $role,
    ':rid'  => $roomId,
    ':uid'  => $memberId,
  ]);

  respond(200, ['ok' => true]);

} catch (Throwable $e) {
  respond(500, [
    'error' => 'Failed to update role',
    'details' => $e->getMessage(), // remove in production
  ]);
}
