<?php
header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

$catalogFile = __DIR__ . '/wp-content/box/admin/catalog.json';
$items = file_exists($catalogFile) ? json_decode(file_get_contents($catalogFile), true) : [];

// Главная каталога
echo "  <url>\n";
echo "    <loc>https://korobki-darom.ru/catalog/</loc>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>0.9</priority>\n";
echo "  </url>\n";

// Категории
$categories = [
    'samosbornye' => 'Самосборные коробки',
    'chetyrehklapannye' => 'Четырёхклапанные коробки',
    'krestoobraznye' => 'Крестообразные коробки',
    'kryshka-dno' => 'Коробки крышка-дно',
    'podarochnye' => 'Подарочные коробки'
];

foreach ($categories as $slug => $name) {
    echo "  <url>\n";
    echo "    <loc>https://korobki-darom.ru/catalog/{$slug}/</loc>\n";
    echo "    <changefreq>daily</changefreq>\n";
    echo "    <priority>0.8</priority>\n";
    echo "  </url>\n";
}

// Товары
foreach ($items as $item) {
    if (($item['status'] ?? 'draft') !== 'published') continue;
    $article = htmlspecialchars($item['article'] ?? '');
    $boxType = $item['box_type_id'] ?? '0427';
    
    $catSlug = 'samosbornye';
    if ($boxType === '0201') $catSlug = 'chetyrehklapannye';
    elseif ($boxType === '0401a') $catSlug = 'krestoobraznye';
    elseif ($boxType === '0306') $catSlug = 'kryshka-dno';
    elseif ($boxType === 'podarochnye') $catSlug = 'podarochnye';
    
    $date = date('Y-m-d', strtotime($item['date_modified'] ?? $item['created_at'] ?? 'now'));
    
    echo "  <url>\n";
    echo "    <loc>https://korobki-darom.ru/catalog/{$catSlug}/{$article}/</loc>\n";
    echo "    <lastmod>{$date}</lastmod>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>0.7</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>';