<?php
require_once __DIR__ . '/../../config/koneksi.php';

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

if ($volume <= 0) die("Volume tidak valid");

$koneksi->begin_transaction();

$q = $koneksi->query("SELECT vol_in_last, vol_out_last FROM sumberdaya WHERE id=1 FOR UPDATE");
$data = $q->fetch_assoc();

// Update OUT
$koneksi->query("UPDATE sumberdaya SET vol_out_last = vol_out_last + $volume WHERE id=1");

// Ambil ulang
$q2 = $koneksi->query("SELECT vol_in_last, vol_out_last FROM sumberdaya WHERE id=1");
$d2 = $q2->fetch_assoc();

$air_bersih = $d2['vol_in_last'] - $d2['vol_out_last'];

// Anomaly
$is_anomaly = 0;
$note = "";

if ($air_bersih < 0) {
    $is_anomaly = 1;
    $note = "Kebocoran / data tidak sinkron";
}

// Log
$stmt = $koneksi->prepare("
INSERT INTO log_air 
(tanggal, last_air, status_air, update_air, total_air, air_bersih, jam_update, is_anomaly, anomaly_note)
VALUES (CURDATE(), ?, ?, ?, ?, ?, CURTIME(), ?, ?)
");

$stmt->bind_param("dsdddis",
    $data['vol_out_last'],
    $jenis,
    $volume,
    $air_bersih,
    $air_bersih,
    $is_anomaly,
    $note
);

$stmt->execute();

$koneksi->commit();

echo "OK OUT | $jenis | $volume L | Sisa: $air_bersih";