<?php
date_default_timezone_set('Asia/Jakarta');
require_once __DIR__ . '/../config/koneksi.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid Request");
}

$suhu = floatval($_POST['suhu'] ?? 0);
$kelembapan = floatval($_POST['kelembapan'] ?? 0);

$tanggal = date("Y-m-d");
$jam = date("H:i:s");

// AMBIL DATA TERAKHIR DI sumberdaya
$sql = "SELECT suhu, kelembapan FROM sumberdaya WHERE id = 1 LIMIT 1";
$res = mysqli_query($koneksi, $sql);
$row = mysqli_fetch_assoc($res);

$last_suhu = floatval($row['suhu']);
$last_kelembapan = floatval($row['kelembapan']);

$updateStatus = [];

// ---------- Jika Suhu Berubah ----------
if ($suhu != $last_suhu) {
    
    $statusSuhu = ($suhu > $last_suhu) ? "Naik" : "Turun";

    // update sumberdaya
    $up1 = $koneksi->prepare("UPDATE sumberdaya SET suhu=? WHERE id=1");
    $up1->bind_param("d", $suhu);
    $up1->execute();

    // log_suhu
    $log1 = $koneksi->prepare("INSERT INTO log_suhu (tanggal, status_suhu, update_suhu, last_suhu, jam_update)
                               VALUES (?, ?, ?, ?, ?)");
    $log1->bind_param("ssdds", $tanggal, $statusSuhu, $suhu, $last_suhu, $jam);
    $log1->execute();

    $updateStatus[] = "Suhu: $last_suhu → $suhu ($statusSuhu)";
}

// ---------- Jika Kelembapan Berubah ----------
if ($kelembapan != $last_kelembapan) {

    $statusKel = ($kelembapan > $last_kelembapan) ? "Naik" : "Turun";

    // update sumberdaya
    $up2 = $koneksi->prepare("UPDATE sumberdaya SET kelembapan=? WHERE id=1");
    $up2->bind_param("d", $kelembapan);
    $up2->execute();

    // log_kelembapan
    $log2 = $koneksi->prepare("INSERT INTO log_kelembapan (tanggal, status_kelembapan, update_kelembapan, last_kelembapan, jam_update)
                              VALUES (?, ?, ?, ?, ?)");
    $log2->bind_param("ssdds", $tanggal, $statusKel, $kelembapan, $last_kelembapan, $jam);
    $log2->execute();

    $updateStatus[] = "Kelembapan: $last_kelembapan → $kelembapan ($statusKel)";
}

if (empty($updateStatus)) {
    echo "Tidak ada perubahan";
} else {
    echo "Update: " . implode(" & ", $updateStatus);
}
