<?php
/**
 * API: Statistiken – CPU-Temperatur, Stromverbrauch und Raumklima-Verlaufsdaten.
 *
 * action=history   CPU/Strom-Verlaufsdaten.
 *   range=1h|6h|24h|7d  (Standard: 24h)
 *
 * action=summary   Min/Max/Avg-Zusammenfassung für eine Range.
 *   range=1h|6h|24h|7d
 *
 * action=sensors   CO2, Temperatur, Luftfeuchtigkeit aus SCD41.
 *   range=1h|6h|24h|7d
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_common.php';

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

$pdo    = $GLOBALS['pdo'] ?? null;
$action = isset($_REQUEST['action']) ? trim((string)$_REQUEST['action']) : 'history';

$rangeMap = [
    '1h'  => ['sql' => 'INTERVAL 1 HOUR',  'bucket_min' => null],
    '6h'  => ['sql' => 'INTERVAL 6 HOUR',  'bucket_min' => 2],
    '24h' => ['sql' => 'INTERVAL 24 HOUR', 'bucket_min' => 5],
    '7d'  => ['sql' => 'INTERVAL 7 DAY',   'bucket_min' => 30],
];

$range    = isset($_REQUEST['range']) && isset($rangeMap[$_REQUEST['range']]) ? $_REQUEST['range'] : '24h';
$interval = $rangeMap[$range]['sql'];
$bucket   = $rangeMap[$range]['bucket_min'];

// ─── history ──────────────────────────────────────────────────────────────────
if ($action === 'history') {
    if (!$pdo) {
        echo json_encode(['ok' => false, 'message' => 'Keine DB-Verbindung.', 'data' => [], 'range' => $range]);
        exit;
    }
    try {
        if ($bucket !== null) {
            // Downsampling per Zeitfenster (Durchschnitt je Bucket)
            $sql = "
                SELECT
                    DATE_FORMAT(
                        FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(zeitstempel) / ({$bucket} * 60)) * ({$bucket} * 60)),
                        '%Y-%m-%d %H:%i:00'
                    ) AS t,
                    ROUND(AVG(cpu_temp), 1) AS cpu_temp,
                    ROUND(AVG(watts),    2) AS watts,
                    ROUND(AVG(volt),     3) AS volt,
                    ROUND(AVG(amp),      4) AS amp
                FROM statistiken
                WHERE zeitstempel > DATE_SUB(NOW(), {$interval})
                GROUP BY FLOOR(UNIX_TIMESTAMP(zeitstempel) / ({$bucket} * 60))
                ORDER BY t ASC
            ";
        } else {
            $sql = "
                SELECT zeitstempel AS t, cpu_temp, watts, volt, amp
                FROM statistiken
                WHERE zeitstempel > DATE_SUB(NOW(), {$interval})
                ORDER BY zeitstempel ASC
            ";
        }

        $stmt = $pdo->query($sql);
        $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];

        $data = array_map(static function (array $r): array {
            return [
                't'        => $r['t'],
                'cpu_temp' => $r['cpu_temp'] !== null ? (float)$r['cpu_temp'] : null,
                'watts'    => $r['watts']    !== null ? (float)$r['watts']    : null,
                'volt'     => $r['volt']     !== null ? (float)$r['volt']     : null,
                'amp'      => $r['amp']      !== null ? (float)$r['amp']      : null,
            ];
        }, $rows);

        echo json_encode(['ok' => true, 'data' => $data, 'range' => $range, 'count' => count($data)]);
    } catch (Throwable $e) {
        echo json_encode(['ok' => false, 'message' => $e->getMessage(), 'data' => [], 'range' => $range]);
    }
    exit;
}

// ─── summary ──────────────────────────────────────────────────────────────────
if ($action === 'summary') {
    if (!$pdo) {
        echo json_encode(['ok' => false, 'message' => 'Keine DB-Verbindung.']);
        exit;
    }
    try {
        $sql = "
            SELECT
                COUNT(*)                         AS anzahl,
                ROUND(MIN(cpu_temp), 1)          AS cpu_min,
                ROUND(MAX(cpu_temp), 1)          AS cpu_max,
                ROUND(AVG(cpu_temp), 1)          AS cpu_avg,
                ROUND(MIN(watts),    2)          AS w_min,
                ROUND(MAX(watts),    2)          AS w_max,
                ROUND(AVG(watts),    2)          AS w_avg,
                MIN(zeitstempel)                 AS von,
                MAX(zeitstempel)                 AS bis
            FROM statistiken
            WHERE zeitstempel > DATE_SUB(NOW(), {$interval})
        ";
        $stmt = $pdo->query($sql);
        $row  = $stmt ? $stmt->fetch(PDO::FETCH_ASSOC) : null;
        echo json_encode(['ok' => true, 'summary' => $row, 'range' => $range]);
    } catch (Throwable $e) {
        echo json_encode(['ok' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ─── sensors ──────────────────────────────────────────────────────────────────
if ($action === 'sensors') {
    if (!$pdo) {
        echo json_encode(['ok' => false, 'message' => 'Keine DB-Verbindung.', 'data' => [], 'range' => $range]);
        exit;
    }
    try {
        if ($bucket !== null) {
            $sql = "
                SELECT
                    DATE_FORMAT(
                        FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(zeitstempel) / ({$bucket} * 60)) * ({$bucket} * 60)),
                        '%Y-%m-%d %H:%i:00'
                    ) AS t,
                    ROUND(AVG(co2),      0) AS co2,
                    ROUND(AVG(temp_scd), 1) AS temp_scd,
                    ROUND(AVG(hum_scd),  1) AS hum_scd
                FROM sensoren
                WHERE zeitstempel > DATE_SUB(NOW(), {$interval})
                  AND status = 'ok'
                GROUP BY FLOOR(UNIX_TIMESTAMP(zeitstempel) / ({$bucket} * 60))
                ORDER BY t ASC
            ";
        } else {
            $sql = "
                SELECT zeitstempel AS t, co2, temp_scd, hum_scd
                FROM sensoren
                WHERE zeitstempel > DATE_SUB(NOW(), {$interval})
                  AND status = 'ok'
                ORDER BY zeitstempel ASC
            ";
        }

        $stmt = $pdo->query($sql);
        $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];

        $data = array_map(static function (array $r): array {
            return [
                't'        => $r['t'],
                'co2'      => $r['co2']      !== null ? (int)$r['co2']      : null,
                'temp_scd' => $r['temp_scd'] !== null ? (float)$r['temp_scd'] : null,
                'hum_scd'  => $r['hum_scd']  !== null ? (float)$r['hum_scd']  : null,
            ];
        }, $rows);

        echo json_encode(['ok' => true, 'data' => $data, 'range' => $range, 'count' => count($data)]);
    } catch (Throwable $e) {
        echo json_encode(['ok' => false, 'message' => $e->getMessage(), 'data' => [], 'range' => $range]);
    }
    exit;
}

echo json_encode(['ok' => false, 'message' => 'Unbekannte Aktion.']);
