<?php
include '../../includes/auth.php';

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

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

// Get the item data to delete the photo
$query = "SELECT foto FROM pdta_inventaris_barang WHERE id_barang = $id_barang";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result)) {
    $item = mysqli_fetch_assoc($result);
    $foto = $item['foto'];
    
    // Delete the item
    $delete_query = "DELETE FROM pdta_inventaris_barang WHERE id_barang = $id_barang";
    if (mysqli_query($conn, $delete_query)) {
        // Delete the photo if exists
        if ($foto && file_exists('../../uploads/' . $foto)) {
            unlink('../../uploads/' . $foto);
        }
        $_SESSION['success'] = 'Data barang berhasil dihapus';
    } else {
        $_SESSION['error'] = 'Gagal menghapus data: ' . mysqli_error($conn);
    }
} else {
    $_SESSION['error'] = 'Barang tidak ditemukan';
}

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