<?php
declare(strict_types=1);

/**
 * Dynamic sitemap for the /cartes/ directory.
 * Lists indexable PDF/HTML chart files with per-file last modification dates.
 */

$baseUrl = 'https://randomflightdatabase.fr';
$rootDir = __DIR__;
$cartesDir = $rootDir . DIRECTORY_SEPARATOR . 'cartes';
$allowedExtensions = ['pdf', 'html', 'htm'];

function collectChartFiles(string $directory, array $extensions): array
{
    if (!is_dir($directory)) {
        return [];
    }

    $files = [];
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($iterator as $item) {
        if (!$item->isFile()) {
            continue;
        }

        $extension = strtolower((string) pathinfo($item->getFilename(), PATHINFO_EXTENSION));
        if (!in_array($extension, $extensions, true)) {
            continue;
        }

        $files[] = $item->getPathname();
    }

    sort($files, SORT_NATURAL | SORT_FLAG_CASE);
    return $files;
}

function relativeUrlFromPath(string $absolutePath, string $rootDir): string
{
    $relative = ltrim(str_replace('\\', '/', substr($absolutePath, strlen($rootDir))), '/');
    $segments = array_map('rawurlencode', explode('/', $relative));
    return implode('/', $segments);
}

function priorityForFile(string $path): string
{
    $extension = strtolower((string) pathinfo($path, PATHINFO_EXTENSION));
    return $extension === 'pdf' ? '0.7' : '0.6';
}

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

$files = collectChartFiles($cartesDir, $allowedExtensions);

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

foreach ($files as $filePath) {
    $loc = $baseUrl . '/' . relativeUrlFromPath($filePath, $rootDir);
    $lastmod = gmdate('Y-m-d', (int) filemtime($filePath));
    $priority = priorityForFile($filePath);

    echo "  <url>\n";
    echo '    <loc>' . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
    echo "    <lastmod>{$lastmod}</lastmod>\n";
    echo "    <changefreq>monthly</changefreq>\n";
    echo "    <priority>{$priority}</priority>\n";
    echo "  </url>\n";
}

echo "</urlset>\n";
