<?xml version="1.0" encoding="UTF-8"?>
<?php
/**
 * Динамическая XML Sitemap с товарами
 * Автоматически генерируется из config.php
 */

// Устанавливаем правильный content-type
header('Content-Type: application/xml; charset=utf-8');

require_once 'config.php';
require_once 'includes/blog-functions.php';

// Получаем все товары
$products = getProducts();
$categories = getCategories();

// Получаем все статьи блога
$blogPosts = getBlogPosts();

// Базовые страницы сайта
$pages = [
    ['url' => '', 'priority' => '1.0', 'changefreq' => 'daily'],
    ['url' => 'catalog.php', 'priority' => '0.9', 'changefreq' => 'daily'],
    ['url' => 'blog.php', 'priority' => '0.8', 'changefreq' => 'daily'],
    ['url' => 'delivery.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['url' => 'contacts.php', 'priority' => '0.6', 'changefreq' => 'monthly'],
];

// Текущая дата
$lastmod = date('Y-m-d');
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<?php foreach ($pages as $page): ?>
    <url>
        <loc><?php echo url($page['url']); ?></loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq><?php echo $page['changefreq']; ?></changefreq>
        <priority><?php echo $page['priority']; ?></priority>
    </url>
<?php endforeach; ?>

<?php foreach ($categories as $category): ?>
    <url>
        <loc><?php echo url('catalog.php?category=' . $category['slug']); ?></loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
<?php endforeach; ?>

<?php foreach ($products as $product): ?>
    <url>
        <loc><?php echo url('product.php?slug=' . $product['slug']); ?></loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority><?php echo $product['is_hit'] ? '0.9' : '0.7'; ?></priority>
        <image:image>
            <image:loc><?php echo url($product['image']); ?></image:loc>
            <image:title><?php echo h($product['name']); ?></image:title>
            <image:caption><?php echo h($product['description']); ?></image:caption>
        </image:image>
    </url>
<?php endforeach; ?>

<?php foreach ($blogPosts as $post): ?>
    <url>
        <loc><?php echo url('blog-post.php?slug=' . $post['slug']); ?></loc>
        <lastmod><?php echo date('Y-m-d', strtotime($post['updated'] ?? $post['date'])); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.7</priority>
        <?php if (!empty($post['image'])): ?>
        <image:image>
            <image:loc><?php echo url($post['image']); ?></image:loc>
            <image:title><?php echo h($post['title']); ?></image:title>
            <image:caption><?php echo h($post['excerpt']); ?></image:caption>
        </image:image>
        <?php endif; ?>
    </url>
<?php endforeach; ?>
</urlset>
