<?php

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed. Use POST."]);
    exit;
}

// Set headers to accept JSON
header('Content-Type: application/json');

// Get the raw POST body
$rawBody = file_get_contents('php://input');
$newData = json_decode($rawBody, true);

if ($newData === null) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON payload"]);
    exit;
}

// Add a server-side timestamp
$newData['serverReceivedAt'] = gmdate('Y-m-d\TH:i:s.v\Z');

// Define the path to the analytics.json file
$filePath = __DIR__ . '/analytics.json';

$analyticsData = [];

// Check if the file already exists and has data
if (file_exists($filePath)) {
    $fileContent = file_get_contents($filePath);
    if (!empty($fileContent)) {
        $parsedData = json_decode($fileContent, true);
        if (is_array($parsedData)) {
            $analyticsData = $parsedData;
        } else {
            // Log error or handle gracefully if JSON is malformed
            error_log('Error parsing existing analytics.json');
        }
    }
}

// Append the new data
$analyticsData[] = $newData;

// Save the updated data back to analytics.json
// LOCK_EX flag prevents concurrent writes from corrupting the file
$success = file_put_contents($filePath, json_encode($analyticsData, JSON_PRETTY_PRINT), LOCK_EX);

if ($success !== false) {
    http_response_code(200);
    echo json_encode(["success" => true, "message" => "Data saved successfully."]);
} else {
    http_response_code(500);
    echo json_encode(["error" => "Failed to write data locally."]);
}
?>
