<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);
    exit;
}

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

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

$record = [
    'receivedAt' => gmdate('c'),
    'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
    'page' => substr((string)($payload['page'] ?? ''), 0, 300),
    'ttfb' => (int)($payload['ttfb'] ?? 0),
    'fcp' => (int)($payload['fcp'] ?? 0),
    'lcp' => (int)($payload['lcp'] ?? 0),
    'inp' => (int)($payload['inp'] ?? 0),
    'cls' => (float)($payload['cls'] ?? 0),
    'domContentLoaded' => (int)($payload['domContentLoaded'] ?? 0),
    'loadEvent' => (int)($payload['loadEvent'] ?? 0),
    'imageRequestCount' => (int)($payload['imageRequestCount'] ?? 0),
    'imageTransferBytes' => (int)($payload['imageTransferBytes'] ?? 0),
    'imageDecodedBytes' => (int)($payload['imageDecodedBytes'] ?? 0),
    'ua' => substr((string)($payload['ua'] ?? ''), 0, 500),
];

$dataDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data';
if (!is_dir($dataDir)) {
    @mkdir($dataDir, 0775, true);
}

$logFile = $dataDir . DIRECTORY_SEPARATOR . 'perf-events.log';
if (is_file($logFile) && filesize($logFile) > 5 * 1024 * 1024) {
    @rename($logFile, $dataDir . DIRECTORY_SEPARATOR . 'perf-events-' . date('Ymd-His') . '.log');
}

$line = json_encode($record, JSON_UNESCAPED_SLASHES) . PHP_EOL;
@file_put_contents($logFile, $line, FILE_APPEND | LOCK_EX);

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