<?php
/*
 * Dynamic XML sitemap.
 *
 * Executed as PHP via the <Files "sitemap.xml"> handler in .htaccess. Every public
 * .php page in the root and in the listed sub-directories is added
 * automatically; pages marked noindex, utility includes and thank-you pages
 * are skipped. <lastmod> is the file's last modified time.
 */
header('Content-Type: application/xml; charset=utf-8');
header('X-Robots-Tag: noindex');

$site_url = 'https://compliancely.com';

// Directories to scan, relative to the site root ('' = root).
$scan_dirs = ['', 'customer-stories', 'white-papers'];

// Files that are never pages.
$ignore_files = [
    'header.php',
    'footer.php',
    'root.php',
    'page-not-found.php',
];

// Filename patterns to skip (thank-you / confirmation pages).
$ignore_patterns = [
    '/thank-you\.php$/i',
];

function page_has_noindex($file)
{
    $contents = @file_get_contents($file);
    if ($contents === false) {
        return false;
    }

    // Pages set $is_noindex = true before including header.php.
    if (preg_match('/\$is_noindex\s*=\s*true\b/i', $contents)) {
        return true;
    }

    // Pages that hard-code a robots meta tag.
    return preg_match('/<meta\s+[^>]*name=["\']robots["\'][^>]*content=["\'][^"\']*noindex/i', $contents)
        || preg_match('/<meta\s+[^>]*content=["\'][^"\']*noindex[^"\']*["\'][^>]*name=["\']robots["\']/i', $contents);
}

$entries = [];
foreach ($scan_dirs as $dir) {
    $path = $dir === '' ? __DIR__ : __DIR__ . '/' . $dir;
    $files = glob($path . '/*.php');
    if (!is_array($files)) {
        continue;
    }

    foreach ($files as $file) {
        $filename = basename($file);
        if (in_array($filename, $ignore_files, true) || page_has_noindex($file)) {
            continue;
        }
        foreach ($ignore_patterns as $pattern) {
            if (preg_match($pattern, $filename)) {
                continue 2;
            }
        }

        $slug = pathinfo($filename, PATHINFO_FILENAME);
        $prefix = $dir === '' ? '/' : '/' . $dir . '/';
        $loc = $site_url . $prefix . ($slug === 'index' ? '' : $slug);

        if ($loc === $site_url . '/') {
            $priority = '1.00';
        } elseif ($dir === '') {
            $priority = '0.80';
        } else {
            $priority = $slug === 'index' ? '0.70' : '0.60';
        }

        $entries[$loc] = [
            'lastmod'  => gmdate('Y-m-d\TH:i:s\Z', filemtime($file)),
            'priority' => $priority,
        ];
    }
}

ksort($entries, SORT_STRING);

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
foreach ($entries as $loc => $entry) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($loc, ENT_XML1, 'UTF-8') . "</loc>\n";
    echo "    <lastmod>{$entry['lastmod']}</lastmod>\n";
    echo "    <priority>{$entry['priority']}</priority>\n";
    echo "  </url>\n";
}
echo "</urlset>\n";
