<?php
include 'koneksi.php';

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

if(strlen($keyword) < 2) {
    echo '<div class="no-result"><i class="fas fa-search"></i><p>Ketik minimal 2 karakter</p></div>';
    exit;
}

$query = "SELECT * FROM berita WHERE judul LIKE '%$keyword%' OR isi LIKE '%$keyword%' ORDER BY id DESC LIMIT 10";
$result = mysqli_query($koneksi, $query);

if(mysqli_num_rows($result) > 0):
    while($row = mysqli_fetch_array($result)):
        $gambarArray = explode(',', $row['gambar']);
        $gambarPertama = trim($gambarArray[0]);
        $tanggal = date('d F Y', strtotime($row['tanggal']));
        $isi_ringkas = strip_tags($row['isi']);
        $isi_ringkas = strlen($isi_ringkas) > 80 ? substr($isi_ringkas, 0, 80) . '...' : $isi_ringkas;
?>
<a href="detail_berita.php?id=<?php echo $row['id']; ?>" class="result-item">
    <img class="thumb" src="<?php echo (!empty($gambarPertama) && file_exists('img/'.$gambarPertama)) ? 'img/'.$gambarPertama : 'https://placehold.co/50x50/1a5f4b/white?text=DPAD'; ?>" alt="Thumb">
    <div class="info">
        <div class="title"><?php echo htmlspecialchars($row['judul']); ?></div>
        <div class="date"><i class="far fa-calendar-alt"></i> <?php echo $tanggal; ?></div>
        <div class="snippet"><?php echo $isi_ringkas; ?></div>
    </div>
</a>
<?php
    endwhile;
else:
?>
<div class="no-result">
    <i class="fas fa-search"></i>
    <p>Tidak ada berita dengan judul atau isi yang mengandung "<strong><?php echo htmlspecialchars($keyword); ?></strong>"</p>
</div>
<?php endif; ?>