<?php
declare(strict_types=1);
date_default_timezone_set('Europe/Paris');
require __DIR__ . '/secure/config.php';
require __DIR__ . '/secure/lib.php';

const SITE_URL = 'https://hosutonews.com';

header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: public, max-age=900');

$items  = load_items();
$stats  = cat_stats($items);
$sstats = source_stats($items);
$latest = $items ? max(array_map(fn($i) => (int) $i['ts'], $items)) : 0;

$urls = [];
$urls[] = [SITE_URL . '/', $latest ?: null];
$urls[] = [SITE_URL . '/tendances.php', $latest ?: null];
foreach (['a-propos.php', 'aide.php', 'journaux.php', 'mentions-legales.php', 'cgu.php', 'politique-confidentialite.php', 'sitemap.php'] as $p) {
    $urls[] = [SITE_URL . '/' . $p, null];
}

// Une page catégorie n'entre dans le sitemap que si elle est indexable (même seuil que categorie.php)
foreach (feed_cats(all_feeds($FEEDS)) as $c) {
    $s = $stats[$c] ?? ['n' => 0, 'ts' => 0];
    if ($s['n'] < CAT_MIN_ARTICLES) continue;
    $urls[] = [SITE_URL . cat_url($c), $s['ts']];
}

// Pages journaux : mêmes règles (seuil SRC_MIN_ARTICLES)
foreach (source_slugs() as $name => $slug) {
    $s = $sstats[$name] ?? ['n' => 0, 'ts' => 0];
    if ($s['n'] < SRC_MIN_ARTICLES) continue;
    $urls[] = [SITE_URL . '/journal.php?s=' . $slug, $s['ts']];
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as [$loc, $ts]) {
    echo '  <url><loc>' . htmlspecialchars($loc, ENT_XML1 | ENT_QUOTES, 'UTF-8') . '</loc>';
    if ($ts) echo '<lastmod>' . date('c', (int) $ts) . '</lastmod>';
    echo "</url>\n";
}
echo "</urlset>\n";
