<?php
include(__DIR__ . '/db_connect.php');

// Set header for XML
header("Content-Type: application/xml; charset=utf-8");

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">';

// 1️⃣ Add static pages from your `pages` table
$pages_res = $conn->query("SELECT slug, updated_at FROM pages");
while($page = $pages_res->fetch_assoc()){
    $url = "https://".$_SERVER['HTTP_HOST']."/".$page['slug'].".php";
    $lastmod = date("Y-m-d", strtotime($page['updated_at']));
    echo "<url>";
    echo "<loc>$url</loc>";
    echo "<lastmod>$lastmod</lastmod>";
    echo "<changefreq>monthly</changefreq>";
    echo "<priority>0.8</priority>";
    echo "</url>";
}

// 2️⃣ Add menu/programme links from `menus` table
$menus_res = $conn->query("SELECT url, updated_at FROM menus WHERE url != ''");
while($menu = $menus_res->fetch_assoc()){
    $url = (strpos($menu['url'], 'http') === 0) ? $menu['url'] : "https://".$_SERVER['HTTP_HOST'].$menu['url'];
    $lastmod = isset($menu['updated_at']) ? date("Y-m-d", strtotime($menu['updated_at'])) : date("Y-m-d");
    echo "<url>";
    echo "<loc>$url</loc>";
    echo "<lastmod>$lastmod</lastmod>";
    echo "<changefreq>monthly</changefreq>";
    echo "<priority>0.7</priority>";
    echo "</url>";
}

echo '</urlset>';
?>