<?php
// Private mailbox only: no player IDs, balances, shell commands or SQL from HTTP.
ini_set('display_errors', '0');
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');
function reply($status, $data) { http_response_code($status); echo json_encode($data); exit; }
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') reply(405, ['error'=>'POST required']);
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] !== 'https://trade.santasrv.com') reply(403, ['error'=>'origin']);
if (strtolower(trim(explode(';', $_SERVER['CONTENT_TYPE'] ?? '')[0])) !== 'application/json') reply(415, ['error'=>'JSON required']);
$input = file_get_contents('php://input', false, null, 0, 513);
if (strlen($input) > 512) reply(413, ['error'=>'too large']);
$body = json_decode($input, true);
if (!is_array($body) || !is_string($body['token'] ?? null) || !preg_match('/\A[0-9a-f]{32}\z/D', $body['token'])) reply(400, ['error'=>'invalid request']);
$action = $body['action'] ?? null;
if (!in_array($action, ['state','command','preview'], true)) reply(400, ['error'=>'invalid action']);
$allowed = $action === 'state' ? ['token','action'] : ($action === 'preview' ? ['token','action','webgl','status'] : ['token','action','revision','key']);
if (array_diff(array_keys($body), $allowed)) reply(400, ['error'=>'unexpected fields']);
$base = dirname(__DIR__, 3).'/tf/addons/sourcemod/data/rpg_full_web/'.$body['token'];
function state($base) {
    $raw = @file_get_contents($base.'.state', false, null, 0, 262144);
    $data = $raw === false ? null : json_decode($raw, true);
    if (!is_array($data) || ($data['expires'] ?? 0) <= time()) reply(410, ['error'=>'session expired; reopen !rpgweb']);
    return $data;
}
$current = state($base);
if ($action === 'state') {
    $raw = @file_get_contents($base.'.appearance', false, null, 0, 32768);
    $current['appearance'] = $raw === false ? null : json_decode($raw, true);
    reply(200, $current);
}
if ($action === 'preview') {
    if (!is_int($body['webgl'] ?? null) || !in_array($body['webgl'], [0,1,2], true) || !in_array($body['status'] ?? null, ['ready','unsupported','loading','partial','error'], true)) reply(400, ['error'=>'invalid preview report']);
    // Diagnostics only, never commands or player state. Fixed bounded payload, no user agent/token logging.
    if (@file_put_contents($base.'.preview', json_encode(['time'=>time(),'webgl'=>$body['webgl'],'status'=>$body['status']]), LOCK_EX) === false) reply(503, ['error'=>'diagnostics unavailable']);
    reply(200, ['ok'=>true]);
}
if (!is_int($body['revision'] ?? null) || $body['revision'] < 1 || $body['revision'] > 100000) reply(400, ['error'=>'invalid revision']);
if (!is_string($body['key'] ?? null) || !preg_match('/\A(?:class:[1-9]|stat:[a-z][a-z0-9_]{0,62}|(?:learn|skill|buyarmor|buyconsumable|buypet|armor|pet|use):[0-9]{1,4})\z/D', $body['key'])) reply(400, ['error'=>'invalid command']);
$lock = @fopen($base.'.lock', 'c');
if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) reply(429, ['error'=>'busy']);
$current = state($base);
if ($current['busy']) reply(429, ['error'=>'busy']);
if ($body['revision'] !== $current['revision'] + 1) reply(409, ['error'=>'stale revision']);
$request = $body['revision'].' '.$body['key']."\n";
$old = @file_get_contents($base.'.request');
if ($old !== false) {
    if ($old !== $request) reply(409, ['error'=>'request pending']);
    reply(202, ['pending'=>true]);
}
$temp = $base.'.'.bin2hex(random_bytes(8)).'.tmp';
if (@file_put_contents($temp, $request, LOCK_EX) !== strlen($request)) { @unlink($temp); reply(503, ['error'=>'mailbox unavailable']); }
if (!@rename($temp, $base.'.request')) { @unlink($temp); reply(503, ['error'=>'mailbox unavailable']); }
if (!is_file($base.'.state')) { @unlink($base.'.request'); reply(410, ['error'=>'session expired']); }
reply(202, ['pending'=>true]);
