<?php
declare(strict_types=1);

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

require_once __DIR__ . '/../../bootstrap.php';
ym_require('src/services/TelemetryDbRouter.php');

$vesselKey = $_GET['vessel'] ?? 'silent_sea';
$lang      = $_GET['lang'] ?? 'de';
$range     = $_GET['range'] ?? '24h';

$allowedRanges = [
    '6h' => ['sql' => 'INTERVAL 6 HOUR', 'step' => 1],
    '24h' => ['sql' => 'INTERVAL 1 DAY',   'step' => 1],
    '1m'  => ['sql' => 'INTERVAL 1 MONTH', 'step' => 10],
    '1y'  => ['sql' => 'INTERVAL 1 YEAR',  'step' => 100],
];

if (!isset($allowedRanges[$range])) {
    $range = '24h';
}

$intervalSql = $allowedRanges[$range]['sql'];
$step        = $allowedRanges[$range]['step'];

try {
    $db = TelemetryDbRouter::getTelemetryPdoByVesselKey($vesselKey);

    $stmt = $db->query("
        SELECT Zeit, category, wert
        FROM ENVdata
        WHERE category IN ('windspeed', 'windtrue')
          AND Zeit >= NOW() - $intervalSql
        ORDER BY Zeit ASC
    ");

    $rowsByTime = [];

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $time = $row['Zeit'];
        $cat  = $row['category'];

        if (!isset($rowsByTime[$time])) {
            $rowsByTime[$time] = [
                'time' => $time,
                'windspeed' => null,
                'windtrue' => null,
            ];
        }

        if (is_numeric($row['wert'])) {
            $rowsByTime[$time][$cat] = (float)$row['wert'];
        }
    }

    $points = [];
    $i = 0;

    foreach ($rowsByTime as $point) {
        $i++;

        if ($step > 1 && ($i % $step !== 0)) {
            continue;
        }

        if ($point['windspeed'] === null && $point['windtrue'] === null) {
            continue;
        }

        $points[] = $point;
    }

    echo json_encode([
        'success' => true,
        'vessel' => $vesselKey,
        'lang' => $lang,
        'range' => $range,
        'step' => $step,
        'count' => count($points),
        'points' => $points,
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

} catch (Throwable $e) {
    http_response_code(500);

    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
