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

$pages = [
    ['loc' => site_url('/index.php'), 'priority' => '1.0', 'changefreq' => 'weekly'],
    ['loc' => site_url('/about.php'), 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => site_url('/services.php'), 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => site_url('/blog.php'), 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => site_url('/careers.php'), 'priority' => '0.7', 'changefreq' => 'weekly'],
    ['loc' => site_url('/privacy.php'), 'priority' => '0.4', 'changefreq' => 'yearly'],
    ['loc' => site_url('/terms.php'), 'priority' => '0.4', 'changefreq' => 'yearly'],
];

try {
    $posts = db()->query("SELECT slug, updated_at FROM blog_posts WHERE status='published' ORDER BY id DESC")->fetchAll();
    foreach ($posts as $p) {
        $pages[] = [
            'loc' => site_url('/blog-post.php?slug=' . urlencode($p['slug'])),
            'priority' => '0.6',
            'changefreq' => 'monthly',
            'lastmod' => date('c', strtotime($p['updated_at'])),
        ];
    }
} catch (Exception $e) {}

try {
    $jobs = db()->query("SELECT id, updated_at FROM jobs WHERE status='open' ORDER BY id DESC")->fetchAll();
    foreach ($jobs as $j) {
        $pages[] = [
            'loc' => site_url('/job.php?id=' . $j['id']),
            'priority' => '0.6',
            'changefreq' => 'monthly',
            'lastmod' => date('c', strtotime($j['updated_at'])),
        ];
    }
} catch (Exception $e) {}

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($pages as $p): ?>
  <url>
    <loc><?= e($p['loc']) ?></loc>
    <priority><?= $p['priority'] ?></priority>
    <changefreq><?= $p['changefreq'] ?></changefreq>
    <?php if (!empty($p['lastmod'])): ?><lastmod><?= $p['lastmod'] ?></lastmod><?php endif; ?>
  </url>
<?php endforeach; ?>
</urlset>
