<?php
header('Content-Type: application/json');
require_once __DIR__ . "/../../../app/config/koneksi.php";

// MODE CHECK
if (isset($_GET['mode']) && $_GET['mode'] === 'check') {
    $q = mysqli_query($koneksi, "SELECT MAX(id) AS last_id FROM sumberdaya");
    $r = mysqli_fetch_assoc($q);
    echo json_encode(["last_id" => (int)$r['last_id']]);
    exit;
}

// Ambil data terakhir
$q = mysqli_query($koneksi, "SELECT * FROM sumberdaya ORDER BY id DESC LIMIT 1");
$data = mysqli_fetch_assoc($q);

if (!$data) {
    echo json_encode([
        "items" => [
            ["nama" => "listrik", "nilai" => 0],
            ["nama" => "air", "nilai" => 0],
            ["nama" => "suhu", "nilai" => 0],
            ["nama" => "kelembapan", "nilai" => 0]
        ],
        "last_id" => 0
    ]);
    exit;
}

// fallback kalau power belum ada
$power = isset($data['power_now']) ? (float)$data['power_now'] : 0;

echo json_encode([
    "items" => [
        ["nama" => "listrik", "nilai" => $power],
        ["nama" => "air", "nilai" => (float)$data['air']],
        ["nama" => "suhu", "nilai" => (float)$data['suhu']],
        ["nama" => "kelembapan", "nilai" => (float)$data['kelembapan']]
    ],
    "last_id" => (int)$data['id']
]);