39315-vm/api/rooms.php
2026-03-25 15:17:29 +00:00

79 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/../multiplayer_data.php';
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
function roomsApiRespond(array $payload, int $status = 200): void
{
http_response_code($status);
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
try {
if ($method === 'GET') {
$roomCode = (string) ($_GET['room_code'] ?? '');
$room = multiplayerFetchRoomByCode($roomCode);
if (!$room) {
roomsApiRespond([
'success' => false,
'error' => 'Room not found or expired.',
], 404);
}
roomsApiRespond([
'success' => true,
'updated_at' => gmdate(DATE_ATOM),
'room' => $room,
]);
}
if ($method !== 'POST') {
roomsApiRespond([
'success' => false,
'error' => 'Method not allowed.',
], 405);
}
$action = strtolower(trim((string) ($_POST['action'] ?? '')));
if ($action === 'create') {
$room = multiplayerCreateRoom((string) ($_POST['player_name'] ?? ''));
roomsApiRespond([
'success' => true,
'message' => 'Room created.',
'updated_at' => gmdate(DATE_ATOM),
'room' => $room,
], 201);
}
if ($action === 'join') {
$room = multiplayerJoinRoom((string) ($_POST['room_code'] ?? ''), (string) ($_POST['player_name'] ?? ''));
roomsApiRespond([
'success' => true,
'message' => 'Joined room.',
'updated_at' => gmdate(DATE_ATOM),
'room' => $room,
]);
}
roomsApiRespond([
'success' => false,
'error' => 'Unknown room action.',
], 422);
} catch (InvalidArgumentException $e) {
roomsApiRespond([
'success' => false,
'error' => $e->getMessage(),
], 422);
} catch (Throwable $e) {
roomsApiRespond([
'success' => false,
'error' => 'Unable to process the room request right now.',
], 500);
}