<?php
// /api/v1/result/browser.quick.test.php

declare(strict_types=1);

/**
 * Handler für:  /v1/browser.quick.test
 *
 * Wird vom Router (/api/router/router.v1.php) aufgerufen.
 * Erwartung:
 *   function browser_quick_test_handle_request(): array
 */
function browser_quick_test_handle_request(): array
{
    // Session sicherstellen (sollte über fileload.php schon aktiv sein,
    // aber doppelt ist hier unkritisch)
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    // ---------------------------------------------------------------------
    // 0. client_id aus zentraler fileload.php
    // ---------------------------------------------------------------------
    // fileload.php setzt:
    //   $GLOBALS['usb_client_id']  UND  das Cookie 'usbcheck_client'
    $clientId = $GLOBALS['usb_client_id'] ?? ($_COOKIE['usbcheck_client'] ?? null);

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

    if (!is_array($data)) {
        return [
            'ok'    => false,
            'error' => 'Invalid JSON payload',
        ];
    }

    // ---------------------------------------------------------------------
    // 2. User / Session ermitteln (robust, mehrere Varianten)
    // ---------------------------------------------------------------------
    $userId     = null;
    $isLoggedIn = 0;

    // A) Klassisch: user_id direkt in der Session
    if (!empty($_SESSION['user_id'])) {
        $userId = (int)$_SESSION['user_id'];
    }
    // B) Dein aktuelles Login verwendet $_SESSION['user']['id']
    elseif (!empty($_SESSION['user']) && is_array($_SESSION['user']) && !empty($_SESSION['user']['id'])) {
        $userId = (int)$_SESSION['user']['id'];
    }
    // C) Optionaler auth-Block (z.B. $_SESSION['auth']['user_id'])
    elseif (!empty($_SESSION['auth']) && is_array($_SESSION['auth']) && !empty($_SESSION['auth']['user_id'])) {
        $userId = (int)$_SESSION['auth']['user_id'];
    }

    if ($userId) {
        $isLoggedIn = 1;
    }

    $sessionId = session_id() ?: null;

    $ipAddress  = $_SERVER['REMOTE_ADDR']     ?? null;
    $userAgent  = $_SERVER['HTTP_USER_AGENT'] ?? null;

    // ---------------------------------------------------------------------
    // 3. Grobe Auswertung aus dem Report (optional)
    // ---------------------------------------------------------------------
    $modeRequested = $data['mode_requested'] ?? 'unknown';
    $meta          = $data['meta'] ?? [];

    // Browser/OS – vorerst leer, später per Parser füllen
    $browserName    = null;
    $browserVersion = null;
    $osName         = null;
    $osVersion      = null;

    // Gesamtmenge geschriebener/verifizierter Bytes aggregieren
    $measuredBytes = 0;

    if (!empty($data['quick']) && is_array($data['quick'])) {
        $measuredBytes += (int)($data['quick']['size_bytes'] ?? 0);
    }
    if (!empty($data['benchmark']) && is_array($data['benchmark'])) {
        $measuredBytes += (int)($data['benchmark']['size_bytes'] ?? 0);
    }
    if (!empty($data['writeverify']) && is_array($data['writeverify'])) {
        $measuredBytes += (int)($data['writeverify']['total_bytes'] ?? 0);
    }

    // Kapazitätsstatus vorerst neutral
    $capacityStatus = 'unknown';

    // Volume-/Stick-Daten aktuell noch nicht separat ermittelt
    $volumeLabel   = null;
    $manufacturer  = null;
    $modelName     = null;
    $usbType       = null;
    $filesystem    = null;

    // advertised_capacity_bytes kennen wir im Browser noch nicht:
    $advCapacityBytes = null;

    // test_report_json = kompletter Report (roher JSON-String)
    $testReportJson = $raw ?: json_encode($data, JSON_UNESCAPED_UNICODE);

    // ---------------------------------------------------------------------
    // 4. Insert in web_quicktests
    // ---------------------------------------------------------------------
    /** @var PDO $pdo */
    global $pdo;

    try {
        $sql = "
            INSERT INTO web_quicktests (
                user_id,
                is_logged_in,
                usb_device_id,
                browser_name,
                browser_version,
                os_name,
                os_version,
                volume_label,
                manufacturer,
                model_name,
                usb_type,
                advertised_capacity_bytes,
                measured_capacity_bytes,
                capacity_status,
                filesystem,
                test_report_json,
                ip_address,
                session_id,
                client_id
            )
            VALUES (
                :user_id,
                :is_logged_in,
                :usb_device_id,
                :browser_name,
                :browser_version,
                :os_name,
                :os_version,
                :volume_label,
                :manufacturer,
                :model_name,
                :usb_type,
                :advertised_capacity_bytes,
                :measured_capacity_bytes,
                :capacity_status,
                :filesystem,
                :test_report_json,
                :ip_address,
                :session_id,
                :client_id
            )
        ";

        $stmt = $pdo->prepare($sql);

        $stmt->execute([
            'user_id'                   => $userId,
            'is_logged_in'              => $isLoggedIn,
            'usb_device_id'             => null,
            'browser_name'              => $browserName,
            'browser_version'           => $browserVersion,
            'os_name'                   => $osName,
            'os_version'                => $osVersion,
            'volume_label'              => $volumeLabel,
            'manufacturer'              => $manufacturer,
            'model_name'                => $modelName,
            'usb_type'                  => $usbType,
            'advertised_capacity_bytes' => $advCapacityBytes,
            'measured_capacity_bytes'   => $measuredBytes ?: null,
            'capacity_status'           => $capacityStatus,
            'filesystem'                => $filesystem,
            'test_report_json'          => $testReportJson,
            'ip_address'                => $ipAddress,
            'session_id'                => $sessionId,
            'client_id'                 => $clientId,
        ]);

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

        // DEBUG-Ausgabe – später für PROD aufräumen
        return [
            'ok'             => true,
            'id'             => $id,
            'mode'           => $modeRequested,
            'measured_bytes' => $measuredBytes ?: null,

            'debug_user_id'          => $userId,
            'debug_is_logged_in'     => $isLoggedIn,
            'debug_session_id'       => $sessionId,
            'debug_client_id'        => $clientId,
            'debug_session_has_user' => isset($_SESSION['user']),
            'debug_session_user'     => $_SESSION['user'] ?? null,
        ];
    } catch (Throwable $e) {
        error_log('[usbcheck] web_quicktests insert failed: ' . $e->getMessage());

        return [
            'ok'    => false,
            'error' => 'DB error',
            'debug' => $e->getMessage(),
        ];
    }
}
