<?php
session_start();
include("./config/config.php");

$actual_link = "https://".$_SERVER['HTTP_HOST'];
$mid_link = $_SERVER['PHP_SELF'];
$mid_link = str_replace("/admin/sitemap.php","",$mid_link);



$domain = "$mid_link"; // Replace with your domain
$rootDir = $_SERVER['DOCUMENT_ROOT'].$domain; // Root directory of your website
 // echo $rootDir ;
// // echo $domain;
 
$sitemapDir = $rootDir; // Directory where sitemaps will be saved

function generateSitemap($domain, $dir, $rootDir) {
    $sitemap = [];
    $dirIterator = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
    $iterator = new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST);

    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() == 'php') {
            $filePath = $file->getPathname();
            $url = str_replace($rootDir, $domain, $filePath);
            $url = str_replace('\\', '/', $url); // Replace backslashes with forward slashes for Windows compatibility
            $sitemap[] = $url;
        }
    }

    return $sitemap;
}

$sitemapUrls = generateSitemap($domain, $rootDir, $rootDir);

$sitemapXml = '<?xml version="1.0" encoding="UTF-8" ?>' . PHP_EOL;
$sitemapXml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

foreach ($sitemapUrls as $url) {
    $sitemapXml .= '  <url>' . PHP_EOL;
    $sitemapXml .= '    <loc>' . htmlspecialchars($actual_link.$url) . '</loc>' . PHP_EOL;
    $sitemapXml .= '  </url>' . PHP_EOL;
}

$sitemapXml .= '</urlset>';

$file = $sitemapDir . '/sitemap.xml';
file_put_contents($file, $sitemapXml);
$_SESSION["redirect-url"] = "complete";
header('Location:./text-file-upload.php');
?>
