<?php
define('HWTRAIL_ROOT', dirname(__FILE__));
require_once HWTRAIL_ROOT . '/config.php';

$siteUrl = $site_config['site_url'] ?: 'http://' . $_SERVER['HTTP_HOST'];
$db = DB::getInstance();

function formatDate($timestamp) {
    if (empty($timestamp) || $timestamp <= 0) {
        return date('Y-m-d');
    }
    return date('Y-m-d', $timestamp);
}

function buildSitemapUrl($parts) {
    global $siteUrl;
    $segments = ['/routes'];
    foreach ($parts as $key => $val) {
        $segments[] = $key . '-' . $val;
    }
    return $siteUrl . implode('/', $segments) . '.html';
}

ob_start();
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?php echo $siteUrl; ?>/</loc>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc><?php echo $siteUrl; ?>/routes.html</loc>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>
    <url>
        <loc><?php echo $siteUrl; ?>/circles.html</loc>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>
    <url>
        <loc><?php echo $siteUrl; ?>/demands.html</loc>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc><?php echo $siteUrl; ?>/notices.html</loc>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
    <url>
        <loc><?php echo $siteUrl; ?>/login.html</loc>
        <changefreq>monthly</changefreq>
        <priority>0.3</priority>
    </url>
    <url>
        <loc><?php echo $siteUrl; ?>/register.html</loc>
        <changefreq>monthly</changefreq>
        <priority>0.3</priority>
    </url>
    <?php
    $routes = $db->getAll("SELECT id, update_time, create_time FROM " . $db->table('route') . " WHERE status=1 ORDER BY id DESC LIMIT 5000");
    foreach ($routes as $r):
        $lastmod = $r['update_time'] > 0 ? formatDate($r['update_time']) : formatDate($r['create_time']);
    ?>
    <url>
        <loc><?php echo $siteUrl; ?>/routes/<?php echo $r['id']; ?>.html</loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.6</priority>
    </url>
    <?php endforeach; ?>

    <?php
    $circles = $db->getAll("SELECT id, create_time FROM " . $db->table('circle') . " WHERE status=1 ORDER BY id DESC LIMIT 1000");
    foreach ($circles as $c):
    ?>
    <url>
        <loc><?php echo $siteUrl; ?>/circles/<?php echo $c['id']; ?>.html</loc>
        <lastmod><?php echo formatDate($c['create_time']); ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.6</priority>
    </url>
    <?php endforeach; ?>

    <?php
    $notices = $db->getAll("SELECT id, create_time FROM " . $db->table('notice') . " WHERE is_show=1 ORDER BY id DESC LIMIT 500");
    foreach ($notices as $n):
    ?>
    <url>
        <loc><?php echo $siteUrl; ?>/notices/<?php echo $n['id']; ?>.html</loc>
        <lastmod><?php echo formatDate($n['create_time']); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
    <?php endforeach; ?>

    <?php
    $cityIds = $db->getAll("SELECT DISTINCT city FROM " . $db->table('route') . " WHERE status=1 AND city != ''");
    $cities = [];
    foreach ($cityIds as $row) {
        $cityArr = array_filter(array_map('trim', explode(',', $row['city'])));
        foreach ($cityArr as $cid) {
            if ($cid && !in_array($cid, $cities)) {
                $cities[] = $cid;
            }
        }
    }

    $types = $db->getAll("SELECT id FROM " . $db->table('route_type') . " WHERE status=1");
    $difficulties = [1, 2, 3, 4, 5];

    $combos = [];
    $addedUrls = [];

    foreach ($cities as $city) {
        $combos[] = ['c' => $city];
        foreach ($difficulties as $d) {
            $combos[] = ['c' => $city, 'd' => $d];
            foreach ($types as $t) {
                $combos[] = ['c' => $city, 'd' => $d, 't' => $t['id']];
            }
        }
        foreach ($types as $t) {
            $combos[] = ['c' => $city, 't' => $t['id']];
        }
    }

    foreach ($difficulties as $d) {
        $combos[] = ['d' => $d];
        foreach ($types as $t) {
            $combos[] = ['d' => $d, 't' => $t['id']];
        }
    }

    foreach ($types as $t) {
        $combos[] = ['t' => $t['id']];
    }

    foreach ($combos as $parts) {
        $url = buildSitemapUrl($parts);
        if (!isset($addedUrls[$url])) {
            $addedUrls[$url] = true;
    ?>
    <url>
        <loc><?php echo $url; ?></loc>
        <changefreq>daily</changefreq>
        <priority>0.7</priority>
    </url>
    <?php
        }
    }
    ?>
</urlset>
<?php
$xmlContent = ob_get_clean();

$sitemapFile = HWTRAIL_ROOT . '/sitemap.xml';
    @file_put_contents($sitemapFile, $xmlContent);

header('Content-Type: application/xml; charset=utf-8');
echo $xmlContent;
