<?php
ob_start(); // Mulai output buffering

header("Content-type: text/xml; charset=UTF-8");
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

// Koneksi ke database
$conn = new mysqli("localhost", "onea_oneandnewsdb", "onea_oneandnewsdb", "onea_oneandnewsdb");
if ($conn->connect_error) {
    error_log("Koneksi gagal: " . $conn->connect_error);
    exit; // Hindari output error ke halaman XML
}

// Daftar halaman statis
$static_pages = [
    ["loc" => "https://oneandnews.com/", "changefreq" => "daily", "priority" => "1.0"],
    ["loc" => "https://oneandnews.com/about.php", "changefreq" => "monthly", "priority" => "0.7"],
    ["loc" => "https://oneandnews.com/privacy.php", "changefreq" => "yearly", "priority" => "0.6"],
    ["loc" => "https://oneandnews.com/contact.php", "changefreq" => "yearly", "priority" => "0.6"]
];

foreach ($static_pages as $page) {
    echo "<url>
             <loc>{$page['loc']}</loc>
             <lastmod>" . date("Y-m-d") . "</lastmod>
             <changefreq>{$page['changefreq']}</changefreq>
             <priority>{$page['priority']}</priority>
          </url>" . PHP_EOL;
}

// Ambil data berita dari database
$result = $conn->query("SELECT slug, updated_at FROM berita ORDER BY updated_at DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $url = "https://oneandnews.com/" . htmlspecialchars($row['slug']);
        $lastmod = date("Y-m-d", strtotime($row['updated_at']));
        echo "<url>
                 <loc>{$url}</loc>
                 <lastmod>{$lastmod}</lastmod>
                 <changefreq>daily</changefreq>
                 <priority>0.8</priority>
              </url>" . PHP_EOL;
    }
}

echo '</urlset>';

$conn->close();
ob_end_flush(); // Akhiri output buffering
?>
