<?php
// Создаем файл sitemap.php для генерации sitemap.xml
// Этот файл нужно вызвать один раз или по крону
require_once 'includes/config.php';
require_once 'includes/functions.php';

$urls = [];

$urls[] = ['loc' => SITE_URL, 'priority' => '1.0', 'changefreq' => 'daily'];

$pages = ['about', 'catalog', 'contacts'];
foreach ($pages as $page) {
    $urls[] = ['loc' => SITE_URL . $page . '.php', 'priority' => '0.8', 'changefreq' => 'weekly'];
}

$db = db();
$categories = $db->fetchAll("SELECT slug FROM categories WHERE is_active = 1");
foreach ($categories as $cat) {
    $urls[] = ['loc' => SITE_URL . 'catalog.php?category=' . $cat['slug'], 'priority' => '0.7', 'changefreq' => 'weekly'];
}

$products = $db->fetchAll("SELECT slug FROM products WHERE is_active = 1");
foreach ($products as $product) {
    $urls[] = ['loc' => SITE_URL . 'product.php?slug=' . $product['slug'], 'priority' => '0.6', 'changefreq' => 'monthly'];
}

$news = $db->fetchAll("SELECT slug FROM news WHERE is_active = 1");
foreach ($news as $item) {
    $urls[] = ['loc' => SITE_URL . 'news.php?slug=' . $item['slug'], 'priority' => '0.5', 'changefreq' => 'monthly'];
}

$xml = '<?xml version="1.0" encoding="UTF-8"?>';
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

foreach ($urls as $url) {
    $xml .= '<url>';
    $xml .= '<loc>' . htmlspecialchars($url['loc']) . '</loc>';
    $xml .= '<priority>' . $url['priority'] . '</priority>';
    $xml .= '<changefreq>' . $url['changefreq'] . '</changefreq>';
    $xml .= '</url>';
}

$xml .= '</urlset>';

file_put_contents(__DIR__ . '/sitemap.xml', $xml);
echo "Sitemap generated successfully!";
?>