<?php
declare(strict_types=1);

/**
 * Dynamic XML Sitemap
 * Spectrum Credit Limited
 */

header('Content-Type: application/xml; charset=utf-8');

$baseUrl = 'https://www.spectrumcredit.co.ke';
$rootDirectory = __DIR__;

/**
 * Folders that should not appear in search results.
 */
$excludedDirectories = [
    'admin',
    'assets',
    'css',
    'js',
    'images',
    'includes',
    'vendor',
    'uploads',
    'private',
    'backup'
];

/**
 * Files that should not appear in the sitemap.
 */
$excludedFiles = [
    '404.php',
    '403.php',
    '500.php',
    'login.php',
    'logout.php',
    'register.php',
    'forgot-password.php',
    'reset-password.php',
    'config.php',
    'database.php',
    'sitemap.php'
];

/**
 * File extensions to include.
 */
$allowedExtensions = [
    'php',
    'html',
    'htm'
];

/**
 * Pages with custom SEO priority and update frequency.
 */
$pageSettings = [
    '/' => [
        'priority'   => '1.0',
        'changefreq' => 'weekly'
    ],
    '/about-us-1' => [
        'priority'   => '0.8',
        'changefreq' => 'monthly'
    ],
    '/logbook-loan' => [
        'priority'   => '0.9',
        'changefreq' => 'weekly'
    ],
    '/asset-financing' => [
        'priority'   => '0.9',
        'changefreq' => 'weekly'
    ],
    '/study-abroad-loan' => [
        'priority'   => '0.9',
        'changefreq' => 'weekly'
    ],
    '/trade-finance' => [
        'priority'   => '0.9',
        'changefreq' => 'weekly'
    ],
    '/import-financing' => [
        'priority'   => '0.8',
        'changefreq' => 'weekly'
    ],
    '/insurance' => [
        'priority'   => '0.8',
        'changefreq' => 'monthly'
    ],
    '/contact' => [
        'priority'   => '0.7',
        'changefreq' => 'monthly'
    ],
    '/blog' => [
        'priority'   => '0.8',
        'changefreq' => 'weekly'
    ]
];

/**
 * Convert a website file path into a clean public URL.
 */
function createPublicUrl(
    string $filePath,
    string $rootDirectory,
    string $baseUrl
): string {
    $relativePath = str_replace($rootDirectory, '', $filePath);
    $relativePath = str_replace(DIRECTORY_SEPARATOR, '/', $relativePath);

    $relativePath = preg_replace('/\/index\.(php|html|htm)$/i', '/', $relativePath);
    $relativePath = preg_replace('/\.(php|html|htm)$/i', '', $relativePath);

    if ($relativePath === '' || $relativePath === '/index') {
        $relativePath = '/';
    }

    $relativePath = '/' . ltrim($relativePath, '/');

    if ($relativePath !== '/') {
        $relativePath = rtrim($relativePath, '/');
    }

    return rtrim($baseUrl, '/') . $relativePath;
}

/**
 * Determine whether a file or directory should be excluded.
 */
function isExcludedPath(
    string $path,
    array $excludedDirectories,
    array $excludedFiles
): bool {
    $normalizedPath = str_replace('\\', '/', $path);
    $pathParts = explode('/', trim($normalizedPath, '/'));

    foreach ($pathParts as $part) {
        if (in_array(strtolower($part), $excludedDirectories, true)) {
            return true;
        }
    }

    return in_array(strtolower(basename($path)), $excludedFiles, true);
}

/**
 * Format a URL safely for XML.
 */
function xmlEscape(string $value): string
{
    return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

$pages = [];

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator(
        $rootDirectory,
        FilesystemIterator::SKIP_DOTS
    )
);

foreach ($iterator as $file) {
    if (!$file->isFile()) {
        continue;
    }

    $filePath = $file->getPathname();
    $extension = strtolower($file->getExtension());

    if (!in_array($extension, $allowedExtensions, true)) {
        continue;
    }

    if (isExcludedPath($filePath, $excludedDirectories, $excludedFiles)) {
        continue;
    }

    $publicUrl = createPublicUrl(
        $filePath,
        $rootDirectory,
        $baseUrl
    );

    $urlPath = parse_url($publicUrl, PHP_URL_PATH) ?: '/';

    $settings = $pageSettings[$urlPath] ?? [
        'priority'   => '0.6',
        'changefreq' => 'monthly'
    ];

    $pages[$publicUrl] = [
        'loc'        => $publicUrl,
        'lastmod'    => date('Y-m-d', $file->getMTime()),
        'changefreq' => $settings['changefreq'],
        'priority'   => $settings['priority']
    ];
}

/**
 * Add manually routed pages here when the page does not correspond
 * directly to a physical PHP or HTML file.
 */
$manualPages = [
    [
        'path'       => '/about-us-1',
        'lastmod'    => date('Y-m-d'),
        'changefreq' => 'monthly',
        'priority'   => '0.8'
    ],
    [
        'path'       => '/logbook-loan',
        'lastmod'    => date('Y-m-d'),
        'changefreq' => 'weekly',
        'priority'   => '0.9'
    ],
    [
        'path'       => '/asset-financing',
        'lastmod'    => date('Y-m-d'),
        'changefreq' => 'weekly',
        'priority'   => '0.9'
    ],
    [
        'path'       => '/trade-finance',
        'lastmod'    => date('Y-m-d'),
        'changefreq' => 'weekly',
        'priority'   => '0.9'
    ],
    [
        'path'       => '/study-abroad-loan',
        'lastmod'    => date('Y-m-d'),
        'changefreq' => 'weekly',
        'priority'   => '0.9'
    ],
    [
        'path'       => '/import-financing',
        'lastmod'    => date('Y-m-d'),
        'changefreq' => 'weekly',
        'priority'   => '0.8'
    ],
    [
        'path'       => '/contact',
        'lastmod'    => date('Y-m-d'),
        'changefreq' => 'monthly',
        'priority'   => '0.7'
    ]
];

foreach ($manualPages as $manualPage) {
    $url = rtrim($baseUrl, '/') . '/' . ltrim($manualPage['path'], '/');

    $pages[$url] = [
        'loc'        => $url,
        'lastmod'    => $manualPage['lastmod'],
        'changefreq' => $manualPage['changefreq'],
        'priority'   => $manualPage['priority']
    ];
}

ksort($pages);

echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
?>

<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($pages as $page): ?>
    <url>
        <loc><?= xmlEscape($page['loc']); ?></loc>
        <lastmod><?= xmlEscape($page['lastmod']); ?></lastmod>
        <changefreq><?= xmlEscape($page['changefreq']); ?></changefreq>
        <priority><?= xmlEscape($page['priority']); ?></priority>
    </url>
<?php endforeach; ?>
</urlset>