<?php
/**
 * OSILMO dynamic XML sitemap.
 * Served at /sitemap.xml via the root .htaccess rewrite.
 * Automatically lists all live CMS content — nothing to regenerate manually.
 */
require_once __DIR__ . '/functions/helpers.php';

header('Content-Type: application/xml; charset=utf-8');

$urls = [];

/* ---- Static pages (clean URLs) ---- */
$static = [
    ['/',               'daily',   '1.0'],
    ['/about',          'monthly', '0.8'],
    ['/awards',         'monthly', '0.7'],
    ['/facilities',     'monthly', '0.7'],
    ['/faq',            'monthly', '0.7'],
    ['/gallery',        'weekly',  '0.8'],
    ['/media',          'weekly',  '0.8'],
    ['/blog',           'weekly',  '0.9'],
    ['/contact',        'monthly', '0.7'],
    ['/testimonials',   'weekly',  '0.8'],
    ['/support',        'monthly', '0.6'],
    ['/osilmo-village', 'monthly', '0.6'],
    ['/privacy-policy', 'yearly',  '0.3'],
];
foreach ($static as [$path, $freq, $prio]) {
    $urls[] = ['loc' => absoluteUrl($path), 'lastmod' => null, 'changefreq' => $freq, 'priority' => $prio];
}

/* ---- Blog posts (published, not noindex) ---- */
try {
    $rows = getDB()->query(
        "SELECT slug, published_at, updated_at, robots FROM blog_posts
         WHERE is_published = 1 AND slug <> ''
         ORDER BY published_at DESC, id DESC"
    )->fetchAll();
    foreach ($rows as $r) {
        if (stripos((string)($r['robots'] ?? ''), 'noindex') !== false) continue;
        $last = $r['updated_at'] ?: $r['published_at'];
        $urls[] = [
            'loc'        => absoluteUrl('/blog/' . $r['slug']),
            'lastmod'    => $last ? date('Y-m-d', strtotime((string)$last)) : null,
            'changefreq' => 'monthly',
            'priority'   => '0.8',
        ];
    }
} catch (Throwable $e) { /* never break the sitemap */ }

/* ---- Gallery events (active) ---- */
try {
    if (dbTableExists('gallery_events')) {
        $rows = getDB()->query(
            "SELECT id, slug, updated_at, event_date FROM gallery_events
             WHERE is_active = 1 ORDER BY event_date DESC, id DESC"
        )->fetchAll();
        foreach ($rows as $r) {
            $slug = ($r['slug'] ?? '') !== '' ? $r['slug'] : 'gallery-' . (int)$r['id'];
            $last = $r['updated_at'] ?: $r['event_date'];
            $urls[] = [
                'loc'        => absoluteUrl('/gallery/' . $slug),
                'lastmod'    => $last ? date('Y-m-d', strtotime((string)$last)) : null,
                'changefreq' => 'monthly',
                'priority'   => '0.6',
            ];
        }
    }
} catch (Throwable $e) { /* never break the sitemap */ }

/* ---- Media programmes (active) ---- */
try {
    if (dbTableExists('media_programmes')) {
        $rows = getDB()->query(
            "SELECT slug, updated_at FROM media_programmes
             WHERE is_active = 1 AND slug <> '' ORDER BY display_order, id"
        )->fetchAll();
        foreach ($rows as $r) {
            $urls[] = [
                'loc'        => absoluteUrl('/media/' . $r['slug']),
                'lastmod'    => $r['updated_at'] ? date('Y-m-d', strtotime((string)$r['updated_at'])) : null,
                'changefreq' => 'weekly',
                'priority'   => '0.6',
            ];
        }
    }
} catch (Throwable $e) { /* never break the sitemap */ }

/* ---- Output ---- */
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as $u) {
    echo "  <url>\n";
    echo '    <loc>' . h($u['loc']) . "</loc>\n";
    if (!empty($u['lastmod']))    echo '    <lastmod>' . h($u['lastmod']) . "</lastmod>\n";
    if (!empty($u['changefreq'])) echo '    <changefreq>' . h($u['changefreq']) . "</changefreq>\n";
    if (!empty($u['priority']))   echo '    <priority>' . h($u['priority']) . "</priority>\n";
    echo "  </url>\n";
}
echo '</urlset>' . "\n";