<?php
// ══════════════════════════════════════════════════════════
//  save_stage.php  —  receives per-node progress from game
//  Upload to: tmudd.net/email_writing/save_stage.php
//  DROP-IN REPLACEMENT — adds CORS for Netlify, keeps same
//  JSON file storage format as original.
// ══════════════════════════════════════════════════════════

// ── CORS ──────────────────────────────────────────────────
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
$is_netlify = (bool) preg_match('/^https:\/\/[a-zA-Z0-9\-]+\.netlify\.app$/', $origin);
$is_same    = in_array($origin, ['https://tmudd.net', 'http://tmudd.net', '']);

if ($is_netlify || $is_same) {
    header("Access-Control-Allow-Origin: " . ($origin ?: 'https://tmudd.net'));
} else {
    header("Access-Control-Allow-Origin: https://tmudd.net");
}
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Max-Age: 86400");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST')    { http_response_code(405); echo json_encode(['error'=>'Method not allowed']); exit(); }

// ── Parse body ────────────────────────────────────────────
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || empty($data['name'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing name']);
    exit();
}

// ── Sanitise ──────────────────────────────────────────────
$name      = substr(trim($data['name']),        0, 80);
$key       = substr(trim(isset($data['key'])   ? $data['key']   : ''), 0, 40);
$label     = substr(trim(isset($data['label']) ? $data['label'] : ''), 0, 100);
$text      = substr(trim(isset($data['text'])  ? $data['text']  : ''), 0, 5000);
$xp        = intval(isset($data['xp'])         ? $data['xp']    : 0);
$complete  = (bool)(isset($data['complete'])   ? $data['complete'] : false);
$fullEmail = isset($data['fullEmail'])          ? substr($data['fullEmail'], 0, 20000) : null;
$elapsed   = isset($data['elapsed'])            ? intval($data['elapsed']) : null;
$now_ms    = round(microtime(true) * 1000);

// ── Load data file ────────────────────────────────────────
$data_file = __DIR__ . '/submissions.json';
$lock_file = __DIR__ . '/submissions.lock';

$lock = fopen($lock_file, 'w');
flock($lock, LOCK_EX);

$store = ['students' => []];
if (file_exists($data_file)) {
    $raw    = file_get_contents($data_file);
    $parsed = json_decode($raw, true);
    if ($parsed) $store = $parsed;
}

// ── Upsert student ────────────────────────────────────────
$name_key = strtolower($name);
if (!isset($store['students'][$name_key])) {
    $store['students'][$name_key] = [
        'name'      => $name,
        'registered'=> $now_ms,
        'sections'  => [],
        'complete'  => false,
        'fullEmail' => null,
        'elapsed'   => null,
        'xp'        => 0,
        'last_seen' => $now_ms,
    ];
}

$s =& $store['students'][$name_key];
$s['xp']       = $xp;
$s['last_seen']= $now_ms;

if ($complete) {
    $s['complete']  = true;
    $s['fullEmail'] = $fullEmail;
    $s['elapsed']   = $elapsed;
}

// ── Upsert section ────────────────────────────────────────
if ($key && $key !== 'joined' && $key !== 'complete') {
    $s['sections'][$key] = [
        'key'       => $key,
        'label'     => $label,
        'text'      => $text,
        'timestamp' => $now_ms,
    ];
}

// ── Save ──────────────────────────────────────────────────
file_put_contents($data_file, json_encode($store, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
flock($lock, LOCK_UN);
fclose($lock);

echo json_encode(['ok' => true, 'name' => $name, 'key' => $key, 'sections' => count($s['sections'])]);
