<?php
// save_post.php

// Get raw POST JSON
$input = file_get_contents('php://input');
if (!$input) {
    http_response_code(400);
    echo json_encode(["error" => "No input received"]);
    exit;
}

$data = json_decode($input, true);
if (!$data) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON"]);
    exit;
}

$file = 'data_akkoma.json';

// Load existing data or initialize array
if (file_exists($file)) {
    $existing = json_decode(file_get_contents($file), true);
    if (!is_array($existing)) {
        $existing = [];
    }
} else {
    $existing = [];
}

// Prepend new data (add to beginning)
array_unshift($existing, $data);

// Save back with pretty print & unicode unescaped
if (file_put_contents($file, json_encode($existing, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
    echo json_encode(["success" => true]);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to write to file"]);
}
