<?php
session_start();

// Cek apakah admin sudah login
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

// Sertakan file config untuk koneksi database
include 'config.php';

// Periksa apakah ID mesin diberikan
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $machineId = $_GET['id'];

    try {
        // Mulai transaksi
        $db->beginTransaction();

        // Hapus mesin berdasarkan ID
        $deleteQuery = "DELETE FROM machine WHERE id = :machineId";
        $stmt = $db->prepare($deleteQuery);
        $stmt->bindParam(':machineId', $machineId, PDO::PARAM_INT);

        if ($stmt->execute()) {
            // Set pesan alert sukses ke session
            $_SESSION['alert'] = [
                'type' => 'success',
                'message' => 'Machine deleted successfully.'
            ];
        } else {
            // Jika gagal, set pesan alert gagal
            $_SESSION['alert'] = [
                'type' => 'danger',
                'message' => 'Failed to delete machine.'
            ];
        }

        // Commit transaksi
        $db->commit();
    } catch (Exception $e) {
        // Rollback jika terjadi kesalahan
        $db->rollBack();
        $_SESSION['alert'] = [
            'type' => 'danger',
            'message' => 'Error: ' . $e->getMessage()
        ];
    }
} else {
    // Jika ID tidak valid, set pesan alert gagal
    $_SESSION['alert'] = [
        'type' => 'danger',
        'message' => 'Invalid machine ID.'
    ];
}

// Arahkan kembali ke halaman machine.php
header("Location: machine.php");
exit;
?>
