<?php
require_once '../../config/database.php';
require_once '../../includes/auth.php';

// Check if ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error'] = "ID tidak valid";
    header("Location: index.php");
    exit();
}

$id_jenis = intval($_GET['id']);

// Check if this item type is used in any inventory items
$check = $conn->prepare("SELECT id_barang FROM pdta_inventaris_barang WHERE id_jenis = ?");
$check->bind_param("i", $id_jenis);
$check->execute();
$check->store_result();

if ($check->num_rows > 0) {
    $_SESSION['error'] = "Tidak dapat menghapus jenis barang karena sudah digunakan di data inventaris";
    header("Location: index.php");
    exit();
}

// Delete item type
$stmt = $conn->prepare("DELETE FROM pdta_jenis_barang WHERE id_jenis = ?");
$stmt->bind_param("i", $id_jenis);

if ($stmt->execute()) {
    $_SESSION['success'] = "Data jenis barang berhasil dihapus";
} else {
    $_SESSION['error'] = "Gagal menghapus data jenis barang: " . $conn->error;
}

header("Location: index.php");
exit();
?>