<?php
// public/api/results/save-browser-test.php
// Achtung: Passe Pfad und Bootstrapping an dein Projekt an!

require __DIR__ . '/../../../config/fileload.php';
session_start();

// Nur eingeloggte User
if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'not_authenticated']);
    exit;
}

$userId = (int)$_SESSION['user_id'];

// JSON einlesen
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid_json']);
    exit;
}

// Minimale Validierung
$mode = $data['mode_requested'] ?? null;
$totalDuration = $data['total_duration_s'] ?? null;

// DB: Beispiel (mysqli/PDO – hier PDO angenommen)
$db = get_db_connection(); // implementiere in deiner config

$stmt = $db->prepare("
    INSERT INTO usb_results_browser
        (user_id, mode, total_duration_s, report_json, created_at)
    VALUES
        (:user_id, :mode, :total_duration_s, :report_json, NOW())
");

$stmt->execute([
    ':user_id'         => $userId,
    ':mode'            => $mode,
    ':total_duration_s'=> $totalDuration,
    ':report_json'     => json_encode($data, JSON_UNESCAPED_UNICODE),
]);

$id = (int)$db->lastInsertId();

header('Content-Type: application/json; charset=utf-8');
echo json_encode([
    'status' => 'ok',
    'id'     => $id,
]);


