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

$base = SITE_URL;

$staticPages = [
    ['url' => '/', 'priority' => '1.0', 'changefreq' => 'hourly'],
    ['url' => '/stores.php', 'priority' => '0.6', 'changefreq' => 'daily'],
    ['url' => '/about.php', 'priority' => '0.3', 'changefreq' => 'monthly'],
    ['url' => '/contact.php', 'priority' => '0.3', 'changefreq' => 'monthly'],
    ['url' => '/help.php', 'priority' => '0.3', 'changefreq' => 'monthly'],
    ['url' => '/business.php', 'priority' => '0.3', 'changefreq' => 'monthly'],
    ['url' => '/advertise.php', 'priority' => '0.3', 'changefreq' => 'monthly'],
    ['url' => '/terms.php', 'priority' => '0.2', 'changefreq' => 'yearly'],
    ['url' => '/privacy.php', 'priority' => '0.2', 'changefreq' => 'yearly'],
];

$categories = db()->query("SELECT slug FROM categories ORDER BY sort_order")->fetchAll();

$ads = db()->query("
    SELECT id, updated_at, created_at FROM ads
    WHERE status='active' AND (expires_at IS NULL OR expires_at > NOW())
    ORDER BY created_at DESC
")->fetchAll();

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach($staticPages as $p): ?>
  <url>
    <loc><?= htmlspecialchars($base . $p['url']) ?></loc>
    <changefreq><?= $p['changefreq'] ?></changefreq>
    <priority><?= $p['priority'] ?></priority>
  </url>
<?php endforeach; ?>
<?php foreach($categories as $cat): ?>
  <url>
    <loc><?= htmlspecialchars($base . '/category.php?slug=' . urlencode($cat['slug'])) ?></loc>
    <changefreq>daily</changefreq>
    <priority>0.7</priority>
  </url>
<?php endforeach; ?>
<?php foreach($ads as $ad): ?>
  <url>
    <loc><?= htmlspecialchars($base . '/ad.php?id=' . $ad['id']) ?></loc>
    <lastmod><?= date('Y-m-d', strtotime($ad['updated_at'] ?? $ad['created_at'])) ?></lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
<?php endforeach; ?>
</urlset>
