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

// Inputs
$name = trim((string)($body['room_name'] ?? ''));
$type = trim((string)($body['room_type'] ?? 'group'));
$key  = trim((string)($body['room_key'] ?? ''));

// Validation (tune limits to your needs)
if ($name === '') respond(400, ['error' => 'room_name is required']);
if (mb_strlen($name) > 120) respond(400, ['error' => 'room_name too long']);

if ($key === '') respond(400, ['error' => 'room_key is required']);
if (!preg_match('/^[a-zA-Z0-9._-]{3,64}$/', $key)) {
  respond(400, ['error' => 'room_key must be 3-64 chars: letters, numbers, dot, underscore, hyphen']);
}

$allowedTypes = ['dm', 'group', 'announcement'];
if (!in_array($type, $allowedTypes, true)) respond(400, ['error' => 'Invalid room_type']);

try {
  // Transaction is helpful if you also want to auto-add creator as a member
  $conn->begin_transaction();

  $stmt = $conn->prepare("
    INSERT INTO pth_staff_rooms (room_key, room_name, room_type, created_by, created_at)
    VALUES (?, ?, ?, ?, NOW())
  ");
  if (!$stmt) throw new Exception("Prepare failed (insert room): " . $conn->error);

  $stmt->bind_param("sssi", $key, $name, $type, $userId);

  if (!$stmt->execute()) {
    // Better duplicate detection: check SQLSTATE / errno if you can
    // MySQL duplicate key is typically errno 1062
    if (($stmt->errno ?? 0) === 1062) {
      $conn->rollback();
      respond(409, ['error' => 'Room key already exists']);
    }
    throw new Exception("Execute failed (insert room): " . $stmt->error);
  }

  $roomId = (int)$conn->insert_id;

  /**
   * Project-fit: auto-add creator as a room member (recommended).
   * Adjust role value to match your system (e.g., 'admin', 'owner', 1, etc.)
   */
  $role = ($type === 'announcement') ? 'admin' : 'admin';

  $m = $conn->prepare("
    INSERT INTO pth_staff_room_members (room_id, user_id, role, joined_at)
    VALUES (?, ?, ?, NOW())
  ");
  if (!$m) throw new Exception("Prepare failed (insert member): " . $conn->error);

  $m->bind_param("iis", $roomId, $userId, $role);

  if (!$m->execute()) {
    throw new Exception("Execute failed (insert member): " . $m->error);
  }

  $conn->commit();

  respond(200, [
    'room' => [
      'id' => $roomId,
      'room_key' => $key,
      'room_name' => $name,
      'room_type' => $type,
      'created_by' => $userId,
      'created_at' => date('Y-m-d H:i:s'),
    ]
  ]);
} catch (Throwable $e) {
  if (isset($conn) && $conn instanceof mysqli) {
    // rollback if transaction started
    try { $conn->rollback(); } catch (Throwable $ignored) {}
  }
  error_log("create room failed: " . $e->getMessage());
  respond(500, ['error' => 'Failed to create room']);
}
