$max) { return null; } return $v; } $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; if ($method === 'GET') { $key = trim((string)($_GET['playerKey'] ?? '')); if (!valid_player_key($key)) { json_response(['ok' => false, 'error' => 'playerKey ต้องยาว 8–128 (a-z 0-9 _ -)'], 400); } $store = read_store(); foreach ($store['accounts'] ?? [] as $a) { if (($a['loginType'] ?? '') !== 'guest') { continue; } if (($a['providerUserId'] ?? '') !== $key) { continue; } json_response([ 'ok' => true, 'colorThemeIndex' => clamp_index_or_null($a['lobbyColorThemeIndex'] ?? null, LOBBY_THEME_MIN, LOBBY_THEME_MAX), 'skinToneIndex' => clamp_index_or_null($a['lobbySkinToneIndex'] ?? null, LOBBY_SKIN_MIN, LOBBY_SKIN_MAX), ]); } // ยังไม่มีบัญชี/ยังไม่เคยเลือกสี — ไม่ต้องสร้างบัญชีตอน GET json_response([ 'ok' => true, 'colorThemeIndex' => null, 'skinToneIndex' => null, ]); } if ($method === 'POST') { $body = require_json_body(); $key = trim((string)($body['playerKey'] ?? '')); if (!valid_player_key($key)) { json_response(['ok' => false, 'error' => 'playerKey ต้องยาว 8–128 (a-z 0-9 _ -)'], 400); } $colorThemeIndex = clamp_index_or_null($body['colorThemeIndex'] ?? null, LOBBY_THEME_MIN, LOBBY_THEME_MAX); $skinToneIndex = clamp_index_or_null($body['skinToneIndex'] ?? null, LOBBY_SKIN_MIN, LOBBY_SKIN_MAX); if ($colorThemeIndex === null && $skinToneIndex === null) { json_response(['ok' => false, 'error' => 'ต้องส่ง colorThemeIndex (1–8) หรือ skinToneIndex (1–3) อย่างน้อย 1 ค่า'], 400); } $store = read_store(); $now = gmdate('c'); $found = false; foreach ($store['accounts'] as $i => $a) { if (($a['loginType'] ?? '') !== 'guest') { continue; } if (($a['providerUserId'] ?? '') !== $key) { continue; } if ($colorThemeIndex !== null) { $store['accounts'][$i]['lobbyColorThemeIndex'] = $colorThemeIndex; } if ($skinToneIndex !== null) { $store['accounts'][$i]['lobbySkinToneIndex'] = $skinToneIndex; } $store['accounts'][$i]['updatedAt'] = $now; $found = true; break; } if (!$found) { $store['accounts'][] = [ 'id' => new_id(), 'email' => '', 'displayName' => 'Guest', 'loginType' => 'guest', 'providerUserId' => $key, 'notes' => 'auto: player-lobby-style', 'blocked' => false, 'coins' => 0, 'lobbyColorThemeIndex' => $colorThemeIndex, 'lobbySkinToneIndex' => $skinToneIndex, 'createdAt' => $now, 'updatedAt' => $now, ]; } if (!write_store($store)) { json_response(['ok' => false, 'error' => 'บันทึกสีไม่สำเร็จ'], 500); } json_response([ 'ok' => true, 'colorThemeIndex' => $colorThemeIndex, 'skinToneIndex' => $skinToneIndex, ]); } json_response(['ok' => false, 'error' => 'Use GET or POST'], 405);