<?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_asal = intval($_GET['id']);

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

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

// Delete source
$stmt = $conn->prepare("DELETE FROM pdta_asal_usul WHERE id_asal = ?");
$stmt->bind_param("i", $id_asal);

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

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