<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';

header('Content-Type: application/xml; charset=utf-8');

$proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$base  = $proto . '://' . ($_SERVER['HTTP_HOST'] ?? 'rankifypro.com');

// Static pages with weights
$staticPages = [
    ['/',                       '1.0', 'weekly'],
    ['/check-seo-score',        '1.0', 'weekly'],
    ['/blog',                   '0.9', 'daily'],
    ['/about',                  '0.6', 'monthly'],
    ['/methodology',            '0.7', 'monthly'],
    ['/editorial-guidelines',   '0.5', 'monthly'],
    ['/contact',                '0.5', 'monthly'],
    ['/privacy',                '0.3', 'yearly'],
    ['/terms',                  '0.3', 'yearly'],
    ['/cookies',                '0.3', 'yearly'],
    ['/disclaimer',             '0.3', 'yearly'],
];

// Pull blog posts
$blogs = [];
try {
    $res = $conn->query("SELECT slug, COALESCE(updated_at, created_at) AS lastmod FROM blogs ORDER BY lastmod DESC");
    if ($res) {
        while ($row = $res->fetch_assoc()) { $blogs[] = $row; }
    }
} catch (Throwable $e) { /* DB may be unreachable on first deploy; sitemap still serves static URLs */ }

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($staticPages as [$path, $prio, $freq]): ?>
  <url>
    <loc><?php echo htmlspecialchars($base . $path); ?></loc>
    <lastmod><?php echo date('Y-m-d'); ?></lastmod>
    <changefreq><?php echo $freq; ?></changefreq>
    <priority><?php echo $prio; ?></priority>
  </url>
<?php endforeach; ?>
<?php foreach ($blogs as $b): ?>
  <url>
    <loc><?php echo htmlspecialchars($base . '/' . rawurlencode($b['slug'])); ?></loc>
    <lastmod><?php echo date('Y-m-d', strtotime($b['lastmod'])); ?></lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
  </url>
<?php endforeach; ?>
</urlset>
