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

// ================= KONFIGURASI =================
$INITIAL_VOLUME = 0; // <-- isi kalau mau pakai offset (misal 300), atau biarkan 0 kalau pakai DB

$TOLERANCE = -20; // toleransi error (liter)

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

$tipe   = $_POST['tipe']   ?? '';
$volume = floatval($_POST['volume'] ?? 0);

$allowed = ['IN', 'WUDHU', 'KM'];

if (!in_array($tipe, $allowed)) {
    die("Tipe tidak valid");
}

if ($volume <= 0 || $volume > 1000) {
    die("Volume tidak masuk akal");
}

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

// ================= TRANSAKSI =================
$koneksi->begin_transaction();

// Lock row biar aman
$q = $koneksi->prepare("SELECT vol_in_last, vol_out_last FROM sumberdaya WHERE id = 1 FOR UPDATE");
$q->execute();
$data = $q->get_result()->fetch_assoc();

$vol_in_last  = floatval($data['vol_in_last']);
$vol_out_last = floatval($data['vol_out_last']);

$status_air = "";
$last_air   = 0;

// ================= UPDATE DATA =================
if ($tipe === "IN") {

    $last_air = $vol_in_last;

    $update = $koneksi->prepare("
        UPDATE sumberdaya 
        SET vol_in_last = vol_in_last + ?
        WHERE id = 1
    ");
    $update->bind_param("d", $volume);
    $update->execute();

    $status_air = "IN | AIR MASUK";
}
else {

    $last_air = $vol_out_last;

    $update = $koneksi->prepare("
        UPDATE sumberdaya 
        SET vol_out_last = vol_out_last + ?
        WHERE id = 1
    ");
    $update->bind_param("d", $volume);
    $update->execute();

    if ($tipe === "WUDHU") {
        $status_air = "OUT | WUDHU";
    } else {
        $status_air = "OUT | KAMAR MANDI";
    }
}

// ================= AMBIL DATA TERBARU =================
$q2 = $koneksi->prepare("SELECT vol_in_last, vol_out_last FROM sumberdaya WHERE id = 1");
$q2->execute();
$d2 = $q2->get_result()->fetch_assoc();

// ================= HITUNG AIR =================
$air_bersih = $INITIAL_VOLUME 
            + floatval($d2['vol_in_last']) 
            - floatval($d2['vol_out_last']);

// ================= DETEKSI ERROR =================
$is_anomaly = 0;
$note = "";

// toleransi awal
if ($air_bersih < $TOLERANCE) {
    $status_air = "ERROR | KEBOCORAN / SENSOR";
    $is_anomaly = 1;
    $note = "Air minus melebihi toleransi";
}

// lonjakan tidak wajar
if ($volume > 50) {
    $is_anomaly = 1;
    $note = "Pemakaian besar";
}

// kondisi awal sistem
if ($vol_in_last == 0 && $vol_out_last == 0) {
    $status_air = "INIT SYSTEM";
}

// ================= SIMPAN LOG =================
$log = $koneksi->prepare("
    INSERT INTO log_air 
    (tanggal, last_air, status_air, update_air, total_air, air_bersih, jam_update, is_anomaly, anomaly_note)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$total_air = $air_bersih;

$log->bind_param(
    "sdssddsiss",
    $tanggal,
    $last_air,
    $status_air,
    $volume,
    $total_air,
    $air_bersih,
    $jam,
    $is_anomaly,
    $note
);

$log->execute();

// commit transaksi
$koneksi->commit();

// ================= RESPONSE =================
echo "OK | $status_air | volume: $volume L | sisa: $air_bersih L";
?>