<?php
require 'config.php';

// Fitur Hapus
if (isset($_GET['hapus'])) {
    $id = $_GET['hapus'];
    $ambil_foto = mysqli_query($conn, "SELECT image FROM posts WHERE id='$id'");
    $data = mysqli_fetch_assoc($ambil_foto);
    unlink("uploads/" . $data['image']); // Hapus file fisik
    mysqli_query($conn, "DELETE FROM posts WHERE id='$id'");
    echo "<script>alert('Berita Dihapus!'); window.location='list-posts.php';</script>";
}

$query = mysqli_query($conn, "SELECT * FROM posts ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html>
<head>
    <title>Kelola Berita</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body class="bg-light p-4">
    <div class="card shadow">
        <div class="card-header bg-danger text-white d-flex justify-content-between">
            <h5 class="mb-0">Daftar Berita</h5>
            <a href="add-post.php" class="btn btn-sm btn-light">Tambah Berita</a>
        </div>
        <div class="card-body">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Gambar</th>
                        <th>Judul Berita</th>
                        <th>Kategori</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($row = mysqli_fetch_assoc($query)) : ?>
                    <tr>
                        <td><img src="uploads/<?= $row['image'] ?>" width="80"></td>
                        <td><?= $row['title'] ?></td>
                        <td><span class="badge bg-secondary"><?= $row['category'] ?></span></td>
                        <td>
                            <a href="edit-post.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                            <a href="?hapus=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus berita ini?')">Hapus</a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>