false, 'error' => 'Use POST'], 405); } $body = require_json_body(); $key = trim((string)($body['playerKey'] ?? '')); if (!preg_match('/^[a-zA-Z0-9_-]{8,128}$/', $key)) { json_response(['ok' => false, 'error' => 'playerKey ต้องยาว 8–128 (a-z 0-9 _ -)'], 400); } $amount = (int)($body['amount'] ?? 0); // กันยิงมั่ว: ครั้งละ 1–100 เหรียญ if ($amount < 1 || $amount > 100) { json_response(['ok' => false, 'error' => 'amount ต้องอยู่ระหว่าง 1–100'], 400); } $store = read_store(); $accounts = $store['accounts'] ?? []; foreach ($accounts as $i => $a) { if (($a['loginType'] ?? '') !== 'guest') { continue; } if (($a['providerUserId'] ?? '') !== $key) { continue; } if (!empty($a['blocked'])) { json_response(['ok' => false, 'error' => 'บัญชีถูกระงับ'], 403); } $coins = max(0, (int)($a['coins'] ?? 0)) + $amount; $store['accounts'][$i]['coins'] = $coins; $store['accounts'][$i]['updatedAt'] = gmdate('c'); if (!write_store($store)) { json_response(['ok' => false, 'error' => 'บันทึกไม่สำเร็จ'], 500); } json_response(['ok' => true, 'coins' => $coins, 'added' => $amount, 'accountId' => $a['id'] ?? null]); } // ยังไม่มีบัญชี → สร้างใหม่พร้อมเหรียญ $new = [ 'id' => new_id(), 'email' => '', 'displayName' => 'Guest', 'loginType' => 'guest', 'providerUserId' => $key, 'notes' => 'auto: player-coins-add', 'blocked' => false, 'coins' => $amount, 'createdAt' => gmdate('c'), 'updatedAt' => gmdate('c'), ]; $store['accounts'][] = $new; if (!write_store($store)) { json_response(['ok' => false, 'error' => 'สร้างบัญชีไม่สำเร็จ'], 500); } json_response(['ok' => true, 'coins' => $amount, 'added' => $amount, 'accountId' => $new['id']]);