<?php
require "../fungsi.php";

// Query untuk mengambil data dari tabel news
$query = "SELECT news.id, news.title, news.content, news.created_at, users.name AS author_name, news.status 
          FROM news 
          LEFT JOIN users ON news.author_id = users.id
          ORDER BY news.created_at DESC";

$result = $conn->query($query);

if ($result && $result->num_rows > 0): ?>

    <div class="container-fluid">
        <h1 class="h3 mb-4 text-gray-800">Daftar Berita</h1>

        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Judul</th>
                    <th>Penulis</th>
                    <th>Tanggal Dibuat</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($row['id']); ?></td>
                        <td><?php echo htmlspecialchars($row['title']); ?></td>
                        <td><?php echo htmlspecialchars($row['author_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                        <td><?php echo htmlspecialchars($row['status']); ?></td>
                        <td>
                            <a href="?page=edit_news&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                            <a href="?page=delete_news&id=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Anda yakin ingin menghapus berita ini?');">Hapus</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>

<?php else: ?>
    <div class="alert alert-info">Tidak ada berita yang tersedia.</div>
<?php endif; ?>