<?php
// XML sitemap. Static pages are listed directly; news articles are pulled
// live from the Dali API (same backend news.php/article.php read from) so
// newly published articles appear here without editing this file.
header('Content-Type: application/xml; charset=utf-8');
require __DIR__ . '/incl/dali-api.php';

$base = 'https://www.daligeotech.com';

// W3C datetime (YYYY-MM-DD) from any parseable date string; null on failure.
function sitemap_date($value) {
    if (empty($value)) return null;
    $ts = strtotime($value);
    return $ts ? date('Y-m-d', $ts) : null;
}

$today = date('Y-m-d');

$staticUrls = [
  ['loc' => '/',                          'changefreq' => 'weekly',  'priority' => '1.0', 'lastmod' => $today],
  ['loc' => '/news',                      'changefreq' => 'daily',   'priority' => '0.8', 'lastmod' => $today],
  ['loc' => '/quote',                     'changefreq' => 'monthly', 'priority' => '0.7', 'lastmod' => null],
  ['loc' => '/services/analytics',        'changefreq' => 'monthly', 'priority' => '0.7', 'lastmod' => null],
  ['loc' => '/services/data-marketplace', 'changefreq' => 'monthly', 'priority' => '0.7', 'lastmod' => null],
  ['loc' => '/services/development',      'changefreq' => 'monthly', 'priority' => '0.7', 'lastmod' => null],
  ['loc' => '/services/geospatial',       'changefreq' => 'monthly', 'priority' => '0.7', 'lastmod' => null],
  ['loc' => '/services/it-solutions',     'changefreq' => 'monthly', 'priority' => '0.7', 'lastmod' => null],
  ['loc' => '/services/monitoring',       'changefreq' => 'monthly', 'priority' => '0.7', 'lastmod' => null],
];

$articles = [];
$newsResp = dali_api_get('/news?status=published&page_size=200');
foreach (($newsResp['data'] ?? []) as $n) {
  if (empty($n['slug'])) continue;
  $articles[] = [
    'loc'     => '/article?slug=' . rawurlencode($n['slug']),
    'lastmod' => sitemap_date($n['updated_at'] ?? $n['date'] ?? null),
  ];
}

// Build a full, XML-escaped <loc> value.
function sitemap_loc($base, $path) {
    return htmlspecialchars($base . $path, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($staticUrls as $u): ?>
  <url>
    <loc><?php echo sitemap_loc($base, $u['loc']); ?></loc>
<?php if (!empty($u['lastmod'])): ?>
    <lastmod><?php echo $u['lastmod']; ?></lastmod>
<?php endif; ?>
    <changefreq><?php echo $u['changefreq']; ?></changefreq>
    <priority><?php echo $u['priority']; ?></priority>
  </url>
<?php endforeach; ?>
<?php foreach ($articles as $a): ?>
  <url>
    <loc><?php echo sitemap_loc($base, $a['loc']); ?></loc>
<?php if (!empty($a['lastmod'])): ?>
    <lastmod><?php echo $a['lastmod']; ?></lastmod>
<?php endif; ?>
    <changefreq>monthly</changefreq>
    <priority>0.6</priority>
  </url>
<?php endforeach; ?>
</urlset>