<?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;

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

// Ambil slug dari query string
$slug = $_GET['slug'] ?? '';

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

// Cek apakah slug ada
if (empty($slug)) {
    die('Artikel tidak ditemukan');
}

// Folder data berita
$newsDir = __DIR__ . '/data/news/';
$newsFiles = glob($newsDir . '*.json');
$found = false;

foreach ($newsFiles as $file) {
    $news = json_decode(file_get_contents($file), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        die('Error decoding JSON: ' . json_last_error_msg());
    }
    if (isset($news['slug']) && $news['slug'] === $slug) {
        $found = true;
        break;
    }
}

if (!$found) {
    echo 'Artikel tidak ditemukan.';
    exit;
}

// Jika ditemukan, tampilkan artikel
?>
<?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']);
?>

<?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';
    }
}
?>
<!DOCTYPE html4>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo htmlspecialchars($news['judul']); ?> | <?php echo htmlspecialchars($settings['site_name'] ?? 'Nama Website'); ?></title>
<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>
<?php if (!empty($news['image'])): ?>
<?php
$imagePath = str_replace('news/', '', htmlspecialchars($news['image']));
?>
<meta property="og:image" content="<?php echo $imagePath; ?>" />
<meta property="og:image:secure_url" content="<?php echo $imagePath; ?>" />
<?php endif; ?>
<meta property="og:image:type" content="image/jpeg" />
<meta property="og:image:width" content="400" />
<meta property="og:image:height" content="300" />
<meta property="og:image:alt" content="<?php echo htmlspecialchars($news['judul']); ?>" />
<style>
    p a {
    color: #000;
    font-weight: bold;
    border-bottom: 1px solid #ccc; /* Warna abu-abu dan ketebalan border */
    text-decoration: none; /* Hilangkan garis bawah default */
}
p a:hover {
    color: #be1e2e;
    font-weight: bold;
    border-bottom: 1px solid #be1e2e; /* Warna abu-abu dan ketebalan border */
    text-decoration: none; /* Hilangkan garis bawah default */
}
</style>
</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="p-4">
                    <h1 class="text-center ps-3 pe-3"><?php echo $news['judul']; ?></h1>
                    <p class="card-title small text-center mb-4 mt-3"><span class="badge rounded-pill text-bg-warning"><?php echo $news['kategori']; ?></span> | 
                    <?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>";
                        }
                    ?>
                    </p>
                    <?php if (!empty($news['image'])): ?>
                        <?php
                        // Hapus 'news/' dari path gambar jika ada
                        $imagePath = str_replace('news/', '', htmlspecialchars($news['image']));
                        ?>
                            <img class="img-fluid rounded-4 mb-4 w-100" src="<?php echo $imagePath; ?>" alt="<?php echo htmlspecialchars($news['judul']); ?>">
                        <?php endif; ?>

                        <?php if (!empty($news['image_description'])): ?>
                            <p class="ps-3 text-center pe-3 small text-secondary"><?php echo htmlspecialchars($news['image_description']); ?></p>
                        <?php endif; ?>

                    <div class="ps-3 pe-3 pt-4">
                        <?php
                        // Menggunakan nl2br untuk menambahkan <br> berdasarkan newline
                        $konten = nl2br($news['konten']);
                        
                        // Menggunakan preg_replace untuk menghapus <br> yang ada di antara <ul>, <ol>, dan <li>
                        $konten = preg_replace('/(<\/?li>|<\/?ul>|<\/?ol>)\s*<br\s*\/?>/', '$1', $konten);
                        ?>
                        <?php echo $konten; ?>
                    </div>
                    
                <div class="d-flex justify-content-center">                   
                    <p class="ps-3 pe-3 pt-4">
                    <?php foreach ($news['tag'] as $tag): ?>
                        <span class="badge bg-light text-dark mb-2"><i class="fa-solid fa-hashtag text-danger"></i> <?php echo htmlspecialchars($tag); ?></span>
                    <?php endforeach; ?>
                    </p>
                </div>

                <div class="ps-3 pe-3 pt-2 pb-4">
                <!-- ShareThis BEGIN --><div class="sharethis-inline-share-buttons"></div><!-- ShareThis END -->
                </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>
<script type='text/javascript' src='https://platform-api.sharethis.com/js/sharethis.js#property=645f9517192408001992d19d&product=inline-share-buttons' async='async'></script>
</body>
</html>
