<?php
/**
 * Dynamic sitemap — this .xml file is executed as PHP (see .htaccess).
 *
 * Every .php file in the repo that renders a full page (includes header.php)
 * is listed automatically. Pages with a robots "noindex" meta tag, partials
 * and anything in $exclude are skipped. <lastmod> comes from the file's
 * modification time.
 */

// root.php only defines $base_url; buffer it so no stray output precedes the XML declaration.
ob_start();
include __DIR__ . '/root.php';
ob_end_clean();

$base_url = rtrim($base_url, '/') . '/';

// Paths relative to the site root that should never appear in the sitemap.
$exclude = [
];

// Directories that never contain public pages.
$skip_dirs = ['.git', 'css', 'js', 'img', 'fonts', 'node_modules', 'vendor'];

$root  = __DIR__;
$pages = [];

$iterator = new RecursiveIteratorIterator(
    new RecursiveCallbackFilterIterator(
        new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
        function ($file) use ($skip_dirs) {
            if ($file->isDir()) {
                return !in_array($file->getFilename(), $skip_dirs, true);
            }
            return strtolower($file->getExtension()) === 'php';
        }
    )
);

foreach ($iterator as $file) {
    $relative = str_replace('\\', '/', substr($file->getPathname(), strlen($root) + 1));

    if (in_array($relative, $exclude, true)) {
        continue;
    }

    $contents = file_get_contents($file->getPathname());

    // Only full pages include the site header; partials (header, footer, faq-content, root) don't.
    if (!preg_match('/include(_once)?\s*\(?\s*[\'"][^\'"]*header\.php[\'"]/i', $contents)) {
        continue;
    }

    // Respect pages marked noindex via $robots (read by header.php) or a hard-coded robots meta tag.
    if (preg_match('/\$robots\s*=\s*[\'"][^\'"]*noindex/i', $contents)
        || preg_match('/<meta[^>]+name=["\']robots["\'][^>]*noindex/i', $contents)) {
        continue;
    }

    // index.php -> directory URL, everything else -> extensionless URL (see .htaccess rewrite).
    if (basename($relative) === 'index.php') {
        $path = substr($relative, 0, -strlen('index.php'));
    } else {
        $path = substr($relative, 0, -strlen('.php'));
    }

    $pages[$path] = [
        'loc'      => $base_url . $path,
        'lastmod'  => gmdate('Y-m-d\TH:i:s+00:00', $file->getMTime()),
        'priority' => $path === '' ? '1.00' : '0.80',
    ];
}

// Homepage first, then alphabetical.
uksort($pages, function ($a, $b) {
    if ($a === '') return -1;
    if ($b === '') return 1;
    return strcmp($a, $b);
});

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

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<?php foreach ($pages as $page): ?>
<url>
  <loc><?= htmlspecialchars($page['loc'], ENT_XML1) ?></loc>
  <lastmod><?= $page['lastmod'] ?></lastmod>
  <priority><?= $page['priority'] ?></priority>
</url>
<?php endforeach; ?>
</urlset>
