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

$urls = [];
$urls[] = ['url' => 'https://tiendamorita.es/', 'priority' => '1.0', 'changefreq' => 'daily'];

$stmt = $pdo->query("SELECT id, fecha_subida FROM productos ORDER BY fecha_subida DESC");
while ($row = $stmt->fetch()) {
    $urls[] = [
        'url' => 'https://tiendamorita.es/?producto=' . $row['id'],
        'priority' => '0.8',
        'changefreq' => 'weekly',
        'lastmod' => date('Y-m-d', strtotime($row['fecha_subida']))
    ];
}

$stmt = $pdo->query("SELECT DISTINCT categoria FROM productos WHERE categoria != ''");
while ($row = $stmt->fetch()) {
    $urls[] = [
        'url' => 'https://tiendamorita.es/?cat=' . $row['categoria'],
        'priority' => '0.6',
        'changefreq' => 'weekly'
    ];
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
foreach ($urls as $item) {
    echo '<url>';
    echo '<loc>' . htmlspecialchars($item['url']) . '</loc>';
    if (isset($item['lastmod'])) echo '<lastmod>' . $item['lastmod'] . '</lastmod>';
    echo '<changefreq>' . ($item['changefreq'] ?? 'monthly') . '</changefreq>';
    echo '<priority>' . ($item['priority'] ?? '0.5') . '</priority>';
    echo '</url>';
}
echo '</urlset>';
