<?php
// ============================================================
//  Flow CMS — Dynamic XML Sitemap
//  Accessible at /sitemap.xml via .htaccess rewrite.
//  Reads published content from the DB and outputs a sitemap.
// ============================================================
define('BASE_PATH', __DIR__);
define('BASE_URL', '');

require_once BASE_PATH . '/includes/functions.php';

$site     = get_site_settings();
$products = get_products();
$posts    = get_published_posts();

$base = rtrim($site['base_url'], '/');
$today = date('Y-m-d');

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

  <!-- Homepage -->
  <url>
    <loc><?= h($base) ?>/</loc>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
    <lastmod><?= h($today) ?></lastmod>
  </url>

  <!-- Blog listing -->
  <url>
    <loc><?= h($base) ?>/blog</loc>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
    <lastmod><?= h($today) ?></lastmod>
  </url>

  <!-- Products -->
<?php foreach ($products as $p): ?>
  <url>
    <loc><?= h($base) ?>/product/<?= h($p['id']) ?></loc>
    <changefreq>monthly</changefreq>
    <priority>0.9</priority>
    <lastmod><?= h($today) ?></lastmod>
  </url>
<?php endforeach; ?>

  <!-- Blog posts -->
<?php foreach ($posts as $post): ?>
  <url>
    <loc><?= h($base) ?>/blog/<?= h($post['slug']) ?></loc>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
<?php if (!empty($post['date_gregorian'])): ?>
    <lastmod><?= h($post['updated_date'] ?: $post['date_gregorian']) ?></lastmod>
<?php else: ?>
    <lastmod><?= h($today) ?></lastmod>
<?php endif; ?>
  </url>
<?php endforeach; ?>

</urlset>
