<?php
header('Content-Type: application/xml; charset=utf-8');

// Awal dari XML untuk sitemap
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

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

// Folder data berita dan halaman
$newsDir = __DIR__ . '/data/news/';
$pagesDir = __DIR__ . '/data/pages/';

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

// Fungsi untuk menambahkan URL ke sitemap
function addUrlToSitemap($url, $lastmod) {
    echo '<url>';
    echo '<loc>' . htmlspecialchars($url) . '</loc>';
    if ($lastmod) {
        echo '<lastmod>' . date('c', strtotime($lastmod)) . '</lastmod>';
    }
    echo '<changefreq>weekly</changefreq>';
    echo '<priority>0.8</priority>';
    echo '</url>';
}

// Tambahkan halaman home ke sitemap
addUrlToSitemap($base_url . '/', date('Y-m-d'));

// Tambahkan setiap artikel ke sitemap
foreach ($newsFiles as $file) {
    $news = json_decode(file_get_contents($file), true);
    if ($news && isset($news['slug'])) {
        $url = $base_url . '/news/' . $news['slug'];
        $lastmod = $news['tanggal'] ?? null;
        addUrlToSitemap($url, $lastmod);
    }
}

// Tambahkan setiap halaman ke sitemap
foreach ($pageFiles as $file) {
    $page = json_decode(file_get_contents($file), true);
    if ($page && isset($page['slug'])) {
        $url = $base_url . '/page/' . $page['slug'];
        $lastmod = $page['tanggal'] ?? null;
        addUrlToSitemap($url, $lastmod);
    }
}

echo '</urlset>';
?>
