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

$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

$products = db()->fetchAll("SELECT id, updated_at FROM products ORDER BY id");
$categories = db()->fetchAll("SELECT slug FROM categories ORDER BY name");
?>
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc><?= htmlspecialchars($baseUrl) ?></loc>
    <priority>1.0</priority>
    <changefreq>weekly</changefreq>
  </url>
  <url>
    <loc><?= htmlspecialchars($baseUrl) ?>shop.php</loc>
    <priority>0.9</priority>
    <changefreq>daily</changefreq>
  </url>
  <url>
    <loc><?= htmlspecialchars($baseUrl) ?>about.php</loc>
    <priority>0.7</priority>
    <changefreq>monthly</changefreq>
  </url>
  <url>
    <loc><?= htmlspecialchars($baseUrl) ?>contact.php</loc>
    <priority>0.6</priority>
    <changefreq>monthly</changefreq>
  </url>
  <?php foreach ($categories as $cat): ?>
  <url>
    <loc><?= htmlspecialchars($baseUrl) ?>shop.php?category=<?= urlencode($cat['slug']) ?></loc>
    <priority>0.8</priority>
    <changefreq>weekly</changefreq>
  </url>
  <?php endforeach; ?>
  <?php foreach ($products as $p): ?>
  <url>
    <loc><?= htmlspecialchars($baseUrl) ?>product.php?id=<?= $p['id'] ?></loc>
    <priority>0.8</priority>
    <changefreq>monthly</changefreq>
    <lastmod><?= $p['updated_at'] ? date('c', strtotime($p['updated_at'])) : date('c') ?></lastmod>
  </url>
  <?php endforeach; ?>
</urlset>
