<?php
/**
 * 宝鸡123 - 动态 Sitemap v5 (php-api版)
 * 放在 php-api 目录内，Nginx 将 /sitemap.php 和 /sitemap.xml rewrite 到此文件
 * 使用共享 config.php + libs/Db.php，确保 DB 连接可靠
 */

header('Content-Type: application/xml; charset=utf-8');
$baseUrl = 'https://baoji123.com';
$now = date('c');

function sitemapEscape($str) {
    return htmlspecialchars($str, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

// 数据库连接
$db = null;
try {
    require_once __DIR__ . '/config.php';
    require_once __DIR__ . '/libs/Db.php';
    $db = \libs\Db::getInstance();
} catch (\Exception $e) {
    // DB 连接失败 → 静默，只输出静态页面
}

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

    <!-- ===== 首页 ===== -->
    <url>
        <loc><?= sitemapEscape($baseUrl) ?>/</loc>
        <lastmod><?= $now ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

<?php if ($db): ?>
    <!-- ===== 一级分类 ===== -->
<?php
    try {
        $cats = $db->fetchAll(
            "SELECT slug, updated_at FROM bj_category
             WHERE parent_id = 0 AND is_show = 1 AND slug != ''
             ORDER BY sort, id"
        );
        foreach ($cats as $cat):
            $lm = !empty($cat['updated_at']) ? date('c', strtotime($cat['updated_at'])) : $now;
?>
    <url>
        <loc><?= sitemapEscape($baseUrl . '/' . $cat['slug']) ?>/</loc>
        <lastmod><?= $lm ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
<?php
        endforeach;
    } catch (\Exception $e) {}
?>
    <!-- ===== 子分类 ===== -->
<?php
    try {
        $subCats = $db->fetchAll(
            "SELECT sc.slug AS sub_slug, pc.slug AS parent_slug, sc.updated_at
             FROM bj_category sc
             LEFT JOIN bj_category pc ON pc.id = sc.parent_id
             WHERE sc.parent_id > 0 AND sc.is_show = 1 AND sc.slug != ''
             ORDER BY sc.sort, sc.id"
        );
        foreach ($subCats as $sc):
            $lm = !empty($sc['updated_at']) ? date('c', strtotime($sc['updated_at'])) : $now;
            $url = $baseUrl . '/' . $sc['parent_slug'] . '/' . $sc['sub_slug'] . '/';
?>
    <url>
        <loc><?= sitemapEscape($url) ?></loc>
        <lastmod><?= $lm ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.7</priority>
    </url>
<?php
        endforeach;
    } catch (\Exception $e) {}
?>
    <!-- ===== 信息详情页 ===== -->
<?php
    try {
        // 先取所有分类 slug 映射
        $catSlugs = $db->fetchAll(
            "SELECT c.name, c.slug AS sub_slug, pc.slug AS parent_slug
             FROM bj_category c
             LEFT JOIN bj_category pc ON pc.id = c.parent_id
             WHERE c.is_show = 1 AND c.slug != ''"
        );
        $catNameToSlug = [];
        foreach ($catSlugs as $cs) {
            $catNameToSlug[$cs['name']] = [
                'sub'    => $cs['sub_slug'],
                'parent' => $cs['parent_slug'] ?? '',
            ];
        }

        $infos = $db->fetchAll(
            "SELECT id, title, category, update_time
             FROM bj_info WHERE status = 1
             ORDER BY update_time DESC LIMIT 5000"
        );

        foreach ($infos as $info):
            $lm = !empty($info['update_time']) ? date('c', strtotime($info['update_time'])) : $now;
            $cat = $catNameToSlug[$info['category']] ?? null;
            if ($cat && $cat['parent']) {
                $url = $baseUrl . '/' . $cat['parent'] . '/' . $cat['sub'] . '/' . (int)$info['id'] . '.html';
            } elseif ($cat) {
                $url = $baseUrl . '/' . $cat['sub'] . '/' . (int)$info['id'] . '.html';
            } else {
                // 无分类映射 → 使用 /detail/{id}.html 通用格式
                $url = $baseUrl . '/detail/' . (int)$info['id'] . '.html';
            }
?>
    <url>
        <loc><?= sitemapEscape($url) ?></loc>
        <lastmod><?= $lm ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.6</priority>
    </url>
<?php
        endforeach;
    } catch (\Exception $e) {}
?>
    <!-- ===== 新闻详情页 ===== -->
<?php
    try {
        $news = $db->fetchAll(
            "SELECT id, publish_time FROM bj_news WHERE status = 1 ORDER BY publish_time DESC LIMIT 500"
        );
        foreach ($news as $n):
            $lm = !empty($n['publish_time']) ? date('c', strtotime($n['publish_time'])) : $now;
?>
    <url>
        <loc><?= sitemapEscape($baseUrl . '/news/' . (int)$n['id'] . '.html') ?></loc>
        <lastmod><?= $lm ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
<?php
        endforeach;
    } catch (\Exception $e) {}
?>
    <!-- ===== 新闻列表 ===== -->
    <url>
        <loc><?= sitemapEscape($baseUrl) ?>/news/</loc>
        <lastmod><?= $now ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.7</priority>
    </url>
<?php endif; ?>

    <!-- ===== 静态页面 ===== -->
    <url><loc><?= sitemapEscape($baseUrl) ?>/about/</loc><lastmod><?= $now ?></lastmod><changefreq>monthly</changefreq><priority>0.5</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/help/</loc><lastmod><?= $now ?></lastmod><changefreq>monthly</changefreq><priority>0.4</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/privacy/</loc><lastmod><?= $now ?></lastmod><changefreq>yearly</changefreq><priority>0.3</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/agreement/</loc><lastmod><?= $now ?></lastmod><changefreq>yearly</changefreq><priority>0.3</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/daren/</loc><lastmod><?= $now ?></lastmod><changefreq>daily</changefreq><priority>0.6</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/skill/</loc><lastmod><?= $now ?></lastmod><changefreq>daily</changefreq><priority>0.6</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/shop/</loc><lastmod><?= $now ?></lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/zhidao/</loc><lastmod><?= $now ?></lastmod><changefreq>daily</changefreq><priority>0.6</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/tools/</loc><lastmod><?= $now ?></lastmod><changefreq>monthly</changefreq><priority>0.4</priority></url>
    <url><loc><?= sitemapEscape($baseUrl) ?>/huangye/</loc><lastmod><?= $now ?></lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url>

</urlset>
