<?php
// /esp32/dashboard/api/data.php
// Disclaimer: This example code is part of a research prototype.
// It is provided “as is”, without any warranty of any kind.
// Please review, adapt, and test carefully before using it in production.

require_once __DIR__ . '/../auth.php';
require_login();

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

$nodeId = (int)($_GET['node_id'] ?? 0);
$range  = $_GET['range'] ?? '24h';

if ($nodeId <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing or invalid node_id']);
    exit;
}

// Parse the requested time window into hours.
$hours = 24;
if (preg_match('/^(\d+)h$/i', $range, $m)) {
    $hours = (int)$m[1];
} elseif (preg_match('/^(\d+)d$/i', $range, $m)) {
    $hours = (int)$m[1] * 24;
} elseif (preg_match('/^(\d+)w$/i', $range, $m)) {
    $hours = (int)$m[1] * 24 * 7;
}

// Clamp between 1 hour and 6 months.
$hours = max(1, min($hours, 24 * 180));

// Resolve node_id to device_id.
$stmt = pdo()->prepare('SELECT device_id FROM nodes WHERE id = ?');
$stmt->execute([$nodeId]);
$node = $stmt->fetch();

if (!$node) {
    http_response_code(404);
    echo json_encode(['error' => 'Node not found']);
    exit;
}

$deviceId = $node['device_id'];

// Query sensor data for the device.
$sql = "
  SELECT timestamp, sht_temp, humidity, bmp_temp, pressure, par, battery
  FROM sensor_data
  WHERE device_id = ?
    AND timestamp >= (NOW() - INTERVAL {$hours} HOUR)
  ORDER BY timestamp ASC
";
$stmt = pdo()->prepare($sql);
$stmt->execute([$deviceId]);
$rows = $stmt->fetchAll();

// Downsample on the server side to a safe maximum number of points.
$maxPoints = 2000;
$count     = count($rows);
$step      = ($count > $maxPoints) ? (int)ceil($count / $maxPoints) : 1;

$out = [];

for ($i = 0; $i < $count; $i += $step) {
    $r = $rows[$i];
    $out[] = [
        't'        => gmdate('c', strtotime($r['timestamp'])),
        'sht_temp' => $r['sht_temp'] === null ? null : (float)$r['sht_temp'],
        'humidity' => $r['humidity'] === null ? null : (float)$r['humidity'],
        'bmp_temp' => $r['bmp_temp'] === null ? null : (float)$r['bmp_temp'],
        'pressure' => $r['pressure'] === null ? null : (float)$r['pressure'],
        'par'      => $r['par'] === null ? null : (float)$r['par'],
        'battery'  => $r['battery'] === null ? null : (float)$r['battery'],
    ];
}

echo json_encode($out);
