<?php
/**
 * Products sitemap
 * URL: /sitemap-products.xml
 */
require_once __DIR__ . '/includes/config.php';

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

$base = 'https://dorojay.com';

try {
    $products = db()->query(
        "SELECT slug, image, updated_at FROM products
         WHERE status = 'active'
         ORDER BY updated_at DESC
         LIMIT 50000"
    )->fetchAll();
} catch (Exception $e) {
    $products = [];
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n";

foreach ($products as $prod):
    $lastmod = $prod['updated_at'] ? date('Y-m-d', strtotime($prod['updated_at'])) : date('Y-m-d');
    $img_url = product_image($prod['image']);
?>
  <url>
    <loc><?= htmlspecialchars($base . '/product/' . $prod['slug']) ?></loc>
    <lastmod><?= $lastmod ?></lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
    <?php if ($img_url): ?>
    <image:image>
      <image:loc><?= htmlspecialchars($img_url) ?></image:loc>
    </image:image>
    <?php endif; ?>
  </url>
<?php endforeach;

echo '</urlset>';
