<?php
ob_start();
require_once 'api/config.php';
ob_end_clean();
header('Content-Type: application/xml; charset=utf-8');

$products   = getProducts();
$storeUrl   = STORE_URL;
$today      = date('Y-m-d');
$categories = array_unique(array_filter(array_column($products, 'categoria')));
sort($categories);

$blogFile  = DATA_DIR . 'blog.json';
$blogPosts = file_exists($blogFile) ? json_decode(file_get_contents($blogFile), true) : [];

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">' . "\n";

// Páginas principales
$pages = [
    ['/', 1.0, 'daily'],
    ['/blog', 0.7, 'weekly'],
    ['/faq', 0.6, 'monthly'],
    ['/politicas', 0.4, 'monthly'],
];
foreach ($pages as [$path, $pri, $freq]) {
    echo "<url><loc>{$storeUrl}{$path}</loc><lastmod>{$today}</lastmod><changefreq>{$freq}</changefreq><priority>{$pri}</priority></url>\n";
}

// Artículos del blog
foreach ($blogPosts as $post) {
    if (empty($post['slug'])) continue;
    $loc = htmlspecialchars($storeUrl . '/blog/' . urlencode($post['slug']));
    $mod = $post['date'] ?? $today;
    echo "<url><loc>{$loc}</loc><lastmod>{$mod}</lastmod><changefreq>monthly</changefreq><priority>0.65</priority></url>\n";
}

// Páginas de categoría
foreach ($categories as $cat) {
    $loc = htmlspecialchars($storeUrl . '/categoria/' . urlencode($cat));
    echo "<url><loc>{$loc}</loc><lastmod>{$today}</lastmod><changefreq>weekly</changefreq><priority>0.9</priority></url>\n";
}

// Productos con imagen
foreach ($products as $p) {
    if (empty($p['images'][0])) continue;
    $id  = urlencode($p['sku'] ?: $p['id']);
    $loc = htmlspecialchars($storeUrl . '/product.php?id=' . $id);
    $img = htmlspecialchars($storeUrl . '/' . ltrim($p['images'][0], '/'));
    $ttl = htmlspecialchars($p['seo_title'] ?: $p['name']);
    $mod = date('Y-m-d', intval(($p['updatedAt'] ?? time() * 1000) / 1000));
    echo "<url>
  <loc>{$loc}</loc>
  <lastmod>{$mod}</lastmod>
  <changefreq>weekly</changefreq>
  <priority>0.8</priority>
  <image:image><image:loc>{$img}</image:loc><image:title>{$ttl}</image:title></image:image>
</url>\n";
}

echo '</urlset>';
?>
