<?php
/**
 * 站点地图 - 自动推送用
 */
require_once __DIR__ . '/db.php';

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

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <?php
    // 主域名配置，直接写死或从环境读取
    $mainDomain = 'aifukeji.top';

    // 检查表字段
    $columns = dbSelectAll("SHOW COLUMNS FROM landing_sites");
    $hasUpdatedAt = false;
    $hasCreatedAt = false;
    foreach ($columns as $col) {
        $colName = is_array($col) ? ($col['Field'] ?? $col['field'] ?? '') : (is_object($col) ? ($col->Field ?? '') : '');
        if (strtolower($colName) === 'updated_at') $hasUpdatedAt = true;
        if (strtolower($colName) === 'created_at') $hasCreatedAt = true;
    }

    $timeField = $hasUpdatedAt ? 'updated_at' : ($hasCreatedAt ? 'created_at' : '');

    if ($timeField) {
        $sites = dbSelectAll("SELECT subdomain, {$timeField} as lastmod FROM landing_sites WHERE status = 1 ORDER BY id");
    } else {
        $sites = dbSelectAll("SELECT subdomain FROM landing_sites WHERE status = 1 ORDER BY id");
    }

    $today = date('Y-m-d');

    foreach ($sites as $site):
        // subdomain 可能是 "beijing" 或 "beijing.aifukeji.top"
        $sub = trim($site['subdomain']);
        if (strpos($sub, '.') === false) {
            $sub = $sub . '.' . $mainDomain;
        }

        $lastmod = $today;
        if (!empty($timeField) && !empty($site['lastmod'])) {
            $lm = strtotime($site['lastmod']);
            if ($lm !== false) {
                $lastmod = date('Y-m-d', $lm);
            }
        }
    ?>
    <url>
        <loc>http://<?php echo htmlspecialchars($sub); ?>/</loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endforeach; ?>
</urlset>