<?php
// save.php — writes the annotations fragment to annotations.html (same folder)
header('Content-Type: application/json');

// IMPORTANT: set the same password here as in index.html (EDIT_PASSWORD)
$SERVER_PASSWORD = 'wuhuan25';

$raw = file_get_contents('php://input');
if (!$raw) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'No payload']); exit; }

$payload = json_decode($raw, true);
if (!is_array($payload)) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'Bad JSON']); exit; }

$pwd = $payload['password'] ?? '';
$path = $payload['path'] ?? '';
$content = $payload['content'] ?? '';

if ($pwd !== $SERVER_PASSWORD) { http_response_code(403); echo json_encode(['ok'=>false,'error'=>'Forbidden']); exit; }

// Only allow writing the fixed annotations file name to avoid traversal
$allowed = 'annotations.html';
if ($path !== $allowed) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'Invalid path']); exit; }

// Write the raw fragment (innerHTML of <g id="annotations">)
if (file_put_contents($allowed, $content) === false) {
  http_response_code(500); echo json_encode(['ok'=>false,'error'=>'Write failed']); exit;
}

echo json_encode(['ok'=>true]);
