<?php include 'header.php'; ?>

<h3>Daftar Buku</h3>
<a href="buku_tambah.php" class="btn btn-primary" style="margin-bottom: 15px;">Tambah Buku</a>

<!-- FORM SEARCH -->
<form method="GET" style="margin-bottom:15px;">
    <input 
        type="text" 
        name="keyword" 
        placeholder="Cari judul / penulis / kategori"
        value="<?= isset($_GET['keyword']) ? $_GET['keyword'] : '' ?>"
        style="padding:8px; width:260px;"
    >
    <button type="submit" class="btn btn-primary">Cari</button>
    <a href="buku_data.php" class="btn btn-secondary">Reset</a>
</form>

<div class="card">
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Judul</th>
                <th>Penulis</th>
                <th>Penerbit</th>
                <th>Tahun</th>
                <th>Kategori</th>
                <th>Stok</th>
                <th>Aksi</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';

            $query = "
                SELECT * FROM buku
                WHERE judul LIKE '%$keyword%'
                   OR penulis LIKE '%$keyword%'
                   OR kategori LIKE '%$keyword%'
                ORDER BY id ASC
            ";

            $result = mysqli_query($koneksi, $query);

            if (mysqli_num_rows($result) > 0) {
                while ($row = mysqli_fetch_assoc($result)) {
            ?>
            <tr>
                <td><?= $row['id']; ?></td>
                <td><?= htmlspecialchars($row['judul']); ?></td>
                <td><?= htmlspecialchars($row['penulis']); ?></td>
                <td><?= htmlspecialchars($row['penerbit']); ?></td>
                <td><?= $row['tahun']; ?></td>
                <td><?= htmlspecialchars($row['kategori']); ?></td>
                <td><?= $row['stok']; ?></td>
                <td>
                    <a href="buku_edit.php?id=<?= $row['id']; ?>" class="btn btn-warning">Edit</a>
                    <a href="buku_hapus.php?id=<?= $row['id']; ?>" 
                       class="btn btn-danger"
                       onclick="return confirm('Yakin ingin menghapus buku ini?')">
                       Hapus
                    </a>
                </td>
            </tr>
            <?php
                }
            } else {
                echo "<tr><td colspan='8' style='text-align:center;'>Tidak ada data buku.</td></tr>";
            }
            ?>
        </tbody>
    </table>
</div>

<?php include 'footer.php'; ?>
