<?php
/**
 * /sitemap.xml.php — Dynamic XML sitemap.
 * Reached as /sitemap.xml via .htaccess rewrite.
 *
 * Goals:
 *  - Pretty URLs (Google prefers them, ranks them better)
 *  - Only URLs that actually return 200
 *  - Correct XML headers, BOM-free output
 *  - lastmod from DB where available, else file mtime
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

// Clean output buffer to prevent any whitespace/BOM before XML declaration
while (ob_get_level()) { ob_end_clean(); }

header('Content-Type: application/xml; charset=utf-8');
header('X-Robots-Tag: noindex'); // sitemap itself shouldn't be indexed

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

// Helper to add a URL
function add_url(array &$urls, string $loc, string $priority, string $changefreq, ?string $lastmod = null): void {
    $urls[] = [
        'loc'        => $loc,
        'lastmod'    => $lastmod ?: date('Y-m-d'),
        'changefreq' => $changefreq,
        'priority'   => $priority,
    ];
}

// ---------- Static pages — pretty URLs only ----------
// Each entry: [path, priority, changefreq]
$static = [
    ['/',                 '1.0', 'weekly'],
    ['/properties',       '0.9', 'weekly'],
    ['/calculator',       '0.9', 'monthly'],
    ['/process',          '0.8', 'monthly'],
    ['/qualification',    '0.8', 'monthly'],
    ['/about',            '0.7', 'monthly'],
    ['/team',             '0.6', 'monthly'],
    ['/gallery',          '0.6', 'weekly'],
    ['/news',             '0.7', 'weekly'],
    ['/apply',            '0.9', 'monthly'],
    ['/enquire',          '0.6', 'monthly'],
    ['/contact',          '0.7', 'monthly'],
    ['/privacy',          '0.3', 'yearly'],
    ['/terms',            '0.3', 'yearly'],
];
foreach ($static as [$path, $priority, $freq]) {
    // Verify the underlying PHP file exists before listing
    $phpFile = __DIR__ . ($path === '/' ? '/index.php' : $path . '.php');
    if (file_exists($phpFile)) {
        $lastmod = date('Y-m-d', filemtime($phpFile));
        add_url($urls, $base . $path, $priority, $freq, $lastmod);
    }
}

// ---------- Dynamic pages from DB ----------
try {
    // House types — pretty URL: /homes/slug
    $stmt = db()->query("SELECT slug, updated_at FROM house_types WHERE is_published = 1 ORDER BY sort_order");
    foreach ($stmt->fetchAll() as $h) {
        if (empty($h['slug'])) continue;
        $lastmod = !empty($h['updated_at']) ? date('Y-m-d', strtotime($h['updated_at'])) : date('Y-m-d');
        add_url(
            $urls,
            $base . '/homes/' . $h['slug'],
            '0.85',
            'monthly',
            $lastmod
        );
    }

    // News articles — pretty URL: /news/slug
    $stmt = db()->query("SELECT slug, updated_at, published_at FROM news_articles WHERE is_published = 1 AND slug IS NOT NULL");
    foreach ($stmt->fetchAll() as $a) {
        if (empty($a['slug'])) continue;
        $t = $a['updated_at'] ?: $a['published_at'];
        $lastmod = $t ? date('Y-m-d', strtotime($t)) : date('Y-m-d');
        add_url(
            $urls,
            $base . '/news/' . $a['slug'],
            '0.6',
            'monthly',
            $lastmod
        );
    }
} catch (Throwable $e) {
    // DB might not be ready (install phase) — silently skip dynamic urls
    error_log('[sitemap] ' . $e->getMessage());
}

// ---------- Render XML ----------
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 | ENT_QUOTES, 'UTF-8') . "</loc>\n";
    echo "    <lastmod>" . htmlspecialchars($u['lastmod']) . "</lastmod>\n";
    echo "    <changefreq>" . htmlspecialchars($u['changefreq']) . "</changefreq>\n";
    echo "    <priority>" . htmlspecialchars($u['priority']) . "</priority>\n";
    echo "  </url>\n";
}
echo '</urlset>' . "\n";
