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

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/turkey.php';

$urls_per_sitemap = 5000;
$hizmet_slugs = array_keys($tum_hizmetler);

$request_uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$filename = basename($request_uri);

if ($filename === 'sitemap.xml') {
    $page = 0;
} elseif (preg_match('/^sitemap-(\d+)\.xml$/', $filename, $matches)) {
    $page = (int)$matches[1];
} else {
    header('HTTP/1.0 404 Not Found');
    exit;
}

function collectAllUrls($site_url, $hizmet_slugs, $turkey_data, $izinli_iller) {
    $urls = [];
    $today = date('Y-m-d');

    $urls[] = [
        'loc'        => $site_url,
        'priority'   => '1.0',
        'changefreq' => 'daily',
        'lastmod'    => $today
    ];

    foreach ($hizmet_slugs as $hizmet_slug) {
        $urls[] = [
            'loc'        => $site_url . $hizmet_slug . '/',
            'priority'   => '1.0',
            'changefreq' => 'hourly',
            'lastmod'    => $today
        ];
    }

    foreach ($hizmet_slugs as $hizmet_slug) {
        foreach ($izinli_iller as $il_slug) {
            if (!isset($turkey_data[$il_slug])) continue;
            $urls[] = [
                'loc'        => $site_url . $hizmet_slug . '/' . $il_slug . '/',
                'priority'   => '0.9',
                'changefreq' => 'hourly',
                'lastmod'    => $today
            ];
        }
    }

    foreach ($hizmet_slugs as $hizmet_slug) {
        foreach ($izinli_iller as $il_slug) {
            if (!isset($turkey_data[$il_slug]['ilceler'])) continue;
            foreach ($turkey_data[$il_slug]['ilceler'] as $ilce_slug => $ilce) {
                $urls[] = [
                    'loc'        => $site_url . $hizmet_slug . '/' . $il_slug . '/' . $ilce_slug . '/',
                    'priority'   => '0.8',
                    'changefreq' => 'hourly',
                    'lastmod'    => $today
                ];
            }
        }
    }

    foreach ($hizmet_slugs as $hizmet_slug) {
        foreach ($izinli_iller as $il_slug) {
            if (!isset($turkey_data[$il_slug]['ilceler'])) continue;
            foreach ($turkey_data[$il_slug]['ilceler'] as $ilce_slug => $ilce) {
                if (!isset($ilce['mahalleler'])) continue;
                foreach ($ilce['mahalleler'] as $mahalle_slug => $mahalle_name) {
                    $urls[] = [
                        'loc'        => $site_url . $hizmet_slug . '/' . $il_slug . '/' . $ilce_slug . '/' . $mahalle_slug . '/',
                        'priority'   => '0.7',
                        'changefreq' => 'weekly',
                        'lastmod'    => $today
                    ];
                }
            }
        }
    }

    return $urls;
}

function generateSitemapIndex($site_url, $total_urls, $urls_per_sitemap) {
    $total_sitemaps = (int)ceil($total_urls / $urls_per_sitemap);
    $lastmod = date('Y-m-d\TH:i:s+00:00');

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

    for ($i = 1; $i <= $total_sitemaps; $i++) {
        echo '  <sitemap>' . "\n";
        echo '    <loc>' . htmlspecialchars($site_url . 'sitemap-' . $i . '.xml') . '</loc>' . "\n";
        echo '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
        echo '  </sitemap>' . "\n";
    }

    echo '</sitemapindex>';
}

function generateSitemapPage($urls, $page, $urls_per_sitemap) {
    $start = ($page - 1) * $urls_per_sitemap;
    $page_urls = array_slice($urls, $start, $urls_per_sitemap);

    if (empty($page_urls)) {
        header('HTTP/1.0 404 Not Found');
        exit;
    }

    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
    echo '        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . "\n";
    echo '        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9' . "\n";
    echo '        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n";

    foreach ($page_urls as $url) {
        echo '  <url>' . "\n";
        echo '    <loc>' . htmlspecialchars($url['loc']) . '</loc>' . "\n";
        echo '    <lastmod>' . $url['lastmod'] . '</lastmod>' . "\n";
        echo '    <changefreq>' . $url['changefreq'] . '</changefreq>' . "\n";
        echo '    <priority>' . $url['priority'] . '</priority>' . "\n";
        echo '  </url>' . "\n";
    }

    echo '</urlset>';
}

$all_urls = collectAllUrls($site_url, $hizmet_slugs, $turkey_data, $izinli_iller);
$total_urls = count($all_urls);

if ($page === 0) {
    generateSitemapIndex($site_url, $total_urls, $urls_per_sitemap);
} else {
    generateSitemapPage($all_urls, $page, $urls_per_sitemap);
}
