<?php
// Koneksi ke database
$servername = "localhost";
$username = "wdpdev_master";
$password = "!Panda9980";
$dbname = "wdpdev_washing";

// Menghubungkan ke database
$conn = new mysqli($servername, $username, $password, $dbname);

// Mengecek koneksi
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Mendapatkan data dari request POST
$serialNumber = isset($_POST['serialNumber']) ? $_POST['serialNumber'] : '';
$branchId = isset($_POST['branchId']) ? $_POST['branchId'] : '';
$command = isset($_POST['command']) ? $_POST['command'] : '';

// Validasi input
if (empty($serialNumber) || empty($branchId) || empty($command)) {
    echo json_encode(["status" => "error", "message" => "Data tidak lengkap."]);
    $conn->close();
    exit;
}

// Pastikan command hanya bisa diupdate menjadi 'OFF'
if ($command !== 'OFF') {
    echo json_encode(["status" => "error", "message" => "Command hanya bisa diupdate menjadi OFF."]);
    $conn->close();
    exit;
}

// Query untuk memperbarui command
$sql = "UPDATE machine SET command = ?, last_updated = NOW() WHERE serialNumber = ? AND branchId = ?";

// Menyiapkan statement
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssi", $command, $serialNumber, $branchId);

// Menjalankan query dan memeriksa apakah berhasil
if ($stmt->execute()) {
    echo json_encode(["status" => "success", "message" => "Status command berhasil diperbarui."]);
} else {
    echo json_encode(["status" => "error", "message" => "Gagal memperbarui command."]);
}

// Menutup koneksi
$stmt->close();
$conn->close();
?>
