<?php
header('Content-Type: application/rss+xml; charset=UTF-8');
header('X-Robots-Tag: noindex');

$json = @file_get_contents(__DIR__ . '/articles.json');
if (!$json) { http_response_code(500); exit; }

$articles = json_decode($json, true);
if (!$articles) { http_response_code(500); exit; }

usort($articles, function ($a, $b) { return strcmp($b['date'], $a['date']); });
$articles = array_values(array_filter($articles, function ($a) {
    return !isset($a['status']) || $a['status'] !== 'upcoming';
}));

$baseUrl = 'https://blog.mp-i.pro';
$rssUrl  = $baseUrl . '/rss.php';

$domaineLabels = [
    'sig-cartographie'    => 'SIG & Cartographie',
    'odoo-erp'            => 'Odoo / ERP',
    'conception-methodes' => 'Conception SI',
    'dev-automatisation'  => 'Dev & Automatisation',
];

function rfc822($iso) {
    $dt = new DateTime($iso . 'T00:00:00', new DateTimeZone('Europe/Paris'));
    return $dt->format('D, d M Y H:i:s O');
}

function ent($s) {
    return htmlspecialchars((string) $s, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?><rss version="2.0"
     xmlns:atom="http://www.w3.org/2005/Atom"
     xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Blog MPI — Ingénierie &amp; Numérique</title>
    <link><?= $baseUrl ?>/</link>
    <description>Articles de conseil, géomatique SIG, Odoo ERP, développement et architecture SI. Par Mattieu Pottier, consultant indépendant.</description>
    <language>fr-FR</language>
    <copyright>© <?= date('Y') ?> Mattieu Pottier — MPI Ingénierie &amp; Numérique</copyright>
    <managingEditor>contact@mp-i.pro (Mattieu Pottier)</managingEditor>
    <lastBuildDate><?= rfc822(date('Y-m-d')) ?></lastBuildDate>
    <ttl>1440</ttl>
    <atom:link href="<?= ent($rssUrl) ?>" rel="self" type="application/rss+xml" />
    <image>
      <url>https://www.mp-i.pro/assets/img/favicon/favicon-32x32.png</url>
      <title>Blog MPI</title>
      <link><?= $baseUrl ?>/</link>
      <width>32</width>
      <height>32</height>
    </image>
<?php foreach ($articles as $a):
    $url      = $baseUrl . '/articles/' . $a['slug'] . '/';
    $category = $domaineLabels[$a['domaine']] ?? $a['domaine'];
    $cover    = isset($a['image'])
        ? $baseUrl . preg_replace('/\.(avif|webp)$/', '.png', $a['image'])
        : null;
?>
    <item>
      <title><?= ent($a['titre']) ?></title>
      <link><?= ent($url) ?></link>
      <description><?= ent($a['description']) ?></description>
      <pubDate><?= rfc822($a['date']) ?></pubDate>
      <guid isPermaLink="true"><?= ent($url) ?></guid>
      <dc:creator>Mattieu Pottier</dc:creator>
      <category><?= ent($category) ?></category>
<?php if ($cover): ?>
      <enclosure url="<?= ent($cover) ?>" type="image/png" length="0" />
<?php endif; ?>
    </item>
<?php endforeach; ?>
  </channel>
</rss>
