<?php
// File: sitemap.php
if (ob_get_length()) ob_end_clean();
header("X-Robots-Tag: noindex");
require_once 'includes/db_connect.php';

$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$baseUrl  = $protocol . '://' . $_SERVER['HTTP_HOST'] . str_replace('/sitemap.php', '', $_SERVER['PHP_SELF']);
$baseUrl  = rtrim($baseUrl, '/');
$type     = $_GET['type'] ?? 'default';

// =====================================================
// IMAGE SITEMAP
// =====================================================
if ($type === 'image') {
    header("Content-Type: application/xml; charset=utf-8");
    echo '<?xml version="1.0" encoding="UTF-8"?>';
    ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
    <?php
    try {
        $stmt = $pdo->query("SELECT id, nama_mobil as name, gambar_utama_url as image FROM produk ORDER BY id DESC");
        while ($row = $stmt->fetch()) {
            if (empty($row['image'])) continue;
            $imgUrl = (strpos($row['image'], 'http') === 0) ? $row['image'] : $baseUrl . '/' . ltrim($row['image'], '/');
            ?><url><loc><?= htmlspecialchars($baseUrl . '/index.php?page=produk-detail&id=' . $row['id']) ?></loc><image:image><image:loc><?= htmlspecialchars($imgUrl) ?></image:loc><image:title><?= htmlspecialchars($row['name']) ?></image:title></image:image></url><?php
        }
    } catch (Exception $e) {}
    try {
        $stmt = $pdo->query("SELECT id, judul as title, gambar_url as image FROM promo ORDER BY id DESC");
        while ($row = $stmt->fetch()) {
            if (empty($row['image'])) continue;
            $imgUrl = (strpos($row['image'], 'http') === 0) ? $row['image'] : $baseUrl . '/' . ltrim($row['image'], '/');
            ?><url><loc><?= htmlspecialchars($baseUrl . '/index.php?page=promo-detail&id=' . $row['id']) ?></loc><image:image><image:loc><?= htmlspecialchars($imgUrl) ?></image:loc><image:title><?= htmlspecialchars($row['title']) ?></image:title></image:image></url><?php
        }
    } catch (Exception $e) {}
    try {
        $stmt = $pdo->query("SELECT id, judul as title, gambar_cover_url as image FROM artikel WHERE status='published' ORDER BY id DESC");
        while ($row = $stmt->fetch()) {
            if (empty($row['image'])) continue;
            $imgUrl = (strpos($row['image'], 'http') === 0) ? $row['image'] : $baseUrl . '/' . ltrim($row['image'], '/');
            ?><url><loc><?= htmlspecialchars($baseUrl . '/index.php?page=artikel-detail&id=' . $row['id']) ?></loc><image:image><image:loc><?= htmlspecialchars($imgUrl) ?></image:loc><image:title><?= htmlspecialchars($row['title']) ?></image:title></image:image></url><?php
        }
    } catch (Exception $e) {}
    ?>
</urlset>
    <?php exit;
}

// =====================================================
// DEFAULT SITEMAP
// =====================================================
header("Content-Type: application/xml; charset=utf-8");
$urls = [];

$staticPages = [
    ''          => ['priority' => 1.0, 'changefreq' => 'daily'],
    'produk'    => ['priority' => 0.9, 'changefreq' => 'daily'],
    'promo'     => ['priority' => 0.9, 'changefreq' => 'daily'],
    'simulasi'  => ['priority' => 0.8, 'changefreq' => 'weekly'],
    'tradein'   => ['priority' => 0.8, 'changefreq' => 'weekly'],
    'artikel'   => ['priority' => 0.8, 'changefreq' => 'daily'],
    'testimoni' => ['priority' => 0.7, 'changefreq' => 'weekly'],
    'kontak'    => ['priority' => 0.7, 'changefreq' => 'monthly'],
];
foreach ($staticPages as $page => $meta) {
    $urls[] = ['loc' => ($page === '') ? $baseUrl . '/' : $baseUrl . '/index.php?page=' . $page, 'lastmod' => date('Y-m-d'), 'changefreq' => $meta['changefreq'], 'priority' => $meta['priority']];
}
try {
    $stmt = $pdo->query("SELECT id, updated_at FROM produk ORDER BY id DESC");
    while ($row = $stmt->fetch()) {
        $lm = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : date('Y-m-d');
        $urls[] = ['loc' => $baseUrl . '/index.php?page=produk-detail&id=' . $row['id'], 'lastmod' => $lm, 'changefreq' => 'weekly', 'priority' => 0.9];
    }
} catch (Exception $e) {}
try {
    $stmt = $pdo->query("SELECT id, updated_at FROM promo ORDER BY id DESC");
    while ($row = $stmt->fetch()) {
        $lm = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : date('Y-m-d');
        $urls[] = ['loc' => $baseUrl . '/index.php?page=promo-detail&id=' . $row['id'], 'lastmod' => $lm, 'changefreq' => 'weekly', 'priority' => 0.8];
    }
} catch (Exception $e) {}
try {
    $stmt = $pdo->query("SELECT id, tanggal_buat FROM artikel WHERE status='published' ORDER BY id DESC");
    while ($row = $stmt->fetch()) {
        $lm = !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' => $lm, 'changefreq' => 'monthly', 'priority' => 0.7];
    }
} catch (Exception $e) {}

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><?= htmlspecialchars($url['lastmod']) ?></lastmod>
        <changefreq><?= htmlspecialchars($url['changefreq']) ?></changefreq>
        <priority><?= htmlspecialchars($url['priority']) ?></priority>
    </url>
<?php endforeach; ?>
</urlset>
