<?php
header('Content-Type: application/xml; charset=utf-8');
require_once 'includes/config.php';
$domain = rtrim(get_seo('canonical_domain'), '/');
$articles_file = __DIR__ . '/data/articles.json';
$articles = file_exists($articles_file) ? (json_decode(file_get_contents($articles_file), true) ?: []) : [];

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

foreach ($articles as $article) {
  $slug = $article['id'] ?? md5($article['title']);
  $url = $domain ? ($domain . '/article.php?id=' . urlencode($slug)) : ('article.php?id=' . urlencode($slug));
  $date = date('Y-m-d', $article['created_at'] ?? time());
  
  echo '  <url>'."\n";
  echo '    <loc>'.htmlspecialchars($url).'</loc>'."\n";
  echo '    <lastmod>'.$date.'</lastmod>'."\n";
  echo '    <changefreq>never</changefreq>'."\n";
  echo '    <priority>0.6</priority>'."\n";
  if (!empty($article['cover_img'])) {
    echo '    <image:image>'."\n";
    echo '      <image:loc>'.htmlspecialchars($domain . '/' . $article['cover_img']).'</image:loc>'."\n";
    echo '      <image:title>'.htmlspecialchars($article['cover_alt'] ?? $article['title']).'</image:title>'."\n";
    echo '    </image:image>'."\n";
  }
  echo '  </url>'."\n";
}

echo '</urlset>'."\n";
?>
