<?php
require_once __DIR__ . '/includes/functions.php';
header('Content-Type: application/xml; charset=UTF-8');

$base = rtrim(SITE_URL, '/');
$urls = [];

$staticPages = [
    ['/', '1.0', 'daily'],
    ['/properties', '0.9', 'daily'],
    ['/investment-locations', '0.8', 'weekly'],
    ['/new-development', '0.8', 'weekly'],
    ['/buy-and-build', '0.7', 'monthly'],
    ['/services', '0.7', 'monthly'],
    ['/about', '0.6', 'monthly'],
    ['/blog', '0.8', 'daily'],
    ['/news', '0.6', 'weekly'],
    ['/faq', '0.5', 'monthly'],
    ['/procurement', '0.4', 'weekly'],
    ['/contact', '0.6', 'monthly'],
    ['/vip-alerts', '0.6', 'monthly'],
    ['/valuation', '0.6', 'monthly'],
    ['/list-your-property', '0.6', 'monthly'],
];
foreach ($staticPages as [$path, $priority, $freq]) {
    $urls[] = ['loc' => $base . $path, 'priority' => $priority, 'freq' => $freq];
}

foreach (get_districts() as $d) {
    $urls[] = ['loc' => $base . '/district/' . $d['slug'], 'priority' => '0.7', 'freq' => 'weekly'];
}
foreach (get_categories() as $c) {
    $urls[] = ['loc' => $base . '/category/' . $c['slug'], 'priority' => '0.7', 'freq' => 'weekly'];
}

$properties = db()->query('SELECT slug, updated_at FROM properties')->fetchAll();
foreach ($properties as $p) {
    $urls[] = ['loc' => $base . '/properties/' . $p['slug'], 'priority' => '0.8', 'freq' => 'weekly', 'lastmod' => date('c', strtotime($p['updated_at']))];
}

$posts = db()->query("SELECT slug, type, published_at FROM blog_posts")->fetchAll();
foreach ($posts as $p) {
    $prefix = $p['type'] === 'news' ? '/news/' : '/blog/';
    $urls[] = ['loc' => $base . $prefix . $p['slug'], 'priority' => '0.6', 'freq' => 'monthly', 'lastmod' => date('c', strtotime($p['published_at']))];
}

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>' . htmlspecialchars($u['loc'], ENT_XML1) . '</loc>' . "\n";
    if (!empty($u['lastmod'])) echo '    <lastmod>' . $u['lastmod'] . '</lastmod>' . "\n";
    echo '    <changefreq>' . $u['freq'] . '</changefreq>' . "\n";
    echo '    <priority>' . $u['priority'] . '</priority>' . "\n";
    echo '  </url>' . "\n";
}
echo '</urlset>';
