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

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

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

// Delete location
$stmt = $conn->prepare("DELETE FROM pdta_lokasi WHERE id_lokasi = ?");
$stmt->bind_param("i", $id_lokasi);

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

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