<?php
// File: sitemap.php

// 1. Matikan output buffering sebelumnya dan bersihkan sampah (spasi/error)
// Ini PENTING banget buat ngatasin error "XML Parsing Error"
if (ob_get_length()) ob_end_clean();

// 2. Set Header XML
header("Content-Type: application/xml; charset=utf-8");

require 'includes/db_connect.php';

// Base URL Otomatis
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$host = $_SERVER['HTTP_HOST'];
$path = str_replace('/sitemap.php', '', $_SERVER['PHP_SELF']); 
$baseUrl = "$protocol://$host$path";

$urls = [];

// A. Halaman Statis
$staticPages = [
    ''          => 1.0,
    'produk'    => 0.9,
    'promo'     => 0.9,
    'simulasi'  => 0.8,
    'artikel'   => 0.8,
    'testimoni' => 0.8,
    'kontak'    => 0.8
];

foreach ($staticPages as $page => $priority) {
    // Gunakan htmlspecialchars buat encode URL (ubah & jadi &amp;)
    $loc = $page === '' ? $baseUrl . '/' : $baseUrl . '/index.php?page=' . $page;
    $urls[] = [
        'loc' => $loc,
        'lastmod' => date('Y-m-d'),
        'changefreq' => 'daily',
        'priority' => $priority
    ];
}

// B. Halaman Dinamis (Produk)
try {
    $stmt = $pdo->query("SELECT id FROM produk ORDER BY id DESC");
    while ($row = $stmt->fetch()) {
        $urls[] = [
            'loc' => $baseUrl . '/index.php?page=produk-detail&id=' . $row['id'],
            'lastmod' => date('Y-m-d'),
            'changefreq' => 'weekly',
            'priority' => 0.9
        ];
    }
} catch (Exception $e) {}

// C. Halaman Dinamis (Promo)
try {
    $stmt = $pdo->query("SELECT id FROM promo ORDER BY id DESC");
    while ($row = $stmt->fetch()) {
        $urls[] = [
            'loc' => $baseUrl . '/index.php?page=promo-detail&id=' . $row['id'],
            'lastmod' => date('Y-m-d'),
            'changefreq' => 'weekly',
            'priority' => 0.8
        ];
    }
} catch (Exception $e) {}

// D. Halaman Dinamis (Artikel)
try {
    $stmt = $pdo->query("SELECT id, tanggal_buat FROM artikel ORDER BY id DESC");
    while ($row = $stmt->fetch()) {
        $date = !empty($row['tanggal_buat']) ? date('Y-m-d', strtotime($row['tanggal_buat'])) : date('Y-m-d');
        $urls[] = [
            'loc' => $baseUrl . '/index.php?page=artikel-detail&id=' . $row['id'],
            'lastmod' => $date,
            'changefreq' => 'monthly',
            'priority' => 0.7
        ];
    }
} catch (Exception $e) {}

// OUTPUT XML
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <?php foreach ($urls as $url): ?>
    <url>
        <loc><?= htmlspecialchars($url['loc']) ?></loc>
        <lastmod><?= $url['lastmod'] ?></lastmod>
        <changefreq><?= $url['changefreq'] ?></changefreq>
        <priority><?= $url['priority'] ?></priority>
    </url>
    <?php endforeach; ?>
</urlset>