<?php
/**
 * Tom's Java Jive - Dynamic XML Sitemap
 */
require_once __DIR__ . '/includes/functions.php';

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

$base = 'https://tomsjavajive.com';
$now  = date('Y-m-d');

$products = db()->fetchAll(
    "SELECT product_id, updated_at FROM products WHERE is_active = 1 ORDER BY created_at DESC"
);

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

// Static pages
$staticPages = [
    ['loc' => '/',            'priority' => '1.0', 'changefreq' => 'weekly'],
    ['loc' => '/shop.php',    'priority' => '0.9', 'changefreq' => 'daily'],
    ['loc' => '/about.php',   'priority' => '0.6', 'changefreq' => 'monthly'],
    ['loc' => '/contact.php', 'priority' => '0.5', 'changefreq' => 'monthly'],
    ['loc' => '/login.php',   'priority' => '0.3', 'changefreq' => 'monthly'],
    ['loc' => '/register.php','priority' => '0.3', 'changefreq' => 'monthly'],
];

foreach ($staticPages as $p) {
    $loc = htmlspecialchars($base . $p['loc']);
    echo "  <url><loc>{$loc}</loc><lastmod>{$now}</lastmod><changefreq>{$p['changefreq']}</changefreq><priority>{$p['priority']}</priority></url>\n";
}

// Product pages
foreach ($products as $product) {
    $loc      = htmlspecialchars($base . '/product.php?id=' . $product['product_id']);
    $lastmod  = substr($product['updated_at'] ?? $now, 0, 10);
    echo "  <url><loc>{$loc}</loc><lastmod>{$lastmod}</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></url>\n";
}

echo '</urlset>';
