<?php
header('Content-Type: application/xml; charset=utf-8');

function page_has_noindex($file) {
    $contents = @file_get_contents($file);
    if ($contents === false) {
        return false;
    }

    return preg_match('/<meta\s+[^>]*name=["\']robots["\'][^>]*content=["\'][^"\']*noindex[^"\']*["\'][^>]*>/i', $contents)
        || preg_match('/<meta\s+[^>]*content=["\'][^"\']*noindex[^"\']*["\'][^>]*name=["\']robots["\'][^>]*>/i', $contents);
}

$site_url = 'https://www.ezextension.com';
$ignore_files = [
    'header.php',
    'footer.php',
    'root.php',
    'sitemap.php',
    'robots.txt',
    'BingSiteAuth.xml',
    'llms.txt',
    'index.php',
    'page-not-found.php',
];

$urls = [];
$files = glob(__DIR__ . '/*.php');
if (is_array($files)) {
    sort($files, SORT_STRING);
    foreach ($files as $file) {
        $filename = basename($file);
        if (in_array($filename, $ignore_files, true) || page_has_noindex($file)) {
            continue;
        }

        $slug = pathinfo($filename, PATHINFO_FILENAME);
        $loc = strtolower($slug) === 'index'
            ? $site_url . '/'
            : $site_url . '/' . $slug;

        $urls[] = $loc;
    }
}

$urls = array_values(array_unique($urls));
sort($urls, SORT_STRING);

$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xml .= "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

foreach ($urls as $loc) {
    $priority = rtrim($loc, '/') === $site_url ? '1.00' : '0.80';
    $lastmod = gmdate('Y-m-d\TH:i:s\Z');
    $xml .= "  <url>\n";
    $xml .= "    <loc>" . htmlspecialchars($loc, ENT_QUOTES, 'UTF-8') . "</loc>\n";
    $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
    $xml .= "    <priority>{$priority}</priority>\n";
    $xml .= "  </url>\n";
}

$xml .= "</urlset>\n";

echo $xml;

