<?php
// Base URL untuk website Anda yang dibuat secara dinamis
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$directory = dirname($_SERVER['SCRIPT_NAME']);
$base_url = $protocol . $host . $directory;

// Ambil pengaturan dari file settings.json
$settings = json_decode(file_get_contents(__DIR__ . '/data/settings.json'), true);
$siteDescription = $settings['site_description'] ?? 'Deskripsi default website';
$siteSlogan = $settings['site_slogan'] ?? 'Slogan default'; // Ambil slogan

$pageDir = __DIR__ . '/data/pages/';
$pageFiles = glob($pageDir . '*.json');

// Ambil query pencarian dari form
$query = $_GET['query'] ?? '';

// Folder data berita
$newsDir = __DIR__ . '/data/news/';

// Ambil semua file berita dengan ekstensi JSON
$newsFiles = glob($newsDir . '*.json');

// Array untuk menyimpan hasil pencarian
$searchResults = [];

// Baca setiap file berita dan lakukan pencarian
foreach ($newsFiles as $file) {
    $jsonData = file_get_contents($file);
    if ($jsonData === false) {
        echo "Gagal membaca file: $file<br>";
        continue;
    }

    $news = json_decode($jsonData, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "Error decoding JSON: " . json_last_error_msg() . "<br>";
        continue;
    }

    // Cek apakah query ada di dalam judul, kategori, atau tag
    $judulMatch = stripos($news['judul'], $query) !== false;
    $kategoriMatch = stripos($news['kategori'], $query) !== false;
    $kontenMatch = stripos($news['konten'], $query) !== false;
    $tagMatch = false;

    // Cek setiap tag jika ada kecocokan
    foreach ($news['tag'] as $tag) {
        if (stripos($tag, $query) !== false) {
            $tagMatch = true;
            break;
        }
    }

    // Jika query cocok dengan judul, kategori, atau tag, tambahkan ke hasil pencarian
    if ($judulMatch || $kategoriMatch || $kontenMatch || $tagMatch) {
        $searchResults[] = $news;
    }
}

?>
<?php
// Fungsi untuk menghitung waktu "time ago"
function timeAgo($datetime) {
    $now = new DateTime(); // Waktu saat ini
    $postTime = new DateTime($datetime); // Waktu dari data berita
    $interval = $now->diff($postTime); // Hitung selisih waktu

    // Tentukan unit waktu (second, minute, hour, day, dll.)
    if ($interval->y > 0) {
        return $interval->y . ' tahun' . ($interval->y > 1 ? '' : '') . ' lalu';
    } elseif ($interval->m > 0) {
        return $interval->m . ' bulan' . ($interval->m > 1 ? '' : '') . ' lalu';
    } elseif ($interval->d > 0) {
        return $interval->d . ' hari' . ($interval->d > 1 ? '' : '') . ' lalu';
    } elseif ($interval->h > 0) {
        return $interval->h . ' jam' . ($interval->h > 1 ? '' : '') . ' lalu';
    } elseif ($interval->i > 0) {
        return $interval->i . ' menit' . ($interval->i > 1 ? '' : '') . ' lalu';
    } else {
        return $interval->s . ' detik' . ($interval->s > 1 ? '' : '') . ' lalu';
    }
}
?>
<?php
// Folder tempat berita disimpan
$newsDir = __DIR__ . '/data/news/';

// Inisialisasi array untuk menyimpan kategori yang ada
$kategoriDenganArtikel = [];

// Baca semua file di folder berita
$newsFiles = glob($newsDir . '*.json');

// Loop melalui setiap file berita
foreach ($newsFiles as $file) {
    // Ambil data berita
    $newsData = json_decode(file_get_contents($file), true);

    // Pastikan data valid dan kategori ada
    if (isset($newsData['kategori']) && !empty($newsData['kategori'])) {
        // Tambahkan kategori ke dalam array jika belum ada
        if (!in_array($newsData['kategori'], $kategoriDenganArtikel)) {
            $kategoriDenganArtikel[] = $newsData['kategori'];
        }
    }
}
?>
<?php
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo htmlspecialchars($settings['site_name'] ?? 'Nama Website'); ?></title>
<meta name="description" content="<?php echo htmlspecialchars($siteDescription); ?>">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/312e1f4072.js" crossorigin="anonymous"></script>
</head>
<body class="bg-light">
<div class="container mt-3 mb-4">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card mt-4 mb-4 border-0 shadow rounded-4 p-3">
                
                <!-- menu -->
<nav class="navbar m-4 navbar-expand-lg shadow rounded-3 mb-3">
  <div class="container-fluid">
    <a class="navbar-brand fw-bold" href="<?php echo $base_url; ?>"><i class="fa-solid fa-rss text-danger"></i>&nbsp;<?php echo htmlspecialchars($settings['site_name'] ?? 'Nama Website'); ?></a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
    <li class="nav-item">
        <a class="nav-link active" aria-current="page" href="<?php echo $base_url; ?>">Home</a>
    </li>
    <?php foreach ($kategoriDenganArtikel as $kategori): ?>
                <li><a class="nav-link active" href="kategori.php?kategori=<?php echo urlencode($kategori); ?>"><?php echo htmlspecialchars($kategori); ?></a></li>
            <?php endforeach; ?>
</ul>

    </div>
  </div>
</nav>
<!--/ menu -->
<div class="ps-4 pe-4">
<form class="d-flex" role="search" action="search.php" method="GET">
    <input type="text" name="query" placeholder="Cari artikel..." class="form-control me-2 rounded-3">
    <button type="submit" class="btn btn-dark rounded-3"><i class="fa-solid fa-magnifying-glass"></i></button>
</form>
</div>
                
<div class="ps-4 pe-4">                
<p class="mt-4">Hasil Pencarian untuk: <span class="fw-bold text-danger"><?php echo htmlspecialchars($query); ?></span></p>

<?php if (!empty($searchResults)): ?>
    <?php foreach ($searchResults as $news): ?>
        <div class="article border-top pt-2">
            <p><a class="text-decoration-none text-dark fw-bold" href="<?php echo htmlspecialchars($news['slug']); ?>"><?php echo htmlspecialchars($news['judul']); ?></a><br>
            <span class="small text-secondary"><span class="badge rounded-pill text-bg-warning"><?php echo htmlspecialchars($news['kategori']); ?></span>&nbsp;
                <?php
// Pastikan file time_ago.php sudah di-include
include 'time_ago.php';

// Asumsikan $news['tanggal'] sudah tersedia dari data berita
if (isset($news['tanggal'])) {
    $timeAgo = timeAgo($news['tanggal']); // Panggil fungsi timeAgo
    ?>
    <!-- Tampilan HTML -->
    <span class="text-secondary">
        <?php echo htmlspecialchars($timeAgo); ?>
    </span>
    <?php
} else {
    echo "<span class='text-secondary'>Date not available</span>";
}
?>
</span>
            </p>
        </div>
    <?php endforeach; ?>
<?php else: ?>
    <p>Tidak ada hasil untuk pencarian '<?php echo htmlspecialchars($query); ?>'</p>
<?php endif; ?>
<div class="pt-4">
<div class="alert alert-warning small" role="alert">
    Artikel ini menggunakan Bahasa Indonesia. Hasil pencarian mungkin tidak bekerja ketika halaman di translate.
</div>
</div>
            </div>
            </div>
            <div class="d-flex justify-content-center">
                <nav aria-label="breadcrumb">
  <ol class="breadcrumb">
                <?php
foreach ($pageFiles as $file) {
    $pageData = json_decode(file_get_contents($file), true);
    $slug = basename($file, '.json');
    echo '<li class="breadcrumb-item"><a class=" text-secondary small text-decoration-none" href="page/' . $slug . '">' . htmlspecialchars($pageData['judul']) . '</a></li>';
}
?>
</ol>
</nav>
            </div>
            <p class="small text-center text-secondary">&copy; 2024 <?php echo htmlspecialchars($settings['site_name'] ?? 'Nama Website'); ?>. All Rights Reserved</p>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

</html>