<?php
/**
 * 动态站点地图生成器 - tjxmlbx-v2
 * 访问地址: /sitemap.xml
 */
require_once __DIR__ . '/include/db.php';
require_once __DIR__ . '/include/functions.php';
require_once __DIR__ . '/include/seo.php';

$pdo = get_db();

// 缓存sitemap，2小时更新
$cache_file = __DIR__ . '/cache/sitemap_cache.json';
$cache_ttl = 7200;

if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_ttl) {
    $cached = json_decode(file_get_contents($cache_file), true);
    if ($cached) {
        output_sitemap($cached);
        exit;
    }
}

$items = [];

// ========== 主站首页 ==========
$items[] = ['loc'=>'https://www.tjxmlbx.com/','priority'=>'1.0','changefreq'=>'daily','lastmod'=>date('Y-m-d'),'type'=>'home'];

// ========== 固定页面 ==========
foreach (['about', 'contact', 'faq', 'search', 'outlets'] as $slug) {
    $items[] = ['loc'=>'https://www.tjxmlbx.com/' . $slug . '/','priority'=>'0.8','changefreq'=>'monthly','lastmod'=>date('Y-m-d'),'type'=>'page'];
}

// ========== 栏目页 ==========
$stmt = $pdo->query("SELECT scode, filename, name, update_time FROM ay_content_sort WHERE status = 1");
while ($sort = $stmt->fetch()) {
    $fn = $sort['filename'] ?: $sort['scode'];
    $lastmod = !empty($sort['update_time']) ? date('Y-m-d', strtotime($sort['update_time'])) : date('Y-m-d');
    $items[] = ['loc'=>'https://www.tjxmlbx.com/' . $fn . '/','priority'=>'0.8','changefreq'=>'daily','lastmod'=>$lastmod,'type'=>'sort','name'=>$sort['name']];
}

// ========== 文章页 ==========
$stmt2 = $pdo->prepare("SELECT c.id, c.scode, c.filename, c.title, c.date, c.update_time, s.filename as sort_filename FROM ay_content c LEFT JOIN ay_content_sort s ON c.scode = s.scode WHERE c.status = 1 ORDER BY COALESCE(c.update_time, c.date) DESC LIMIT 1000");
$stmt2->execute();
while ($article = $stmt2->fetch()) {
    $fn = $article['filename'] ?: $article['id'];
    $slug = !empty($article['sort_filename']) ? $article['sort_filename'] : $article['scode'];
    $lastmod = !empty($article['update_time']) ? date('Y-m-d', strtotime($article['update_time'])) : date('Y-m-d', strtotime($article['date']));
    $items[] = ['loc'=>'https://www.tjxmlbx.com/' . $slug . '/' . $fn . '.html','priority'=>'0.6','changefreq'=>'monthly','lastmod'=>$lastmod,'type'=>'article','title'=>$article['title']];
}

// 缓存
@mkdir(__DIR__ . '/cache', 0755, true);
file_put_contents($cache_file, json_encode($items));

output_sitemap($items);

function output_sitemap($items) {
    $format = isset($_GET['format']) ? $_GET['format'] : 'xml';

    if ($format === 'json') {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['code'=>200,'total'=>count($items),'urls'=>array_map(function($item){return ['loc'=>$item['loc'],'priority'=>$item['priority'],'changefreq'=>$item['changefreq'],'lastmod'=>$item['lastmod']];},$items)], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
        exit;
    }

    if ($format === 'html') {
        header('Content-Type: text/html; charset=utf-8');
        echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>站点地图 - 北京啄木鸟电器维修</title>';
        echo '<style>body{font-family:system-ui;max-width:1100px;margin:0 auto;padding:40px 20px}h1{color:var(--primary);border-bottom:2px solid #f97316;padding-bottom:10px}.stats{color:#666;margin-bottom:20px}table{width:100%;border-collapse:collapse}th,td{padding:8px 12px;border-bottom:1px solid #eee}th{background:#f8f9fa}a{color:#1E88E5;text-decoration:none}a:hover{text-decoration:underline}</style></head><body>';
        echo '<h1>🗺️ 北京啄木鸟电器维修 - 站点地图</h1>';
        echo '<p class="stats">共 <strong>' . count($items) . '</strong> 个页面</p>';
        echo '<table><thead><tr><th>URL</th><th>优先级</th><th>最后修改</th></tr></thead><tbody>';
        foreach ($items as $item) {
            echo '<tr><td><a href="'.htmlspecialchars($item['loc']).'">'.htmlspecialchars($item['loc']).'</a></td><td>'.$item['priority'].'</td><td>'.$item['lastmod'].'</td></tr>';
        }
        echo '</tbody></table></body></html>';
        exit;
    }

    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    foreach ($items as $item) {
        echo '  <url>' . "\n";
        echo '    <loc>' . htmlspecialchars($item['loc']) . '</loc>' . "\n";
        echo '    <lastmod>' . $item['lastmod'] . '</lastmod>' . "\n";
        echo '    <changefreq>' . $item['changefreq'] . '</changefreq>' . "\n";
        echo '    <priority>' . $item['priority'] . '</priority>' . "\n";
        echo '  </url>' . "\n";
    }
    echo '</urlset>';
}
