<?php
header('Content-Type: application/xml; charset=utf-8');

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$domain = $protocol . '://' . $_SERVER['HTTP_HOST'];
$basePath = __DIR__;

// ============ НАСТРОЙКИ ============
$excludeFiles = [
    'counter.php',
    'track.php',
    'sitemap.php',
    'composer.php',
    'vendor',
    'converted',
    'counter.db',
    '.htaccess',
    'robots.txt'
];

$languages = ['ru', 'en'];

// ============ ФУНКЦИИ ============
function getAllPages($dir, $basePath, $excludeFiles) {
    $pages = [];
    $files = scandir($dir);
    
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        
        // Пропускаем исключенные файлы/папки
        if (in_array($file, $excludeFiles)) continue;
        
        $fullPath = $dir . '/' . $file;
        $relativePath = str_replace($basePath, '', $fullPath);
        $relativePath = str_replace('\\', '/', $relativePath);
        
        if (is_dir($fullPath)) {
            // Рекурсивно сканируем подпапки
            $subPages = getAllPages($fullPath, $basePath, $excludeFiles);
            $pages = array_merge($pages, $subPages);
        } else {
            // Проверяем расширение
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            if (in_array($ext, ['php', 'html', 'htm'])) {
                // Преобразуем в URL
                $url = $relativePath;
                
                // Убираем index.php/index.html
                if (basename($url) === 'index.php') {
                    $url = dirname($url) . '/';
                } elseif (basename($url) === 'index.html') {
                    $url = dirname($url) . '/';
                }
                
                // Убираем расширение .php/.html (кроме главной)
                if ($url !== '/index.php' && $url !== '/index.html') {
                    $url = preg_replace('/\.(php|html?)$/', '', $url);
                }
                
                // Корректируем слеши
                $url = '/' . ltrim($url, '/');
                if ($url !== '/' && substr($url, -1) !== '/') {
                    $url .= '/';
                }
                
                // Получаем дату изменения файла
                $lastmod = date('Y-m-d', filemtime($fullPath));
                
                // Определяем приоритет
                $priority = '0.5';
                $changefreq = 'monthly';
                
                if ($url === '/') {
                    $priority = '1.0';
                    $changefreq = 'daily';
                } elseif (strpos($url, '/converter') !== false || strpos($file, 'converter') !== false) {
                    $priority = '0.9';
                    $changefreq = 'weekly';
                } elseif (strpos($url, '/privacy') !== false || strpos($url, '/terms') !== false || strpos($url, '/about') !== false) {
                    $priority = '0.3';
                    $changefreq = 'monthly';
                }
                
                $pages[] = [
                    'url' => $url,
                    'lastmod' => $lastmod,
                    'priority' => $priority,
                    'changefreq' => $changefreq
                ];
            }
        }
    }
    
    return $pages;
}

// ============ ГЛАВНЫЕ СТРАНИЦЫ (если автосканирование не находит) ============
$manualPages = [
    [
        'url' => '/',
        'lastmod' => date('Y-m-d'),
        'priority' => '1.0',
        'changefreq' => 'daily'
    ],
    [
        'url' => '/privacy/',
        'lastmod' => '2024-01-15',
        'priority' => '0.3',
        'changefreq' => 'monthly'
    ],
    [
        'url' => '/terms/',
        'lastmod' => '2024-01-15',
        'priority' => '0.3',
        'changefreq' => 'monthly'
    ],
    [
        'url' => '/about/',
        'lastmod' => '2024-06-01',
        'priority' => '0.5',
        'changefreq' => 'monthly'
    ],
    [
        'url' => '/contact/',
        'lastmod' => '2024-06-01',
        'priority' => '0.4',
        'changefreq' => 'monthly'
    ]
];

// ============ АВТОМАТИЧЕСКОЕ СКАНИРОВАНИЕ ============
$autoPages = getAllPages($basePath, $basePath, $excludeFiles);

// Убираем дубликаты
$allPages = [];
$seenUrls = [];

foreach ($manualPages as $page) {
    if (!in_array($page['url'], $seenUrls)) {
        $allPages[] = $page;
        $seenUrls[] = $page['url'];
    }
}

foreach ($autoPages as $page) {
    if (!in_array($page['url'], $seenUrls)) {
        $allPages[] = $page;
        $seenUrls[] = $page['url'];
    }
}

// Сортируем по приоритету
usort($allPages, function($a, $b) {
    return $b['priority'] <=> $a['priority'];
});

// ============ ГЕНЕРАЦИЯ XML ============
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
    
    <?php foreach ($allPages as $page): ?>
    <url>
        <loc><?php echo htmlspecialchars($domain . $page['url']); ?></loc>
        
        <?php if ($page['url'] === '/'): ?>
        <!-- Мультиязычные версии для главной -->
        <xhtml:link rel="alternate" hreflang="ru" href="<?php echo $domain; ?>/?lang=ru"/>
        <xhtml:link rel="alternate" hreflang="en" href="<?php echo $domain; ?>/?lang=en"/>
        <xhtml:link rel="alternate" hreflang="x-default" href="<?php echo $domain; ?>/"/>
        <?php endif; ?>
        
        <lastmod><?php echo $page['lastmod']; ?></lastmod>
        <changefreq><?php echo $page['changefreq']; ?></changefreq>
        <priority><?php echo $page['priority']; ?></priority>
    </url>
    <?php endforeach; ?>
    
    <!-- Дополнительные URL для языковых версий -->
    <url>
        <loc><?php echo $domain; ?>/?lang=ru</loc>
        <xhtml:link rel="alternate" hreflang="ru" href="<?php echo $domain; ?>/?lang=ru"/>
        <xhtml:link rel="alternate" hreflang="en" href="<?php echo $domain; ?>/?lang=en"/>
        <xhtml:link rel="alternate" hreflang="x-default" href="<?php echo $domain; ?>/"/>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    
    <url>
        <loc><?php echo $domain; ?>/?lang=en</loc>
        <xhtml:link rel="alternate" hreflang="ru" href="<?php echo $domain; ?>/?lang=ru"/>
        <xhtml:link rel="alternate" hreflang="en" href="<?php echo $domain; ?>/?lang=en"/>
        <xhtml:link rel="alternate" hreflang="x-default" href="<?php echo $domain; ?>/"/>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    
</urlset>