<?php
require_once __DIR__ . '/common.php';

$pdo = db();



$siteTitle       = get_setting('site.title', '六柱博客');
$siteSubtitle    = get_setting('site.subtitle', '六柱个人博客');
$siteDescription = get_setting('site.description', '六柱个人博客');


$articleId   = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$article     = null;
$articleTags = [];
$prevArticle = null;
$nextArticle = null;


$comments         = [];
$commentsTree     = ['byId' => [], 'children' => [], 'roots' => []];
$replyToId        = isset($_GET['reply_to']) ? (int)($_GET['reply_to'] ?? 0) : 0;
$replyToComment   = null;
$commentPage      = isset($_GET['cpage']) ? max(1, (int)$_GET['cpage']) : 1;
$commentPageSize  = 20; 
$commentPageTotal = 1;


$likeStatus = null;
if (isset($_GET['like'])) {
    $flag = (string)$_GET['like'];
    if ($flag === 'ok') {
        $likeStatus = '感谢你的点赞！';
    } elseif ($flag === 'exists') {
        $likeStatus = '你已经点过赞了，每个 IP 只能点一次。';
    }
}


if ($articleId > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT a.*, c.name AS category_name
            FROM articles a
            LEFT JOIN categories c ON c.id = a.category_id
            WHERE a.id = :id AND a.status = 'published'
            LIMIT 1
        ");
        $stmt->execute([':id' => $articleId]);
        $article = $stmt->fetch();

        if ($article) {
            
            $stmt = $pdo->prepare("
                SELECT t.id, t.name
                FROM article_tag at
                INNER JOIN tags t ON t.id = at.tag_id
                WHERE at.article_id = :id
                ORDER BY t.id ASC
            ");
            $stmt->execute([':id' => $articleId]);
            $articleTags = $stmt->fetchAll() ?: [];

            
            if (!empty($article['published_at'])) {
                $publishedAt = (int)$article['published_at'];

                $stmt = $pdo->prepare("
                    SELECT id, title
                    FROM articles
                    WHERE status = 'published'
                      AND published_at < :t
                    ORDER BY published_at DESC, id DESC
                    LIMIT 1
                ");
                $stmt->execute([':t' => $publishedAt]);
                $prevArticle = $stmt->fetch();

                $stmt = $pdo->prepare("
                    SELECT id, title
                    FROM articles
                    WHERE status = 'published'
                      AND published_at > :t
                    ORDER BY published_at ASC, id ASC
                    LIMIT 1
                ");
                $stmt->execute([':t' => $publishedAt]);
                $nextArticle = $stmt->fetch();
            }
        }
    } catch (Throwable $e) {
        $article = null;
    }
}



if (!$article) {
    http_response_code(404);
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>文章不存在</title></head><body style="margin:0;padding:0;"><p>你访问的文章不存在或尚未发布。</p><p><a href="index.php">返回首页</a></p></body></html>';
    exit;
}


try {
    $stmt = $pdo->prepare("
        SELECT c.*, u.nickname
        FROM comments c
        LEFT JOIN users u ON u.id = c.user_id
        WHERE c.article_id = :aid AND c.status = 'approved'
        ORDER BY c.created_at ASC, c.id ASC
    ");
    $stmt->execute([':aid' => $articleId]);
    $comments = $stmt->fetchAll() ?: [];

    $byId     = [];
    $children = [];
    foreach ($comments as $c) {
        $cid            = (int)$c['id'];
        $byId[$cid]     = $c;
        $children[$cid] = [];
    }
    $roots = [];
    foreach ($comments as $c) {
        $cid = (int)$c['id'];
        $pid = $c['parent_id'] !== null ? (int)$c['parent_id'] : 0;
        if ($pid > 0 && isset($byId[$pid])) {
            $children[$pid][] = $cid;
        } else {
            $roots[] = $cid;
        }
    }
    $totalRoots = count($roots);
    if ($totalRoots > 0) {
        $commentPageTotal = (int)ceil($totalRoots / $commentPageSize);
        if ($commentPage > $commentPageTotal) {
            $commentPage = $commentPageTotal;
        }
        $offset  = ($commentPage - 1) * $commentPageSize;
        $pageRoots = array_slice($roots, $offset, $commentPageSize);
    } else {
        $pageRoots = [];
        $commentPage      = 1;
        $commentPageTotal = 1;
    }

    $commentsTree = ['byId' => $byId, 'children' => $children, 'roots' => $pageRoots];

    if ($replyToId > 0 && isset($byId[$replyToId])) {
        $replyToComment = $byId[$replyToId];
    }
} catch (Throwable $e) {
    $commentsTree   = ['byId' => [], 'children' => [], 'roots' => []];
    $replyToComment = null;
}


track_visit($articleId);
cleanup_visit_log();


$scheme       = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host         = $_SERVER['HTTP_HOST'] ?? 'localhost';
$canonicalUrl = $scheme . '://' . $host . '/post.php?id=' . $articleId;


$metaDescription = '';
if (!empty($article['summary'])) {
    $metaDescription = $article['summary'];
} else {
    $plain = strip_tags($article['content_html']);
    $plain = preg_replace('/\s+/u', ' ', $plain);
    $metaDescription = mb_substr($plain, 0, 120, 'UTF-8');
}


$currentUser     = current_user();
$memberActivity  = load_member_activity($currentUser);
$myArticles      = $memberActivity['myArticles'];
$myReplies       = $memberActivity['myReplies'];


$siteFooterBrand        = get_setting('site.footer_brand', '六柱php轻型博客源码');
$siteFooterOfficialUrl  = get_setting('site.footer_official_url', 'https://www.6zjz.com');
$siteFooterOfficialText = get_setting('site.footer_official_text', 'www.6zjz.com');

require_once __DIR__ . '/includes/sidebar-data.php';
extract(load_common_sidebar_data($pdo), EXTR_OVERWRITE);


$unlockedArticle = article_is_unlocked_for_current_visitor($pdo, (int)$articleId);

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title><?php echo h($article['title']); ?> - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="<?php echo h($metaDescription ?: $siteDescription); ?>">
    <link rel="canonical" href="<?php echo h($canonicalUrl); ?>">
    <style>
        :root {
            --bg: #f5f5f7;
            --bg-elevated: #ffffff;
            --bg-header: #ffffff;
            --border-subtle: #e5e7eb;
            --text-main: #111827;
            --text-muted: #6b7280;
            --accent: #2563eb;
            --accent-soft: #dbeafe;
            --accent-strong: #1d4ed8;
        }
        body[data-theme="dark"] {
            --bg: #0f172a;
            --bg-elevated: #111827;
            --bg-header: #020617;
            --border-subtle: #1f2937;
            --text-main: #e5e7eb;
            --text-muted: #9ca3af;
            --accent: #3b82f6;
            --accent-soft: #1d4ed8;
            --accent-strong: #60a5fa;
        }
        html, body { height:100%;  margin:0; padding:0; }
        body { margin:0; padding:0; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif; background:var(--bg); color:var(--text-main); }
        a { color:var(--accent); text-decoration:none; }
        a:hover { text-decoration:underline; }

        .header { background:var(--bg-header); border-bottom:1px solid var(--border-subtle);  margin:0;  padding:0;  margin-top:-18px; padding-top:18px; }
        .header-inner { max-width:1200px; margin:0 auto; padding:0 16px 6px; display:grid; grid-template-columns:220px minmax(0,1fr) 260px; gap:16px; align-items:flex-start; }
        .logo { font-size:20px; font-weight:700; white-space:nowrap; }
        .subtitle { font-size:12px; color:var(--text-muted); }
                .search-box { width:100%; min-width:0; display:flex; align-items:center; gap:0; }
        .search-input { flex:1; min-width:0; position:relative; }
        .search-input input { width:100%; padding:6px 10px; border-radius:999px; border:1px solid var(--border-subtle); background:var(--bg); color:var(--text-main); font-size:14px; }
                .search-box form, form.search-box { width:100%; display:flex; align-items:center; height:40px; background:var(--bg); border:1px solid var(--border-subtle); border-radius:999px; overflow:hidden; }
.search-box form:focus-within, form.search-box:focus-within { border-color:var(--accent); box-shadow:0 0 0 2px rgba(37,99,235,0.08); }
.search-box input[type="text"], form.search-box input[type="text"] { flex:1; min-width:0; height:100%; padding:0 12px; border:0; background:transparent; color:var(--text-main); font-size:14px; }
.search-box input[type="text"]::placeholder, form.search-box input[type="text"]::placeholder { color:var(--text-muted); }
.search-btn { min-width:72px; height:100%; white-space:nowrap; padding:0 16px; border:0; border-left:1px solid var(--border-subtle); background:linear-gradient(135deg, var(--accent), var(--accent-strong)); color:#fff; font-size:13px; font-weight:600; display:inline-flex; align-items:center; justify-content:center; cursor:pointer; transition:filter .12s, transform .12s; }
.search-btn:hover { filter:brightness(1.06); transform:none; }
        .header-actions { display:flex; align-items:flex-start; justify-content:flex-end; gap:8px; flex-wrap:wrap; }
        .btn, .btn-ghost { font-size:13px; padding:6px 10px; border-radius:999px; border:1px solid var(--accent); cursor:pointer; }
        .btn { background:var(--accent-soft); color:var(--accent-strong); }
        .btn-ghost { background:transparent; color:var(--text-muted); border-color:transparent; }

        .page { max-width:1200px; margin:0 auto; padding:16px; }
        .layout { display:grid; grid-template-columns:220px minmax(0,1fr) 260px; gap:16px; }
        .column { display:flex; flex-direction:column; gap:12px; }

        .card { background:var(--bg-elevated); border-radius:6px; border:1px solid var(--border-subtle); padding:10px 12px; }
        .card-title { font-size:14px; font-weight:600; margin-bottom:6px; position:relative; padding-left:6px; }
        .card-title-sub { font-size:12px; color:var(--text-muted); margin-left:4px; }

        ul { list-style:none; margin:0; padding:0; }
        li { font-size:12px; padding:2px 0; }
        .small-text { font-size:11px; color:var(--text-muted); }

        .category-name a { color:var(--text-main); font-weight:500; }
        .category-pill { display:flex; align-items:flex-start; justify-content:flex-start; padding:4px 8px; border-radius:999px; background:rgba(37,99,235,0.05); margin-bottom:4px; transition:background 0.15s, transform 0.15s; }
        .category-pill:hover { background:rgba(37,99,235,0.12); transform:translateX(2px); }
        .category-count { font-size:11px; color:var(--text-muted); }
        .category-count-num { display:inline-block; min-width:18px; height:16px; line-height:16px; padding:0 5px; border-radius:999px; text-align:center; font-size:10px; font-weight:600; font-variant-numeric:tabular-nums; background:rgba(37,99,235,0.12); color:var(--accent-strong); }

        .contact-list li { display:flex; align-items:flex-start; margin-bottom:4px; }
        .contact-icon { width:20px; height:20px; border-radius:999px; background:rgba(37,99,235,0.12); color:var(--accent-strong); display:flex; align-items:flex-start; justify-content:center; font-size:12px; margin-right:6px; }
        .contact-text { flex:1; }
        .friend-links { display:grid; grid-template-columns:repeat(2, minmax(0,1fr)); gap:6px 8px; }
        .friend-links li { padding:0; }
        .friend-links + .small-text { text-align:left; }
        .friend-links li a {
            text-align:left; display:inline-flex; align-items:center; width:auto; max-width:100%; padding:4px 8px; border-radius:999px; background:rgba(37,99,235,0.04); transition:background 0.15s, transform 0.15s; }
        .friend-links li a:hover { background:rgba(37,99,235,0.12); transform:translateX(2px); }
        .new-sites-list li a { display:inline-block; padding:3px 0; }

        .meta-line { font-size:12px; color:var(--text-muted); margin-bottom:6px; }
        .article-body { font-size:14px; line-height:1.7; white-space:normal; word-break:break-word; overflow-wrap:anywhere; }
        .article-body img,
        .article-body video {
            max-width:100% !important;
            height:auto !important;
            display:block;
            margin:6px 0;
        }
        .article-body iframe {
            max-width:100% !important;
            width:100% !important;
            display:block;
            margin:6px 0;
        }
        .article-body table {
            display:block;
            max-width:100%;
            overflow-x:auto;
        }
        .article-body pre {
            max-width:100%;
            overflow-x:auto;
            white-space:pre;
        }
        .article-body p { margin:0 0 8px; }
        .hidden-block { margin-top:10px; padding:10px 12px; border-radius:6px; border:1px dashed var(--border-subtle); background:rgba(15,23,42,0.9); }
        .hidden-block-placeholder { margin-top:10px; padding:10px 12px; border-radius:6px; border:1px dashed var(--border-subtle); background:rgba(15,23,42,0.9); color:var(--text-muted); font-size:12px; }

        .article-title-main { font-size:20px; font-weight:700; margin:0 0 6px 0; }
        .article-tags { margin:8px 0; }
        .article-tags .tag { display:inline-block; border-radius:999px; border:1px solid var(--border-subtle); padding:2px 8px; font-size:11px; margin:0 4px 4px 0; }
        .like-status { font-size:12px; color:#f59e0b; margin:4px 0; }

        .comments-block { margin-top:12px; }
        .comments-title { font-size:14px; font-weight:600; margin-bottom:8px; }
        .comment { display:flex; margin-bottom:6px; }
        .comment-avatar { width:24px; height:24px; border-radius:999px; background:linear-gradient(135deg,#60a5fa,#a855f7); margin-right:8px; }
        .comment-body { flex:1; font-size:12px; }
        .comment-content { margin-bottom:3px; }
        .comment-header { display:flex; justify-content:flex-start; align-items:baseline; gap:6px; margin-bottom:3px; }
        .comment-name { font-weight:600; }
        .comment-meta { color:var(--text-muted); font-size:11px; }
        .comment-children { margin-top:4px; margin-left:14px; border-left:1px dashed var(--border-subtle); padding-left:6px; }

        .comment-form .form-row { margin-bottom:6px; font-size:12px; }
        .comment-form textarea { width:100%; min-height:72px; padding:6px; border-radius:4px; border:1px solid var(--border-subtle); background:var(--bg); color:var(--text-main); line-height:1.5; }
        .comment-form input[type="text"] { width:100px; padding:4px 6px; border-radius:4px; border:1px solid var(--border-subtle); background:var(--bg); color:var(--text-main); font-size:12px; }
        .emoji-bar button { border:none; background:transparent; cursor:pointer; font-size:16px; margin-right:4px; }

        .list-compact li { border-bottom:1px dashed #e5e7eb; }
        .site-stats-list { list-style:none; margin:0; padding:0; border:0; border-radius:0; background:transparent; }
        .site-stats-item { display:flex; align-items:center; justify-content:space-between; min-height:34px; padding:0 2px; border-bottom:1px solid #eef2f7; font-size:13px; }
        .site-stats-item:last-child { border-bottom:none; }
        .site-stats-label { display:inline-flex; align-items:center; gap:8px; color:var(--text-muted); }
        .site-stats-value { color:var(--text-main); font-size:13px; font-weight:700; font-variant-numeric:tabular-nums; }
        .site-stats-item-highlight .site-stats-value { color:var(--accent-strong); }
        .site-stats-icon { width:14px; height:14px; flex:0 0 14px; display:inline-flex; align-items:center; justify-content:center; color:#64748b; }
        .site-stats-item-highlight .site-stats-icon { color:var(--accent); }
        .site-stats-icon svg { width:14px; height:14px; display:block; fill:none; stroke:currentColor; stroke-width:1.8; stroke-linecap:round; stroke-linejoin:round; }
        body[data-theme="dark"] .site-stats-item { border-bottom-color:#1f2937; }
        body[data-theme="dark"] .site-stats-icon { color:#94a3b8; }

                .member-card-header {
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:8px;
            margin-bottom:6px;
        }
                .member-card-title-main {
            font-size:14px;
            font-weight:600;
        }
                .member-card-title-sub {
            display:inline-flex;
            align-items:center;
            height:20px;
            padding:0 8px;
            border-radius:999px;
            font-size:11px;
            color:#166534;
            background:#dcfce7;
            border:1px solid #86efac;
            line-height:20px;
            white-space:nowrap;
        }
                .member-actions {
            display:grid;
            grid-template-columns:repeat(3, minmax(0, 1fr));
            gap:8px;
            margin-top:8px;
        }
        .member-actions .btn {
            display:flex;
            align-items:center;
            justify-content:center;
            height:30px;
            margin-top:0;
            padding:0 8px;
            font-size:12px;
            text-align:center;
            white-space:nowrap;
        }
        .member-actions .btn.btn-logout {
            border-color:#fdba74;
            background:#fff7ed;
            color:#9a3412;
        }
        .member-welcome {
            margin:0 0 8px;
            font-size:12px;
            color:var(--text-muted);
            line-height:1.5;
        }
        .member-more {
            margin-top:6px;
            text-align:right;
            font-size:12px;
            color:var(--text-muted);
        }
        .member-guest-actions { display:flex; gap:8px; margin-top:6px; }
        .member-guest-actions .btn { flex:1; font-size:12px; padding:5px 0; }

        .site-footer { margin-top:16px; border-top:1px solid var(--border-subtle); background:var(--bg-header); color:var(--text-muted); font-size:12px; }
        .site-footer .footer-inner { max-width:1200px; margin:0 auto; padding:10px 16px 16px; text-align:center;
            display:flex;
            justify-content:center;
            align-items:flex-start; }
        .site-footer a { color:var(--accent); }

        @media (max-width:768px) {
            .layout { grid-template-columns:minmax(0,1fr); }
            .header-inner { grid-template-columns:minmax(0,1fr); }
        .header-actions { justify-content:flex-start; }
        }
    </style>
</head>
<body style="margin:0;padding:0;" data-theme="light"><header class="header">
    <div class="header-inner">
        <div>
            <div class="logo"><?php echo h($siteTitle); ?></div>
            <div class="subtitle"><?php echo h($siteSubtitle); ?></div>
        </div>
        <div class="search-box">
            <div class="search-input">
                <form method="get" action="search.php">
                    <input type="text" name="q" placeholder="搜索文章（标题/正文）">
                
                    <button type="submit" class="search-btn">搜索</button>
                </form>
            </div>
        </div>
        <div class="header-actions">
            <button class="btn-ghost" id="theme-toggle">夜间模式</button>
            <a class="btn" href="member_post.php">发布文章</a>
            <button class="btn" id="fav-btn">收藏本站</button>
        </div>
    </div>
</header>

<main class="page">
    <div class="layout">
        
        <aside class="column">
            <section class="card">
                <div class="card-title">分类导航</div>
                <ul>
                    <li>
                        <div class="category-pill">
                            <span class="category-name">
                                <?php echo render_home_nav_link('index.php'); ?>
                            </span>
                            <span class="category-count">&nbsp;</span>
                        </div>
                    </li>
                    <?php foreach ($categories as $cat): ?>
                        <li>
                            <div class="category-pill">
                                <span class="category-name">
                                    <a href="category.php?id=<?php echo (int)$cat['id']; ?>">
                                        <?php if (!empty($cat['icon_path'])): ?>
                                            <img src="<?php echo h($cat['icon_path']); ?>" alt="" style="width:16px;height:16px;border-radius:3px;vertical-align:-3px;margin-right:4px;">
                                        <?php endif; ?>
                                        <?php echo h($cat['name']); ?>
                                    </a>
                                </span>
                                <span class="category-count category-count-num"><?php echo (int)$cat['article_count']; ?></span>
                            </div>
                        </li>
                    <?php endforeach; ?>
                    <?php if (!$categories): ?><li class="small-text">暂无分类</li><?php endif; ?>
                </ul>
            </section>

            <section class="card" style="order: <?php echo (int)$sidebarOrderContact; ?>;<?php if (!$showContactCard) echo 'display:none;'; ?>">
                <div class="card-title"><?php echo h($titleContactCard); ?></div>
                <ul class="contact-list">
                    <?php if (!empty($contactItems)): ?>
                        <?php foreach ($contactItems as $ci): ?>
                            <li>
                                <div class="contact-icon"><?php echo h($ci['icon']); ?></div>
                                <div class="contact-text small-text"><?php echo h($ci['label']); ?>：<?php echo h($ci['value']); ?></div>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li class="small-text">可在后台“站点设置 &gt; 联系方式”中配置联系方式。</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card" style="order: <?php echo (int)$sidebarOrderImportantLinks; ?>;<?php if (!$showImportantLinksCard) echo 'display:none;'; ?>">
                <div class="card-title"><?php echo h($titleImportantLinksCard); ?></div>
                <ul class="friend-links">
                    <?php if ($importantFriendLinks): foreach ($importantFriendLinks as $fl): ?>
                        <li>
                            <a href="<?php echo h($fl['url']); ?>" target="_blank"><?php echo h($fl['name']); ?></a>
                        </li>
                    <?php endforeach; else: ?>
                        <li class="small-text">可在后台“友链与最新网址”中添加友情链接。</li>
                    <?php endif; ?>
                </ul>
                <div class="small-text" style="margin-top:4px;">
                    <a href="links.php">查看全部友链 / 提交申请</a>
                </div>
            </section>

            <section class="card" style="order: <?php echo (int)$sidebarOrderNewSites; ?>;<?php if (!$showNewSitesCard) echo 'display:none;'; ?>">
                <div class="card-title"><?php echo h($titleNewSitesCard); ?></div>
                <ul class="new-sites-list">
                    <?php if ($newSites): foreach ($newSites as $ns): ?>
                        <li><?php echo render_new_site_anchor($ns); ?></li>
                    <?php endforeach; else: ?>
                        <li class="small-text">可在后台添加防封用域名。</li>
                    <?php endif; ?>
                </ul>
            </section>

            
            <section class="card" style="order: <?php echo (int)$sidebarOrderTags; ?>;">
                <div class="card-title">热门标签</div>
                <div>
                    <?php if ($tags): foreach ($tags as $t): ?>
                        <a class="small-text" href="tag.php?id=<?php echo (int)$t['id']; ?>" style="margin-right:4px;">#<?php echo h($t['name']); ?></a>
                    <?php endforeach; else: ?>
                        <span class="small-text">暂无标签。</span>
                    <?php endif; ?>
                </div>
            </section>
</aside>

        
        <section class="column">
            <section class="card">
                <h1 class="article-title-main"><?php echo h($article['title']); ?></h1>
                <div class="meta-line">
                    分类：
                    <?php if (!empty($article['category_id']) && !empty($article['category_name'])): ?>
                        <a href="category.php?id=<?php echo (int)$article['category_id']; ?>"><?php echo h($article['category_name']); ?></a>
                    <?php else: ?>
                        未分类
                    <?php endif; ?>
                    · 发布于 <?php echo $article['published_at'] ? date('Y-m-d H:i', (int)$article['published_at']) : '未设置'; ?>
                    · 浏览 <?php echo (int)$article['view_count']; ?>
                    · 点赞 <?php echo (int)$article['like_count']; ?>
                </div>

                <?php if ($articleTags): ?>
                    <div class="article-tags">
                        <?php foreach ($articleTags as $t): ?>
                            <a class="tag" href="tag.php?id=<?php echo (int)$t['id']; ?>">#<?php echo h($t['name']); ?></a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <div class="article-body">
                    <?php
                    $articleHtml = render_article_with_hidden_blocks((string)$article['content_html'], $unlockedArticle);
                    
                    $articleHtml = preg_replace('/<p>\\s*(?:&nbsp;|&#160;|<br\\s*\\/?>|\\s)*<\\/p>/i', '', $articleHtml);
                    // 合并连续 <br>，避免多余空行
                    $articleHtml = preg_replace('/(?:<br\\s*\\/?>\\s*){2,}/i', '<br>', $articleHtml);
                    echo $articleHtml;
                    ?>
                </div>

                <?php if ($likeStatus): ?>
                    <div class="like-status"><?php echo h($likeStatus); ?></div>
                <?php endif; ?>
                <form method="post" action="like.php" style="margin-top:4px;">
                    <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
                    <input type="hidden" name="article_id" value="<?php echo (int)$articleId; ?>">
                    <button type="submit" class="btn">为这篇文章点赞</button>
                </form>

                <?php if ($prevArticle || $nextArticle): ?>
                    <div class="small-text" style="margin-top:8px;">
                        <?php if ($prevArticle): ?>
                            上一篇：<a href="post.php?id=<?php echo (int)$prevArticle['id']; ?>"><?php echo h($prevArticle['title']); ?></a><br>
                        <?php endif; ?>
                        <?php if ($nextArticle): ?>
                            下一篇：<a href="post.php?id=<?php echo (int)$nextArticle['id']; ?>"><?php echo h($nextArticle['title']); ?></a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="card comments-block" id="comments">
                <?php
                
                if (!function_exists('render_comments_tree_for_post_page')) {
                    function render_comments_tree_for_post_page(array $tree, int $commentId, int $level = 0): void
                    {
                        $byId     = $tree['byId'];
                        $children = $tree['children'];
                        if (!isset($byId[$commentId])) {
                            return;
                        }
                        $c    = $byId[$commentId];
                        $name = $c['is_guest'] ? ($c['guest_name'] ?? '匿名') : ($c['nickname'] ?? '会员');
                        ?>
                        <div class="comment" id="comment-<?php echo (int)$c['id']; ?>">
                            <div class="comment-avatar"></div>
                            <div class="comment-body">
                                <div class="comment-header">
                                    <span class="comment-name"><?php echo h($name); ?></span>
                                    <span class="comment-meta">· <?php echo date('Y-m-d H:i', (int)$c['created_at']); ?></span>
                                </div>
                                <div class="comment-content"><?php echo nl2br(h($c['content'])); ?></div>
                                <div class="comment-actions">
                                    <a href="post.php?id=<?php echo (int)$c['article_id']; ?>&reply_to=<?php echo (int)$c['id']; ?>#comment-form">回复</a>
                                </div>
                                <?php if (!empty($children[$commentId]) && $level < 12): ?>
                                    <div class="comment-children">
                                        <?php foreach ($children[$commentId] as $childId): ?>
                                            <?php render_comments_tree_for_post_page($tree, $childId, $level + 1); ?>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php
                    }
                }
                ?>

                <div class="comments-title">评论</div>
                <?php if (!empty($commentsTree['roots'])): ?>
                    <?php foreach ($commentsTree['roots'] as $rootId): ?>
                        <?php render_comments_tree_for_post_page($commentsTree, $rootId, 0); ?>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="small-text">还没有评论，欢迎抢沙发。</div>
                <?php endif; ?>

                <?php if ($commentPageTotal > 1): ?>
                    <div class="small-text" style="margin-top:8px;text-align:right;">
                        <?php if ($commentPage > 1): ?>
                            <a href="post.php?id=<?php echo (int)$articleId; ?>&cpage=1#comments">首页</a>
                            · <a href="post.php?id=<?php echo (int)$articleId; ?>&cpage=<?php echo $commentPage-1; ?>#comments">上一页</a>
                        <?php endif; ?>
                        <span>第 <?php echo $commentPage; ?> / <?php echo $commentPageTotal; ?> 页</span>
                        <?php if ($commentPage < $commentPageTotal): ?>
                            · <a href="post.php?id=<?php echo (int)$articleId; ?>&cpage=<?php echo $commentPage+1; ?>#comments">下一页</a>
                            · <a href="post.php?id=<?php echo (int)$articleId; ?>&cpage=<?php echo $commentPageTotal; ?>#comments">末页</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="card comment-form" id="comment-form">
                <div class="comments-title">发表新评论</div>
                <?php if ($replyToComment): ?>
                    <div class="small-text">
                        正在回复：<?php echo h($replyToComment['is_guest'] ? ($replyToComment['guest_name'] ?? '匿名') : ($replyToComment['nickname'] ?? '会员')); ?>
                        的评论：<?php echo h(mb_substr($replyToComment['content'], 0, 30, 'UTF-8')); ?>...
                    </div>
                <?php endif; ?>

                <form method="post" action="comment_submit.php">
                    <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
                    <input type="hidden" name="article_id" value="<?php echo (int)$articleId; ?>">
                    <input type="hidden" name="parent_id" value="<?php echo $replyToComment ? (int)$replyToComment['id'] : 0; ?>">
                    <div class="form-row">
                        <label for="comment_content">评论内容：</label>
                        <textarea id="comment_content" name="content" required></textarea>
                        <div class="emoji-bar">
                            <span class="small-text">表情：</span>
                            <?php
                            $emojis = ['😀','😃','😄','😁','😆','😂','😊','😉','😍','😎','😢','😭','😡','🤔','👍','👎'];
                            foreach ($emojis as $e) {
                                echo '<button type="button" class="emoji-btn" data-emoji="' . $e . '">' . $e . '</button>';
                            }
                            ?>
                        </div>
                    </div>
                    <?php if (!$currentUser): ?>
                        <div class="form-row">
                            <?php $captchaQuestion = generate_captcha('comment_' . $articleId); ?>
                            <label for="captcha_input">验证码：<?php echo h($captchaQuestion); ?></label>
                            <input type="text" id="captcha_input" name="captcha" required>
                            <div class="small-text">匿名评论需要输入简单算术验证码；登录后评论可免验证码。</div>
                        </div>
                    <?php else: ?>
                        <div class="small-text">已登录会员（<?php echo h($currentUser['nickname'] ?? ''); ?>），评论无需验证码。</div>
                    <?php endif; ?>
                    <div class="form-row">
                        <button type="submit" class="btn">提交评论</button>
                    </div>
                </form>
            </section>
        </section>

        
        <aside class="column">
            <section class="card">
                <div class="member-card-header">
                    <div class="member-card-title-main">会员中心</div>
                    <?php if ($currentUser): ?>
                        <div class="member-card-title-sub">已登录</div>
                    <?php endif; ?>
                </div>
                <?php if ($currentUser): ?>
                    <div class="member-welcome">欢迎，<?php echo h($currentUser['nickname'] ?? '会员'); ?>（ID：<?php echo (int)$currentUser['id']; ?>）
                    </div>
                    <div class="member-actions">
                        <a class="btn" href="profile.php">资料 / 头像</a>
                        <a class="btn" href="member_password.php">密码修改</a>
                        <a class="btn btn-logout" href="logout.php">退出登录</a>
                    </div>

                    <?php if ($myArticles): ?>
                        <div class="small-text" style="margin-top:6px;">我的主题</div>
                        <ul class="list-compact">
                            <?php foreach ($myArticles as $ma): ?>
                                <li>
                                    <a href="post.php?id=<?php echo (int)$ma['id']; ?>">
                                        <?php echo h($ma['title']); ?>
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>

                    <?php if ($myReplies): ?>
                        <div class="small-text" style="margin-top:6px;">我的回复</div>
                        <ul class="list-compact">
                            <?php foreach ($myReplies as $mr): ?>
                                <?php $snippet = mb_substr($mr['content'], 0, 20, 'UTF-8'); ?>
                                <li>
                                    <a href="post.php?id=<?php echo (int)$mr['article_id']; ?>#comment-<?php echo (int)$mr['id']; ?>">
                                        <?php echo h($mr['article_title'] ?: '正文'); ?>：<?php echo h($snippet); ?>...
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                    <div class="member-more">
                        <a href="member_center.php">查看更多 ></a>
                    </div>
                <?php else: ?>
                    <div class="member-guest-actions">
                        <a class="btn" href="login.php">会员登录</a>
                        <a class="btn btn-ghost" href="register.php">注册账号</a>
                    </div>
                <?php endif; ?>
            </section>

            <section class="card">
                <div class="card-title">最新评论</div>
                <ul class="list-compact">
                    <?php if ($recentComments): foreach ($recentComments as $c): ?>
                        <li>
                            <?php $name = $c['is_guest'] ? ($c['guest_name'] ?: '匿名') : ($c['nickname'] ?: '会员'); ?>
                            <?php $text = mb_substr($c['content'], 0, 30, 'UTF-8'); ?>
                            <?php echo h($name); ?>：<?php echo h($text); ?>...
                        </li>
                    <?php endforeach; else: ?>
                        <li class="small-text">暂无评论。</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card">
                <div class="card-title">最多点赞</div>
                <ul class="list-compact">
                    <?php if ($mostLikedArticles): foreach ($mostLikedArticles as $ma): ?>
                        <li><a href="post.php?id=<?php echo (int)$ma['id']; ?>"><?php echo h($ma['title']); ?></a>（<?php echo (int)$ma['like_count']; ?> 赞）</li>
                    <?php endforeach; else: ?>
                        <li class="small-text">暂无点赞数据。</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card">
                <div class="card-title">最热文章</div>
                <ul class="list-compact">
                    <?php if ($hotArticles): foreach ($hotArticles as $ha): ?>
                        <li><a href="post.php?id=<?php echo (int)$ha['id']; ?>"><?php echo h($ha['title']); ?></a>（<?php echo (int)$ha['view_count']; ?> 浏览 / <?php echo (int)$ha['like_count']; ?> 赞）</li>
                    <?php endforeach; else: ?>
                        <li class="small-text">暂无热门文章。</li>
                    <?php endif; ?>
                </ul>
            </section>

            <section class="card">
                <div class="card-title">站点统计</div>
                <ul class="site-stats-list">
                    <li class="site-stats-item site-stats-item-highlight">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="4"></circle><path d="M4 21c1.5-4 4.2-6 8-6s6.5 2 8 6"></path></svg></span>今日访客</span>
                        <span class="site-stats-value"><?php echo (int)$statsToday['uv']; ?></span>
                    </li>
                    <li class="site-stats-item site-stats-item-highlight">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M2 12s3.8-6 10-6 10 6 10 6-3.8 6-10 6-10-6-10-6"></path><circle cx="12" cy="12" r="2.8"></circle></svg></span>今日浏览</span>
                        <span class="site-stats-value"><?php echo (int)$statsToday['pv']; ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><line x1="5" y1="20" x2="19" y2="20"></line><rect x="6" y="11" width="2.8" height="7"></rect><rect x="11" y="8" width="2.8" height="10"></rect><rect x="16" y="5" width="2.8" height="13"></rect></svg></span>总浏览量</span>
                        <span class="site-stats-value"><?php echo (int)$statsTotal['pv']; ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M7 3h7l5 5v13H7z"></path><path d="M14 3v5h5"></path></svg></span>文章数目</span>
                        <span class="site-stats-value"><?php echo (int)($statsTotal['articles'] ?? 0); ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M4 6h16v9H7l-3 3z"></path></svg></span>评论数目</span>
                        <span class="site-stats-value"><?php echo (int)($statsTotal['comments'] ?? 0); ?></span>
                    </li>
                    <li class="site-stats-item">
                        <span class="site-stats-label"><span class="site-stats-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"></circle><path d="M12 8v4l2.8 1.6"></path></svg></span>运行天数</span>
                        <span class="site-stats-value"><?php echo (int)($statsTotal['runtime_days'] ?? 1); ?> 天</span>
                    </li>
                </ul>
            </section></aside>
    </div>
</main>

<footer class="site-footer">
    <div class="footer-inner">
        <div class="footer-main">
            <?php echo h($siteFooterBrand); ?> &copy; <?php echo date('Y'); ?>
            <?php if ($siteFooterOfficialUrl && $siteFooterOfficialText): ?>
                · 官方站点：<a href="<?php echo h($siteFooterOfficialUrl); ?>" target="_blank"><?php echo h($siteFooterOfficialText); ?></a>
            <?php endif; ?>
        </div>
    </div>
</footer>

<script>
    (function () {
        var key  = 'lzblog-theme';
        var body = document.body;
        var btnTheme = document.getElementById('theme-toggle');
        var btnFav   = document.getElementById('fav-btn');

        function applyTheme(theme) {
            body.setAttribute('data-theme', theme);
            if (btnTheme) {
                btnTheme.textContent = theme === 'dark' ? '日间模式' : '夜间模式';
            }
        }

        var saved = localStorage.getItem(key);
        applyTheme(saved === 'dark' ? 'dark' : 'light');

        if (btnTheme) {
            btnTheme.addEventListener('click', function () {
                var next = body.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
                localStorage.setItem(key, next);
                applyTheme(next);
            });
        }

        if (btnFav) {
            btnFav.addEventListener('click', function () {
                alert('请使用浏览器的收藏功能（例如：按 Ctrl + D）来收藏本站。');
            });
        }

        var textarea = document.getElementById('comment_content');
        if (textarea) {
            function insertAtCursor(text) {
                var start = textarea.selectionStart || 0;
                var end   = textarea.selectionEnd || 0;
                var value = textarea.value || '';
                textarea.value = value.slice(0, start) + text + value.slice(end);
                var pos = start + text.length;
                textarea.selectionStart = textarea.selectionEnd = pos;
                textarea.focus();
            }
            var buttons = document.querySelectorAll('.emoji-btn');
            buttons.forEach(function (btn) {
                btn.addEventListener('click', function () {
                    var emoji = btn.getAttribute('data-emoji') || '';
                    if (emoji) insertAtCursor(emoji);
                });
            });
        }
    })();
</script>
</body>
</html>
























