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

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// ================= VALIDASI =================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die("Invalid request");
}

// ================= AMBIL DATA =================
$voltage = floatval($_POST['voltage'] ?? 0);
$current = floatval($_POST['current'] ?? 0);
$power   = floatval($_POST['power'] ?? 0);
$energy  = floatval($_POST['energy'] ?? 0);

// Validasi dasar
if ($voltage <= 0) {
    die("Data tidak valid");
}

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

// ================= AMBIL / BUAT DATA =================
$get = $koneksi->query("SELECT * FROM sumberdaya WHERE id=1");
$data = $get->fetch_assoc();

if (!$data) {
    $koneksi->query("
        INSERT INTO sumberdaya 
        (id, listrik, air, vol_in_last, vol_out_last, suhu, kelembapan, listrik_harian, last_energy, last_reset, power_now)
        VALUES (1, 0, 0, 0, 0, 0, 0, 0, 0, '$tanggal', 0)
    ");

    $get = $koneksi->query("SELECT * FROM sumberdaya WHERE id=1");
    $data = $get->fetch_assoc();
}

// ================= DATA LAMA =================
$lastEnergy = floatval($data['last_energy']);
$lastReset  = $data['last_reset'];
$listrik_harian = floatval($data['listrik_harian']);
$lastPower  = floatval($data['power_now']);

// ================= RESET HARIAN =================
if (empty($lastReset) || $lastReset != $tanggal) {
    $listrik_harian = 0;

    $koneksi->query("
        UPDATE sumberdaya 
        SET listrik_harian = 0, last_reset = '$tanggal'
        WHERE id=1
    ");
}

// ================= HITUNG KWH =================
$delta = $energy - $lastEnergy;
if ($delta < 0) $delta = 0;

$listrik_harian += $delta;

// ================= LOGIKA FILTER POWER =================
$updatePower = false;

// hanya update jika beda >= 5 Watt
if (abs($power - $lastPower) >= 5) {
    $updatePower = true;
}

// ================= UPDATE SUMBERDAYA =================
if ($updatePower) {

    $stmt = $koneksi->prepare("
        UPDATE sumberdaya 
        SET listrik=?, listrik_harian=?, last_energy=?, power_now=? 
        WHERE id=1
    ");
    $stmt->bind_param("dddd", $energy, $listrik_harian, $energy, $power);
    $stmt->execute();
}

// ================= SIMPAN RAW =================
$stmt2 = $koneksi->prepare("
    INSERT INTO monitoring_listrik (voltage, current, power, energy)
    VALUES (?, ?, ?, ?)
");
$stmt2->bind_param("dddd", $voltage, $current, $power, $energy);
$stmt2->execute();

// ================= LOG =================
$fields = [
    "voltage" => $voltage,
    "current" => $current,
    "power"   => $power,
    "energy"  => $energy
];

foreach ($fields as $k => $v) {

    $log = $koneksi->prepare("
        INSERT INTO log_listrik 
        (tanggal, status_update, data_update, nilai_update, waktu_update)
        VALUES (?, 'update', ?, ?, ?)
    ");
    $log->bind_param("ssds", $tanggal, $k, $v, $jam);
    $log->execute();
}

// ================= RESPONSE =================
echo "OK | Power: $power W | Last: $lastPower W";
?>