<?php
// sitemap.php - dynamic XML sitemap
require_once __DIR__ . "/includes/db.php";

header('Content-Type: application/xml; charset=utf-8');

$base = 'https://www.letworkbedone.com';
$today = date('Y-m-d');

$pages = [
    '/'               => '1.0',
    '/services'       => '0.9',
    '/how-it-works'   => '0.8',
    '/trust'          => '0.7',
    '/about'          => '0.7',
    '/contact'        => '0.6',
    '/become-seller'  => '0.8',
    '/selling'        => '0.7',
    '/buying'         => '0.7',
    '/terms'          => '0.4',
    '/privacy'        => '0.4',
];

// NEVER write ?> inside a string - split it
echo '<?xml version="1.0" encoding="UTF-8"?' . ">\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

foreach ($pages as $url => $prio) {
    echo "  <url>\n";
    echo "    <loc>" . $base . $url . "</loc>\n";
    echo "    <lastmod>$today</lastmod>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>$prio</priority>\n";
    echo "  </url>\n";
}

try {
    $r = $conn->query("SELECT slug, updated_at, created_at FROM services WHERE status='active' ORDER BY id DESC LIMIT 5000");
    if ($r) {
        while ($row = $r->fetch_assoc()) {
            $slug = trim($row['slug']);
            if ($slug === '') continue;
            $mod = !empty($row['updated_at']) ? date('Y-m-d', strtotime($row['updated_at'])) : $today;
            echo "  <url>\n";
            echo "    <loc>" . $base . '/' . htmlspecialchars($slug) . "</loc>\n";
            echo "    <lastmod>$mod</lastmod>\n";
            echo "    <changefreq>weekly</changefreq>\n";
            echo "    <priority>0.8</priority>\n";
            echo "  </url>\n";
        }
    }
} catch (Throwable $e) {}

echo '</urlset>';