<?php
require_once __DIR__ . '/includes/config.php';

header('Content-Type: application/xml; charset=UTF-8');

$base = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'jvpcars.fr');

function url_node($loc, $lastmod = null, $changefreq = null, $priority = null) {
  $loc = htmlspecialchars($loc, ENT_QUOTES, 'UTF-8');
  $out = "  <url>\n";
  $out .= "    <loc>{$loc}</loc>\n";
  if ($lastmod) $out .= "    <lastmod>{$lastmod}</lastmod>\n";
  if ($changefreq) $out .= "    <changefreq>{$changefreq}</changefreq>\n";
  if ($priority) $out .= "    <priority>{$priority}</priority>\n";
  $out .= "  </url>\n";
  return $out;
}

$static = [
  ['/', 'daily', '1.0'],
  ['/catalogue.php', 'daily', '0.9'],
  ['/promos.php', 'weekly', '0.6'],
  ['/comparateur.php', 'weekly', '0.5'],
  ['/reprise.php', 'weekly', '0.7'],
  ['/contact.php', 'monthly', '0.5'],
  ['/faq.php', 'monthly', '0.7'],
  ['/avis.php', 'monthly', '0.6'],
  ['/societe.php', 'monthly', '0.7'],
  ['/mentions-legales.php', 'yearly', '0.2'],
  ['/trouver.php', 'monthly', '0.4'],
];

$data = pcars_json_read(VEHICLES_FILE, ['meta'=>[], 'vehicles'=>[]]);
$vehicles = $data['vehicles'] ?? [];
$lastmod_site = substr(($data['meta']['updated_at'] ?? pcars_now_iso()), 0, 10);

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

foreach ($static as $s) {
  $path = $s[0];
  $freq = $s[1];
  $prio = $s[2];
  echo url_node($base . $path, $lastmod_site, $freq, $prio);
}

foreach ($vehicles as $v) {
  $id = $v['id'] ?? '';
  if (!$id) continue;
  $lm = substr(($v['updated_at'] ?? $lastmod_site), 0, 10);
  $loc = $base . '/vehicule.php?id=' . rawurlencode($id);
  echo url_node($loc, $lm, 'weekly', '0.7');
}

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