<?php
include 'includes/header.php';
include 'fungsi.php';

// Ambil ID berita dari URL
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Query untuk mendapatkan data berita berdasarkan ID
$query = "
SELECT news.*, users.name AS author_name 
FROM news 
JOIN users ON news.author_id = users.id 
WHERE news.id = $id
";
$result = $conn->query($query);

// Jika data tidak ditemukan, tampilkan pesan error
if ($result->num_rows == 0) {
    echo "<div class='container mx-auto px-4 py-16'>";
    echo "<h1 class='text-4xl font-bold mb-8'>Berita Tidak Ditemukan</h1>";
    echo "<p class='text-gray-600'>Berita dengan ID yang diminta tidak tersedia atau telah dihapus.</p>";
    echo "</div>";
    include 'includes/footer.php';
    exit;
}

// Ambil data berita
$item = $result->fetch_assoc();

// Pisahkan gambar dan teks
$konten = $item['content'];
preg_match('/<img[^>]+src="([^"]+)"[^>]*>/i', $konten, $match);
$gambar = $match[1] ?? ''; // Ambil URL gambar
$teks = preg_replace('/<img[^>]*>/', '', $konten); // Hapus tag gambar
?>

<div class="container mx-auto px-4 py-16">
    <div class="max-w-3xl mx-auto bg-white rounded-lg overflow-hidden shadow-md">
        <?php if ($gambar): ?>
            <!--<img src="<?php //echo htmlspecialchars($gambar); 
                            ?>" alt="<?php //echo $item['title']; 
                                    ?>" class="w-full h-64 object-cover">-->
        <?php endif; ?>
        <div class="p-6">
            <h1 class="text-4xl font-bold mb-4"><?php echo htmlspecialchars($item['title']); ?></h1>
            <div class="flex items-center justify-between mb-4">
                <span class="text-sm text-gray-500">Ditulis oleh: <?php echo htmlspecialchars($item['author_name']); ?></span>
                <span class="text-sm text-gray-500"><?php echo htmlspecialchars($item['created_at']); ?></span>
            </div>
            <div class="text-gray-800 leading-relaxed">
                <?php echo $item['content']; //$teks; 
                ?>
            </div>
        </div>
    </div>
</div>

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