<?php
header('Content-Type: application/xml; charset=utf-8');

// Ruta a los JSONs de maquinaria
$json_path = dirname(__DIR__) . '/json/maquinaria/';

if (!file_exists($json_path . '_indice.json')) {
    echo '<?xml version="1.0" encoding="UTF-8"?>';
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    echo '<url><loc>https://infoautomotriz.net/manuales-maquinaria-pesada/</loc><lastmod>' . date('Y-m-d') . '</lastmod><priority>0.8</priority></url>';
    echo '</urlset>';
    exit;
}

$indice = json_decode(file_get_contents($json_path . '_indice.json'), true);
$marcas = $indice['marcas'] ?? [];

echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

// Página principal de maquinaria
echo '<url>';
echo '<loc>https://infoautomotriz.net/manuales-maquinaria-pesada/</loc>';
echo '<lastmod>' . date('Y-m-d') . '</lastmod>';
echo '<changefreq>weekly</changefreq>';
echo '<priority>0.9</priority>';
echo '</url>';

foreach ($marcas as $marca) {
    $slug = $marca['slug'];
    $total = $marca['total'];
    $total_paginas = ceil($total / 24);
    
    // Página principal de la marca
    echo '<url>';
    echo '<loc>https://infoautomotriz.net/manuales-maquinaria-pesada/' . $slug . '/</loc>';
    echo '<lastmod>' . date('Y-m-d') . '</lastmod>';
    echo '<changefreq>weekly</changefreq>';
    echo '<priority>0.8</priority>';
    echo '</url>';
    
    // Páginas secundarias (paginación)
    for ($i = 2; $i <= $total_paginas; $i++) {
        echo '<url>';
        echo '<loc>https://infoautomotriz.net/manuales-maquinaria-pesada/' . $slug . '/' . $i . '/</loc>';
        echo '<lastmod>' . date('Y-m-d') . '</lastmod>';
        echo '<changefreq>weekly</changefreq>';
        echo '<priority>0.5</priority>';
        echo '</url>';
    }
}

echo '</urlset>';
?>