<?php
include 'koneksi.php';

$keyword = isset($_GET['q']) ? mysqli_real_escape_string($koneksi, $_GET['q']) : '';

$query = "SELECT * FROM berita";
if($keyword != '') {
    $query .= " WHERE judul LIKE '%$keyword%' OR isi LIKE '%$keyword%'";
}
$query .= " ORDER BY id DESC";

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

if(mysqli_num_rows($result) > 0):
    while($berita = mysqli_fetch_array($result)):
        $gambarArray = [];
        if(!empty($berita['gambar'])){
            $gambarArray = explode(',', $berita['gambar']);
            $gambarArray = array_map('trim', $gambarArray);
            $gambarArray = array_filter($gambarArray);
        }
        $gambarPertama = !empty($gambarArray) ? $gambarArray[0] : '';
        $tanggal = date('d F Y', strtotime($berita['tanggal']));
        $isi_ringkas = strip_tags($berita['isi']);
        $isi_ringkas = strlen($isi_ringkas) > 120 ? substr($isi_ringkas, 0, 120) . '...' : $isi_ringkas;
?>
<div class="berita-card" data-aos="fade-up" data-aos-delay="50">
    <div class="image">
        <?php if($gambarPertama && file_exists("img/".$gambarPertama)): ?>
            <img src="img/<?php echo $gambarPertama; ?>" alt="<?php echo htmlspecialchars($berita['judul']); ?>">
        <?php else: ?>
            <img src="https://placehold.co/600x400/e2e8f0/475569?text=DPAD+News" alt="Default">
        <?php endif; ?>
    </div>
    <div class="content">
        <div class="tanggal">
            <i class="far fa-calendar-alt"></i> <?php echo $tanggal; ?>
        </div>
        <div class="judul"><?php echo htmlspecialchars($berita['judul']); ?></div>
        <div class="isi"><?php echo $isi_ringkas; ?></div>
        <a href="detail_berita.php?id=<?php echo $berita['id']; ?>" class="link">
            Baca Selengkapnya <i class="fas fa-arrow-right"></i>
        </a>
    </div>
</div>
<?php
    endwhile;
else:
?>
<div class="empty-state">
    <i class="fas fa-search"></i>
    <h3>Tidak Ditemukan</h3>
    <p>Tidak ada berita dengan judul atau isi yang mengandung "<strong><?php echo htmlspecialchars($keyword); ?></strong>"</p>
</div>
<?php endif; ?>