<?php
include ("koneksi.php");

// Cek apakah ada ID yang dikirim untuk dihapus
if (isset($_POST['delete_id'])) {
    $id = $_POST['delete_id'];
    $koneksi->query("DELETE FROM buku WHERE id_buku = $id");
    
    // Redirect agar form tidak dikirim ulang saat refresh
    header("Location: index.php");
    exit();
}

// Ambil data dari tabel buku
$result = $koneksi->query("SELECT * FROM buku");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hapus Data dengan Konfirmasi</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body>

    <h2>Daftar Buku</h2>
    <table border="1" cellspacing="0" cellpadding="10">
        <tr>
            <th>ID</th>
            <th>Judul Buku</th>
            <th>Aksi</th>
        </tr>
        <?php while ($row = $result->fetch_assoc()) : ?>
            <tr>
                <td><?= $row['id_buku']; ?></td>
                <td><?= $row['judul_buku']; ?></td>
                <td>
                    <form method="POST" onsubmit="return confirmDelete(this);">
                        <input type="hidden" name="delete_id" value="<?= $row['id_buku']; ?>">
                        <button type="submit">Hapus</button>
                    </form>
                </td>
            </tr>
        <?php endwhile; ?>
    </table>

    <script>
        function confirmDelete(form) {
            Swal.fire({
                title: "Apakah Anda yakin?",
                text: "Data yang dihapus tidak bisa dikembalikan!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#d33",
                cancelButtonColor: "#3085d6",
                confirmButtonText: "Ya, hapus!",
                cancelButtonText: "Batal"
            }).then((result) => {
                if (result.isConfirmed) {
                    form.submit();
                }
            });

            return false; // Mencegah form langsung terkirim
        }
    </script>

</body>
</html>
