<?php
header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

    <?php
    require_once 'includes/config.php';
    require_once 'includes/fonctions.php';

    // URL de base du site
    $base_url = rtrim($site['base_url'] ?? '/', '/') . '/';

    // Récupération de tous les articles publiés
    $stmt = $pdo->query("SELECT id, slug, created_at, updated_at FROM articles WHERE statut = 'publie' ORDER BY created_at DESC");
    $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Page d'accueil
    ?>
    <url>
        <loc><?= $base_url ?></loc>
        <lastmod><?= date('Y-m-d') ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- Catégories (pour améliorer l'indexation) -->
    <?php
    $catStmt = $pdo->query("SELECT slug FROM categories ORDER BY nom");
    $categories = $catStmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($categories as $cat):
    ?>
    <url>
        <loc><?= $base_url ?>categorie/<?= $cat['slug'] ?></loc>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endforeach; ?>

    <!-- Articles -->
    <?php foreach ($articles as $art): ?>
    <url>
        <loc><?= $base_url . date('Y/m/d', strtotime($art['created_at'])) . '/' . $art['slug'] ?></loc>
        <lastmod><?= date('Y-m-d', strtotime($art['updated_at'] ?? $art['created_at'])) ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.9</priority>
    </url>
    <?php endforeach; ?>

</urlset>