<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/functions.php';

// Pastikan output buffering dimulai
ob_start();

// Verifikasi request harus menggunakan metode GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    showAlert('error', 'Error!', 'Metode request tidak valid.', 'index.php');
    ob_end_flush();
    exit();
}

// Validasi parameter ID
if (!isset($_GET['id']) || !ctype_digit($_GET['id'])) {
    showAlert('error', 'Error!', 'ID barang tidak valid.', 'index.php');
    ob_end_flush();
    exit();
}

$id = (int)$_GET['id'];

// Mulai transaksi
$conn->begin_transaction();

try {
    // 1. Periksa keberadaan data
    $check_query = "SELECT id_barang FROM pdt_barang WHERE id_barang = ? LIMIT 1";
    $check_stmt = $conn->prepare($check_query);
    
    if (!$check_stmt) {
        throw new Exception('Prepare statement gagal: ' . $conn->error);
    }
    
    $check_stmt->bind_param("i", $id);
    
    if (!$check_stmt->execute()) {
        throw new Exception('Eksekusi statement gagal: ' . $check_stmt->error);
    }
    
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows === 0) {
        throw new Exception('Data barang tidak ditemukan');
    }
    
    // 2. Lakukan penghapusan
    $delete_query = "DELETE FROM pdt_barang WHERE id_barang = ?";
    $delete_stmt = $conn->prepare($delete_query);
    
    if (!$delete_stmt) {
        throw new Exception('Prepare statement gagal: ' . $conn->error);
    }
    
    $delete_stmt->bind_param("i", $id);
    
    if (!$delete_stmt->execute()) {
        throw new Exception('Gagal menghapus data: ' . $delete_stmt->error);
    }
    
    // Commit transaksi
    $conn->commit();
    
    // Set pesan sukses dalam session
    $_SESSION['alert'] = [
        'type' => 'success',
        'title' => 'Sukses!',
        'message' => 'Data barang berhasil dihapus.'
    ];
    
    // Redirect ke halaman index
    header('Location: index.php');
    ob_end_flush();
    exit();
    
} catch (Exception $e) {
    // Rollback transaksi jika ada error
    $conn->rollback();
    
    // Set pesan error dalam session
    $_SESSION['alert'] = [
        'type' => 'error',
        'title' => 'Error!',
        'message' => $e->getMessage()
    ];
    
    // Redirect ke halaman index
    header('Location: index.php');
    ob_end_flush();
    exit();
    
} finally {
    // Tutup statement
    if (isset($check_stmt)) $check_stmt->close();
    if (isset($delete_stmt)) $delete_stmt->close();
}
?>