<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

function build_content_return_query($view, $keyword, $status, $domainId, $templateId)
{
    $params = array('view' => $view);
    if ($keyword !== '') {
        $params['keyword'] = $keyword;
    }
    if ($status !== '' && $status !== 'all') {
        $params['status'] = $status;
    }
    if ((int)$domainId > 0) {
        $params['domain_id'] = (int)$domainId;
    }
    if ((int)$templateId > 0) {
        $params['template_id'] = (int)$templateId;
    }
    return http_build_query($params);
}

function is_homepage_content_item($item)
{
    $templateType = isset($item['template_type']) ? trim((string)$item['template_type']) : '';
    if ($templateType !== '') {
        return is_homepage_template_type($templateType);
    }
    return !is_article_source_type(isset($item['source_type']) ? (string)$item['source_type'] : '');
}

$keyword = isset($_GET['keyword']) ? trim((string)$_GET['keyword']) : '';
$status = isset($_GET['status']) ? trim((string)$_GET['status']) : '';
$domainId = isset($_GET['domain_id']) ? (int)$_GET['domain_id'] : 0;
$templateId = isset($_GET['template_id']) ? (int)$_GET['template_id'] : 0;
$contentView = isset($_GET['view']) ? trim((string)$_GET['view']) : 'homepage';
if ($contentView !== 'article') {
    $contentView = 'homepage';
}
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPageOptions = array(10, 20, 30, 50, 100, 200, 500, 1000);
$perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 20;
if (!in_array($perPage, $perPageOptions)) { $perPage = 20; }
$deleteStatus = isset($_GET['delete_status']) ? trim((string)$_GET['delete_status']) : '';
$deletedTitle = isset($_GET['deleted_title']) ? trim((string)$_GET['deleted_title']) : '';
$publishStatus = isset($_GET['publish_status']) ? trim((string)$_GET['publish_status']) : '';
$publishAction = isset($_GET['publish_action']) ? trim((string)$_GET['publish_action']) : '';
$publishTitle = isset($_GET['publish_title']) ? trim((string)$_GET['publish_title']) : '';
$staticStatus = isset($_GET['static_status']) ? trim((string)$_GET['static_status']) : '';
$staticTitle = isset($_GET['static_title']) ? trim((string)$_GET['static_title']) : '';
$batchStatus = isset($_GET['batch_status']) ? trim((string)$_GET['batch_status']) : '';
$batchAction = isset($_GET['batch_action']) ? trim((string)$_GET['batch_action']) : '';
$batchCount = isset($_GET['batch_count']) ? (int)$_GET['batch_count'] : 0;
$fixCoverStatus = isset($_GET['fix_cover_status']) ? trim((string)$_GET['fix_cover_status']) : '';
$fixCoverCount = isset($_GET['fix_cover_count']) ? (int)$_GET['fix_cover_count'] : 0;
$fixRepublishCount = isset($_GET['fix_republish_count']) ? (int)$_GET['fix_republish_count'] : 0;
$fixCoverMessage = isset($_GET['fix_cover_message']) ? trim((string)$_GET['fix_cover_message']) : '';
$returnQuery = build_content_return_query($contentView, $keyword, $status, $domainId, $templateId);

$statusOptions = content_status_options();
$dbError = '';
$contents = array();
$filteredContents = array();
$domains = array();

$contentStats = array('site_total' => 0, 'site_today' => 0, 'article_total' => 0, 'article_today' => 0);
try {
    $contents = list_contents($keyword, $status, $domainId, $templateId);
    $domains = list_enabled_domain_options();
    $contentStats = count_content_stats();
} catch (Exception $e) {
    $dbError = $e->getMessage();
}

foreach ($contents as $item) {
    $isHomepageItem = is_homepage_content_item($item);
    if (($contentView === 'homepage' && $isHomepageItem) || ($contentView === 'article' && !$isHomepageItem)) {
        $filteredContents[] = $item;
    }
}
$totalItems = count($filteredContents);
$totalPages = max(1, (int)ceil($totalItems / $perPage));
if ($page > $totalPages) { $page = $totalPages; }
$pagedContents = array_slice($filteredContents, ($page - 1) * $perPage, $perPage);

function build_pagination_url($page, $contentView, $keyword, $status, $domainId, $templateId)
{
    global $perPage;
    $params = array('view' => $contentView, 'page' => $page);
    if ($keyword !== '') { $params['keyword'] = $keyword; }
    if ($status !== '' && $status !== 'all') { $params['status'] = $status; }
    if ((int)$domainId > 0) { $params['domain_id'] = (int)$domainId; }
    if ((int)$templateId > 0) { $params['template_id'] = (int)$templateId; }
    if (isset($perPage) && (int)$perPage !== 20) { $params['per_page'] = (int)$perPage; }
    return '/admin/content/list.php?' . http_build_query($params);
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 内容管理</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <style>
        .content-filter-row {
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: nowrap;
            margin-bottom: 14px;
        }

        .content-filter-row .input {
            flex: 1.5;
            min-width: 0;
        }

        .content-filter-row .select {
            flex: 0.8;
            min-width: 0;
        }

        .content-filter-row .btn-soft,
        .content-filter-row .btn-ghost {
            flex: 0 0 auto;
            white-space: nowrap;
        }

        .content-title-cell strong,
        .content-title-cell .content-subline {
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .content-title-cell .content-subline {
            margin-top: 4px;
            font-size: 12px;
            color: #64748b;
        }

        .content-actions {
            white-space: nowrap;
            font-size: 13px;
        }

        .content-batch-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            flex-wrap: wrap;
            margin: 16px 0 12px;
            padding: 12px 14px;
            border: 1px solid rgba(148,163,184,0.2);
            border-radius: 16px;
            background: #f8fafc;
        }

        .content-batch-bar .batch-left,
        .content-batch-bar .batch-right {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        .content-batch-bar label {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
            color: #334155;
        }

        .content-checkbox-cell {
            width: 44px;
            text-align: center;
        }

        .content-checkbox-cell input {
            width: 16px;
            height: 16px;
        }

        .content-view-switch {
            display: flex;
            gap: 12px;
            margin-bottom: 16px;
        }

        .content-view-switch a {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 132px;
            padding: 12px 18px;
            border-radius: 14px;
            border: 1px solid rgba(148,163,184,0.24);
            background: #fff;
            color: #334155;
            font-weight: 700;
        }

        .content-view-switch a.is-active {
            border-color: transparent;
            background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
            color: #fff;
            box-shadow: 0 12px 30px rgba(79,70,229,0.22);
        }

        .content-pagination {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            margin-top: 20px;
            flex-wrap: wrap;
        }

        .content-pagination a,
        .content-pagination span {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 36px;
            height: 36px;
            padding: 0 10px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.18s;
        }

        .content-pagination a {
            background: #fff;
            color: #334155;
            border: 1px solid rgba(148,163,184,0.22);
        }

        .content-pagination a:hover {
            background: #f1f5f9;
            border-color: rgba(99,102,241,0.3);
            color: #4f46e5;
        }

        .content-pagination .pg-current {
            background: linear-gradient(135deg, #4f46e5, #6366f1);
            color: #fff;
            border: none;
            box-shadow: 0 4px 12px rgba(79,70,229,0.22);
        }

        .content-pagination .pg-ellipsis {
            color: #94a3b8;
            border: none;
            cursor: default;
        }

        .content-pagination .pg-disabled {
            color: #cbd5e1;
            border: 1px solid rgba(148,163,184,0.12);
            background: #f8fafc;
            cursor: default;
            pointer-events: none;
        }

        .content-pagination-info {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 10px;
            font-size: 13px;
            color: #64748b;
        }

        @media (max-width: 1280px) {
            .content-filter-row {
                gap: 10px;
            }
        }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('content', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>内容管理</h1></div>
                <div class="topbar-actions"><?php if ($contentView === 'article'): ?><a class="btn-ghost" href="/admin/content/fix-cover-paths.php" onclick="return confirm('确认批量修复历史文章封面图路径，并对已发布内容重新生成静态文件吗？');">修复封面图路径</a><a class="btn-primary" href="/admin/content/add.php?view=article">发布文章</a><?php endif; ?></div>
            </header>
            <section class="page-card">
                <div class="content-view-switch">
                    <a class="<?php echo $contentView === 'homepage' ? 'is-active' : ''; ?>" href="/admin/content/list.php?view=homepage">首页管理</a>
                    <a class="<?php echo $contentView === 'article' ? 'is-active' : ''; ?>" href="/admin/content/list.php?view=article">文章管理</a>
                </div>
                <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:18px;">
                    <div style="padding:16px 18px;border-radius:14px;background:linear-gradient(135deg,#eef2ff 0%,#e0e7ff 100%);border:1px solid rgba(99,102,241,.12);">
                        <div style="font-size:12px;color:#6366f1;font-weight:600;margin-bottom:6px;">今日生成站点</div>
                        <div style="font-size:26px;font-weight:800;color:#4338ca;line-height:1.2;"><?php echo number_format($contentStats['site_today']); ?></div>
                    </div>
                    <div style="padding:16px 18px;border-radius:14px;background:linear-gradient(135deg,#f0fdf4 0%,#dcfce7 100%);border:1px solid rgba(34,197,94,.12);">
                        <div style="font-size:12px;color:#16a34a;font-weight:600;margin-bottom:6px;">站点总数</div>
                        <div style="font-size:26px;font-weight:800;color:#15803d;line-height:1.2;"><?php echo number_format($contentStats['site_total']); ?></div>
                    </div>
                    <div style="padding:16px 18px;border-radius:14px;background:linear-gradient(135deg,#fff7ed 0%,#ffedd5 100%);border:1px solid rgba(249,115,22,.12);">
                        <div style="font-size:12px;color:#ea580c;font-weight:600;margin-bottom:6px;">今日生成文章</div>
                        <div style="font-size:26px;font-weight:800;color:#c2410c;line-height:1.2;"><?php echo number_format($contentStats['article_today']); ?></div>
                    </div>
                    <div style="padding:16px 18px;border-radius:14px;background:linear-gradient(135deg,#fdf2f8 0%,#fce7f3 100%);border:1px solid rgba(236,72,153,.12);">
                        <div style="font-size:12px;color:#db2777;font-weight:600;margin-bottom:6px;">文章总数</div>
                        <div style="font-size:26px;font-weight:800;color:#be185d;line-height:1.2;"><?php echo number_format($contentStats['article_total']); ?></div>
                    </div>
                </div>
                <?php if ($deleteStatus === 'success'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">删除成功</strong>
                        <p style="margin:0; color:#166534;">内容 <?php echo e($deletedTitle); ?> 已删除。</p>
                    </div>
                <?php elseif ($deleteStatus === 'missing'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">删除失败</strong>
                        <p style="margin:0; color:#b91c1c;">未找到对应的内容记录。</p>
                    </div>
                <?php elseif ($deleteStatus === 'error'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">删除失败</strong>
                        <p style="margin:0; color:#b91c1c;">数据库删除失败，请稍后重试。</p>
                    </div>
                <?php endif; ?>
                <?php if ($publishStatus === 'success'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">状态更新成功</strong>
                        <p style="margin:0; color:#166534;">内容 <?php echo e($publishTitle); ?> 已<?php echo $publishAction === 'published' ? '发布（动态可访问，未生成静态）' : '取消发布（前台404，并清理静态文件）'; ?>。</p>
                    </div>
                <?php elseif ($publishStatus === 'missing'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">状态更新失败</strong>
                        <p style="margin:0; color:#b91c1c;">未找到对应的内容记录。</p>
                    </div>
                <?php elseif ($publishStatus === 'error'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">状态更新失败</strong>
                        <p style="margin:0; color:#b91c1c;">数据库操作失败，请稍后重试。</p>
                    </div>
                <?php endif; ?>
                <?php if ($staticStatus === 'success'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">静态发布成功</strong>
                        <p style="margin:0; color:#166534;">内容 <?php echo e($staticTitle); ?> 已重新生成静态文件。</p>
                    </div>
                <?php elseif ($staticStatus === 'missing'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">静态发布失败</strong>
                        <p style="margin:0; color:#b91c1c;">未找到对应的内容记录。</p>
                    </div>
                <?php elseif ($staticStatus === 'error'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">静态发布失败</strong>
                        <p style="margin:0; color:#b91c1c;">请确认内容已发布且模板可用。</p>
                    </div>
                <?php endif; ?>
                <?php if ($batchStatus === 'success'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">批量操作完成</strong>
                        <p style="margin:0; color:#166534;">已完成 <?php echo $batchAction === 'draft_publish' ? '批量草稿发布' : ($batchAction === 'static_publish' ? '批量重新静态发布' : ($batchAction === 'publish' ? '批量发布' : ($batchAction === 'unpublish' ? '批量取消发布' : '批量删除'))); ?>，共处理 <?php echo (int)$batchCount; ?> 条内容。</p>
                    </div>
                <?php elseif ($batchStatus === 'empty'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">批量操作失败</strong>
                        <p style="margin:0; color:#b91c1c;">请先勾选需要处理的文章。</p>
                    </div>
                <?php elseif ($batchStatus === 'error'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">批量操作失败</strong>
                        <p style="margin:0; color:#b91c1c;">批量<?php echo $batchAction === 'static_publish' ? '重新静态发布' : ($batchAction === 'publish' ? '发布' : ($batchAction === 'unpublish' ? '取消发布' : '删除')); ?>时出现异常，请稍后重试。</p>
                    </div>
                <?php endif; ?>
                <?php if ($fixCoverStatus === 'success'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">封面图路径修复完成</strong>
                        <p style="margin:0; color:#166534;">已修复 <?php echo (int)$fixCoverCount; ?> 篇历史文章的封面图路径，并重新生成 <?php echo (int)$fixRepublishCount; ?> 篇已发布内容的静态文件。</p>
                    </div>
                <?php elseif ($fixCoverStatus === 'error'): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">封面图路径修复失败</strong>
                        <p style="margin:0; color:#b91c1c;"><?php echo e($fixCoverMessage !== '' ? $fixCoverMessage : '请稍后重试。'); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($dbError !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">数据库读取失败</strong>
                        <p style="margin:0; color:#b91c1c;"><?php echo e($dbError); ?></p>
                    </div>
                <?php endif; ?>
                <div class="mini-item" style="margin-bottom:16px; border-color: rgba(79,70,229,0.16); background: rgba(238,242,255,0.92);">
                    <strong style="color:#4338ca;"><?php echo $contentView === 'article' ? '文章内容说明' : '首页内容说明'; ?></strong>
                    <p style="margin:0; color:#3730a3;"><?php echo $contentView === 'article' ? '文章内容主要来自站点发布中的文章AI定时生成任务，支持封面图修复、关键词追踪与静态发布。' : '首页默认映射根路径 `/`：发布=动态可访问，取消发布=草稿并404，静态发布=生成HTML加速但URL仍为伪静态。'; ?></p>
                </div>
                <form class="filter-row content-filter-row" method="get" action="/admin/content/list.php">
                    <input type="hidden" name="view" value="<?php echo e($contentView); ?>">
                    <input class="input" type="text" name="keyword" value="<?php echo e($keyword); ?>" placeholder="<?php echo $contentView === 'article' ? '搜索文章标题 / 路径 / SEO标题' : '搜索首页标题 / 路径 / SEO标题'; ?>">
                    <select class="select" name="status">
                        <option value="all"<?php echo ($status === '' || $status === 'all') ? ' selected' : ''; ?>>全部状态</option>
                        <?php foreach ($statusOptions as $key => $label): ?>
                            <option value="<?php echo e($key); ?>"<?php echo $status === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select class="select" name="domain_id">
                        <option value="0">全部域名</option>
                        <?php foreach ($domains as $item): ?>
                            <option value="<?php echo (int)$item['id']; ?>"<?php echo $domainId === (int)$item['id'] ? ' selected' : ''; ?>><?php echo e($item['domain']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button class="btn-soft" type="submit">搜索</button>
                    <a class="btn-ghost" href="/admin/content/list.php?view=<?php echo e($contentView); ?>">重置</a>
                </form>
                <form id="batchForm" method="post" action="/admin/content/batch.php" onsubmit="return beforeBatchSubmit(this) && confirm(this.dataset.confirmMessage || '确认执行批量操作吗？');">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="return_query" value="<?php echo e($returnQuery); ?>">
                    <div class="content-batch-bar">
                        <div class="batch-left">
                            <label><input type="checkbox" id="content-check-all"> 全选 / 取消全选</label>
                            <span style="font-size:13px; color:#64748b;">已选<?php echo $contentView === 'article' ? '文章' : '首页'; ?>将执行批量操作。</span>
                        </div>
                        <div class="batch-right">
                            <?php if ($contentView === 'article'): ?>
                            <button class="btn-primary" type="button" onclick="startBatchDraftPublish()" style="font-size:13px;">批量草稿发布</button>
                            <?php endif; ?>
                            <?php if ($contentView === 'homepage'): ?>
                            <button class="btn-primary" type="submit" name="batch_action" value="publish" onclick="this.form.dataset.confirmMessage='确认批量发布已勾选首页吗？发布后为动态可访问（不自动生成静态）。';">批量发布</button>
                            <button class="btn-soft" type="submit" name="batch_action" value="unpublish" onclick="this.form.dataset.confirmMessage='确认批量取消发布已勾选首页吗？将变为草稿并清理静态文件。';">批量取消发布</button>
                            <?php endif; ?>
                            <button class="btn-ghost" type="button" id="batchPublishBtn" onclick="startBatchPublish()">批量静态发布</button>
                            <button class="btn-soft" type="submit" name="batch_action" value="delete" onclick="this.form.dataset.confirmMessage='确认批量删除已勾选内容吗？此操作不可恢复。';">批量删除</button>
                        </div>
                    </div>
                </form>

                <script>
                var _batchAbort = false;
                function getCheckedIds() {
                    var ids = [];
                    document.querySelectorAll('input[name="ids[]"]:checked').forEach(function(el) {
                        if (parseInt(el.value) > 0) ids.push(parseInt(el.value));
                    });
                    return ids;
                }
                function startBatchPublish() {
                    var ids = getCheckedIds();
                    if (ids.length === 0) { alert('请先勾选需要发布的内容。'); return; }
                    if (!confirm('确认批量重新静态发布已勾选的 ' + ids.length + ' 条内容吗？')) return;
                    _batchAbort = false;
                    var modal = document.getElementById('batchPublishModal');
                    var bar = document.getElementById('batchProgressBar');
                    var label = document.getElementById('batchProgressLabel');
                    var pct = document.getElementById('batchProgressPercent');
                    var statusText = document.getElementById('batchStatusText');
                    var logWrap = document.getElementById('batchLogWrap');
                    var cancelBtn = document.getElementById('batchCancelBtn');
                    var closeBtn = document.getElementById('batchCloseBtn');
                    document.getElementById('batchModalTitle').textContent = '批量静态发布';
                    modal.style.display = 'block';
                    bar.style.width = '0%';
                    label.textContent = '0 / ' + ids.length;
                    pct.textContent = '0%';
                    statusText.textContent = '正在发布，请勿关闭页面...';
                    logWrap.innerHTML = '';
                    cancelBtn.style.display = '';
                    closeBtn.style.display = 'none';
                    var done = 0, ok = 0, fail = 0;
                    var CHUNK_SIZE = 10;
                    var PARALLEL = 3;
                    var DISPLAY_INTERVAL = 100;
                    var chunks = [];
                    for (var i = 0; i < ids.length; i += CHUNK_SIZE) {
                        chunks.push(ids.slice(i, i + CHUNK_SIZE));
                    }
                    var chunkCursor = 0;
                    var activeWorkers = 0;
                    var displayQueue = [];
                    var displayTimer = null;
                    var fetchDone = false;
                    function addLog(msg, isErr) {
                        var d = document.createElement('div');
                        d.textContent = msg;
                        if (isErr) d.style.color = '#dc2626';
                        logWrap.appendChild(d);
                        logWrap.scrollTop = logWrap.scrollHeight;
                    }
                    function updateProgress() {
                        var p = ids.length > 0 ? Math.round(done / ids.length * 100) : 0;
                        bar.style.width = p + '%';
                        label.textContent = done + ' / ' + ids.length;
                        pct.textContent = p + '%';
                    }
                    function checkFinish() {
                        if (done >= ids.length || (_batchAbort && activeWorkers <= 0 && displayQueue.length === 0)) {
                            statusText.textContent = _batchAbort
                                ? '已取消，成功 ' + ok + ' 篇，失败 ' + fail + ' 篇，剩余 ' + (ids.length - done) + ' 篇未处理。'
                                : '全部完成！成功 ' + ok + ' 篇' + (fail > 0 ? '，失败 ' + fail + ' 篇' : '') + '。';
                            statusText.style.color = fail > 0 ? '#ea580c' : '#16a34a';
                            cancelBtn.style.display = 'none';
                            closeBtn.style.display = '';
                            return true;
                        }
                        return false;
                    }
                    function drainQueue() {
                        if (displayQueue.length === 0) {
                            displayTimer = null;
                            if (fetchDone || _batchAbort) checkFinish();
                            return;
                        }
                        var item = displayQueue.shift();
                        done++;
                        if (item.success) {
                            ok++;
                            addLog('[' + done + '/' + ids.length + '] ID:' + item.id + ' ' + (item.title || '') + ' ✓');
                        } else {
                            fail++;
                            addLog('[' + done + '/' + ids.length + '] ID:' + item.id + ' 失败: ' + (item.message || '未知错误'), true);
                        }
                        updateProgress();
                        if (!checkFinish()) {
                            displayTimer = setTimeout(drainQueue, DISPLAY_INTERVAL);
                        }
                    }
                    function startDrain() {
                        if (!displayTimer && displayQueue.length > 0) {
                            displayTimer = setTimeout(drainQueue, DISPLAY_INTERVAL);
                        }
                    }
                    function onChunkResults(results) {
                        results.forEach(function(r) { displayQueue.push(r); });
                        startDrain();
                    }
                    function doChunkFetch(chunk, isRetry) {
                        activeWorkers++;
                        var fd = new FormData();
                        fd.append('ids', chunk.join(','));
                        fd.append('_csrf_token', document.querySelector('#batchForm input[name="_csrf_token"]').value);
                        fetch('/admin/api/content-batch-publish-chunk.php', { method: 'POST', body: fd })
                            .then(function(r) { return r.json(); })
                            .then(function(data) {
                                activeWorkers--;
                                if (data.results && Array.isArray(data.results)) {
                                    onChunkResults(data.results);
                                } else {
                                    var errResults = chunk.map(function(id) { return {success:false, id:id, message:'返回格式异常'}; });
                                    onChunkResults(errResults);
                                }
                                if (!_batchAbort) runNextChunk();
                                if (activeWorkers <= 0 && chunkCursor >= chunks.length) fetchDone = true;
                            })
                            .catch(function(e) {
                                activeWorkers--;
                                if (!isRetry) {
                                    addLog('批次请求异常（' + chunk.length + ' 篇），2秒后重试...', true);
                                    setTimeout(function() { doChunkFetch(chunk, true); }, 2000);
                                } else {
                                    var errResults = chunk.map(function(id) { return {success:false, id:id, message:'请求异常: ' + e.message}; });
                                    onChunkResults(errResults);
                                    if (!_batchAbort) runNextChunk();
                                    if (activeWorkers <= 0 && chunkCursor >= chunks.length) fetchDone = true;
                                }
                            });
                    }
                    function runNextChunk() {
                        while (activeWorkers < PARALLEL && chunkCursor < chunks.length && !_batchAbort) {
                            doChunkFetch(chunks[chunkCursor++], false);
                        }
                    }
                    runNextChunk();
                }
                function cancelBatchPublish() {
                    _batchAbort = true;
                    document.getElementById('batchStatusText').textContent = '正在取消...';
                }
                function closeBatchPublish() {
                    document.getElementById('batchPublishModal').style.display = 'none';
                    location.reload();
                }
                function startBatchDraftPublish() {
                    var ids = getCheckedIds();
                    if (ids.length === 0) { alert('请先勾选需要发布的草稿文章。'); return; }
                    if (!confirm('确认批量将已勾选的 ' + ids.length + ' 篇草稿文章发布吗？')) return;
                    _batchAbort = false;
                    var modal = document.getElementById('batchPublishModal');
                    var bar = document.getElementById('batchProgressBar');
                    var label = document.getElementById('batchProgressLabel');
                    var pct = document.getElementById('batchProgressPercent');
                    var statusText = document.getElementById('batchStatusText');
                    var logWrap = document.getElementById('batchLogWrap');
                    var cancelBtn = document.getElementById('batchCancelBtn');
                    var closeBtn = document.getElementById('batchCloseBtn');
                    document.getElementById('batchModalTitle').textContent = '批量草稿发布';
                    modal.style.display = 'block';
                    bar.style.width = '0%';
                    label.textContent = '0 / ' + ids.length;
                    pct.textContent = '0%';
                    statusText.textContent = '正在批量发布草稿，请勿关闭页面...';
                    statusText.style.color = '#64748b';
                    logWrap.innerHTML = '';
                    cancelBtn.style.display = '';
                    closeBtn.style.display = 'none';
                    var done = 0, ok = 0, fail = 0;
                    var CHUNK_SIZE = 10;
                    var PARALLEL = 3;
                    var DISPLAY_INTERVAL = 100;
                    var chunks = [];
                    for (var i = 0; i < ids.length; i += CHUNK_SIZE) {
                        chunks.push(ids.slice(i, i + CHUNK_SIZE));
                    }
                    var chunkCursor = 0;
                    var activeWorkers = 0;
                    var displayQueue = [];
                    var displayTimer = null;
                    var fetchDone = false;
                    function addLog(msg, isErr) {
                        var d = document.createElement('div');
                        d.textContent = msg;
                        if (isErr) d.style.color = '#dc2626';
                        logWrap.appendChild(d);
                        logWrap.scrollTop = logWrap.scrollHeight;
                    }
                    function updateProgress() {
                        var p = ids.length > 0 ? Math.round(done / ids.length * 100) : 0;
                        bar.style.width = p + '%';
                        label.textContent = done + ' / ' + ids.length;
                        pct.textContent = p + '%';
                    }
                    function checkFinish() {
                        if (done >= ids.length || (_batchAbort && activeWorkers <= 0 && displayQueue.length === 0)) {
                            statusText.textContent = _batchAbort
                                ? '已取消，成功 ' + ok + ' 篇，失败 ' + fail + ' 篇，剩余 ' + (ids.length - done) + ' 篇未处理。'
                                : '全部完成！成功 ' + ok + ' 篇' + (fail > 0 ? '，失败 ' + fail + ' 篇' : '') + '。';
                            statusText.style.color = fail > 0 ? '#ea580c' : '#16a34a';
                            cancelBtn.style.display = 'none';
                            closeBtn.style.display = '';
                            return true;
                        }
                        return false;
                    }
                    function drainQueue() {
                        if (displayQueue.length === 0) {
                            displayTimer = null;
                            if (fetchDone || _batchAbort) checkFinish();
                            return;
                        }
                        var item = displayQueue.shift();
                        done++;
                        if (item.success) {
                            ok++;
                            addLog('[' + done + '/' + ids.length + '] ID:' + item.id + ' ' + (item.title || '') + ' ✓ 已发布');
                        } else {
                            fail++;
                            addLog('[' + done + '/' + ids.length + '] ID:' + item.id + ' 失败: ' + (item.message || '未知错误'), true);
                        }
                        updateProgress();
                        if (!checkFinish()) {
                            displayTimer = setTimeout(drainQueue, DISPLAY_INTERVAL);
                        }
                    }
                    function startDrain() {
                        if (!displayTimer && displayQueue.length > 0) {
                            displayTimer = setTimeout(drainQueue, DISPLAY_INTERVAL);
                        }
                    }
                    function onChunkResults(results) {
                        results.forEach(function(r) { displayQueue.push(r); });
                        startDrain();
                    }
                    function doChunkFetch(chunk, isRetry) {
                        activeWorkers++;
                        var fd = new FormData();
                        fd.append('ids', chunk.join(','));
                        fd.append('_csrf_token', document.querySelector('#batchForm input[name="_csrf_token"]').value);
                        fetch('/admin/api/content-batch-draft-publish-chunk.php', { method: 'POST', body: fd })
                            .then(function(r) { return r.json(); })
                            .then(function(data) {
                                activeWorkers--;
                                if (data.results && Array.isArray(data.results)) {
                                    onChunkResults(data.results);
                                } else {
                                    var errResults = chunk.map(function(id) { return {success:false, id:id, message:'返回格式异常'}; });
                                    onChunkResults(errResults);
                                }
                                if (!_batchAbort) runNextChunk();
                                if (activeWorkers <= 0 && chunkCursor >= chunks.length) fetchDone = true;
                            })
                            .catch(function(e) {
                                activeWorkers--;
                                if (!isRetry) {
                                    addLog('批次请求异常（' + chunk.length + ' 篇），2秒后重试...', true);
                                    setTimeout(function() { doChunkFetch(chunk, true); }, 2000);
                                } else {
                                    var errResults = chunk.map(function(id) { return {success:false, id:id, message:'请求异常: ' + e.message}; });
                                    onChunkResults(errResults);
                                    if (!_batchAbort) runNextChunk();
                                    if (activeWorkers <= 0 && chunkCursor >= chunks.length) fetchDone = true;
                                }
                            });
                    }
                    function runNextChunk() {
                        while (activeWorkers < PARALLEL && chunkCursor < chunks.length && !_batchAbort) {
                            doChunkFetch(chunks[chunkCursor++], false);
                        }
                    }
                    runNextChunk();
                }
                </script>
                <table class="data-table">
                    <thead><tr><th class="content-checkbox-cell">选</th><th>ID</th><th><?php echo $contentView === 'article' ? '文章标题' : '首页标题'; ?></th><th>域名</th><th>模板</th><th><?php echo $contentView === 'article' ? '来源' : '页面路径'; ?></th><th>状态</th><th>更新时间</th><th>操作</th></tr></thead>
                    <tbody>
                    <?php if (!empty($pagedContents)): ?>
                        <?php foreach ($pagedContents as $item): ?>
                            <?php
                            $previewDomain = isset($item['domain_name']) ? trim((string)$item['domain_name']) : '';
                            $previewPath = isset($item['path']) ? (string)$item['path'] : (isset($item['slug']) ? (string)$item['slug'] : '');
                            $isHomepageItem = is_homepage_content_item($item);
                            $effectivePathLabel = $isHomepageItem ? '/' : '/' . $previewPath;
                            $previewUrl = '/admin/content/preview.php?id=' . (int)$item['id'];
                            $hasStaticFile = content_has_static_file($item);
                            if (isset($item['status']) && $item['status'] === 'published' && $previewDomain !== '') {
                                $previewUrl = '//' . $previewDomain . ($isHomepageItem ? '/' : content_public_url_path($previewPath, $hasStaticFile));
                            }
                            $sourceLabel = isset($item['source_type']) && $item['source_type'] === 'article_ai'
                                ? ('AI关键词：' . (isset($item['source_keyword']) && $item['source_keyword'] !== '' ? $item['source_keyword'] : '-'))
                                : '手动 / 首页生成';
                            $actionQuery = $returnQuery !== '' ? '&return_query=' . urlencode($returnQuery) : '';
                            ?>
                            <tr>
                                <td class="content-checkbox-cell"><input type="checkbox" class="content-check-item" name="ids[]" value="<?php echo (int)$item['id']; ?>"></td>
                                <td><?php echo (int)$item['id']; ?></td>
                                <td class="content-title-cell"><strong><?php echo e($item['title']); ?></strong><span class="content-subline"><?php echo e($effectivePathLabel); ?></span></td>
                                <td><?php echo e($item['domain_name'] !== '' ? $item['domain_name'] : '-'); ?></td>
                                <td><?php echo e($item['template_name'] !== '' ? $item['template_name'] : '-'); ?></td>
                                <td><?php echo e($contentView === 'article' ? $sourceLabel : $effectivePathLabel); ?></td>
                                <td><span class="badge <?php echo e(content_badge_class($item['status'])); ?>"><?php echo e(isset($statusOptions[$item['status']]) ? $statusOptions[$item['status']] : $item['status']); ?></span></td>
                                <td><?php echo e($item['updated_at']); ?></td>
                                <td class="content-actions">
                                    <a href="/admin/content/edit.php?id=<?php echo (int)$item['id']; ?>">编辑</a>
                                    <?php if ($previewUrl !== ''): ?> / <a href="<?php echo e($previewUrl); ?>" target="_blank" rel="noopener noreferrer">预览</a><?php endif; ?>
                                    <?php if ($contentView === 'homepage'): ?> / <a href="/admin/site-build/index.php?regen=<?php echo (int)$item['id']; ?>">重新生成</a><?php endif; ?>
                                    / <?php if ($item['status'] === 'published'): ?>
                                        <?php $staticLabel = $hasStaticFile ? '重新静态发布' : '生成静态'; ?>
                                        <a href="/admin/content/static-publish.php?id=<?php echo (int)$item['id']; ?><?php echo $actionQuery; ?>"><?php echo $staticLabel; ?></a> /
                                        <form method="post" action="/admin/content/status.php" style="display:inline;" onsubmit="return confirm('确认取消发布内容「<?php echo e($item['title']); ?>」吗？取消发布将变草稿并清理静态文件。');"><?php echo csrf_field(); ?><input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>"><input type="hidden" name="status" value="draft"><input type="hidden" name="return_query" value="<?php echo e($returnQuery); ?>"><button type="submit" class="link-btn">取消发布</button></form>
                                    <?php else: ?>
                                        <form method="post" action="/admin/content/status.php" style="display:inline;" onsubmit="return confirm('确认发布内容「<?php echo e($item['title']); ?>」吗？发布仅开启动态访问，不会自动生成静态。');"><?php echo csrf_field(); ?><input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>"><input type="hidden" name="status" value="published"><input type="hidden" name="return_query" value="<?php echo e($returnQuery); ?>"><button type="submit" class="link-btn">发布</button></form>
                                    <?php endif; ?>
                                    / <form method="post" action="/admin/content/delete.php" style="display:inline;" onsubmit="return confirm('确认删除内容「<?php echo e($item['title']); ?>」吗？');"><?php echo csrf_field(); ?><input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>"><input type="hidden" name="return_query" value="<?php echo e($returnQuery); ?>"><button type="submit" class="link-btn" style="color:#dc2626;">删除</button></form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="9" class="empty-note"><?php echo $dbError === '' ? ($contentView === 'article' ? '暂无文章内容，请先到一键建站中创建文章任务或生成文章。' : '暂无首页内容，请先新增首页内容或通过一键建站生成。') : '无法加载数据。'; ?></td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
                <?php if ($totalPages > 1): ?>
                <nav class="content-pagination">
                    <?php if ($page > 1): ?>
                        <a href="<?php echo e(build_pagination_url(1, $contentView, $keyword, $status, $domainId, $templateId)); ?>" title="首页">&laquo;</a>
                        <a href="<?php echo e(build_pagination_url($page - 1, $contentView, $keyword, $status, $domainId, $templateId)); ?>" title="上一页">&lsaquo;</a>
                    <?php else: ?>
                        <span class="pg-disabled">&laquo;</span>
                        <span class="pg-disabled">&lsaquo;</span>
                    <?php endif; ?>
                    <?php
                    $pgStart = max(1, $page - 3);
                    $pgEnd = min($totalPages, $page + 3);
                    if ($pgStart > 1): ?><a href="<?php echo e(build_pagination_url(1, $contentView, $keyword, $status, $domainId, $templateId)); ?>">1</a><?php if ($pgStart > 2): ?><span class="pg-ellipsis">&hellip;</span><?php endif; endif;
                    for ($p = $pgStart; $p <= $pgEnd; $p++): ?>
                        <?php if ($p === $page): ?><span class="pg-current"><?php echo $p; ?></span>
                        <?php else: ?><a href="<?php echo e(build_pagination_url($p, $contentView, $keyword, $status, $domainId, $templateId)); ?>"><?php echo $p; ?></a>
                        <?php endif; ?>
                    <?php endfor;
                    if ($pgEnd < $totalPages): ?><?php if ($pgEnd < $totalPages - 1): ?><span class="pg-ellipsis">&hellip;</span><?php endif; ?><a href="<?php echo e(build_pagination_url($totalPages, $contentView, $keyword, $status, $domainId, $templateId)); ?>"><?php echo $totalPages; ?></a><?php endif; ?>
                    <?php if ($page < $totalPages): ?>
                        <a href="<?php echo e(build_pagination_url($page + 1, $contentView, $keyword, $status, $domainId, $templateId)); ?>" title="下一页">&rsaquo;</a>
                        <a href="<?php echo e(build_pagination_url($totalPages, $contentView, $keyword, $status, $domainId, $templateId)); ?>" title="末页">&raquo;</a>
                    <?php else: ?>
                        <span class="pg-disabled">&rsaquo;</span>
                        <span class="pg-disabled">&raquo;</span>
                    <?php endif; ?>
                </nav>
                <?php endif; ?>
                <div class="content-pagination-info">
                    <span>共 <?php echo $totalItems; ?> 条记录，<?php echo $totalPages; ?> 页，当前第 <?php echo $page; ?> 页</span>
                    <label style="display:inline-flex;align-items:center;gap:6px;font-size:13px;color:#64748b;">每页
                        <select id="perPageSelect" style="padding:3px 8px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;color:#334155;background:#fff;cursor:pointer;">
                            <?php foreach ($perPageOptions as $_pp): ?>
                                <option value="<?php echo $_pp; ?>"<?php echo $perPage === $_pp ? ' selected' : ''; ?>><?php echo $_pp; ?></option>
                            <?php endforeach; ?>
                        </select>条
                    </label>
                    <script>document.getElementById('perPageSelect').onchange=function(){var b='<?php echo e(build_pagination_url(1, $contentView, $keyword, $status, $domainId, $templateId)); ?>';window.location.href=b+(b.indexOf('?')>=0?'&':'?')+'per_page='+this.value;};</script>
                </div>
                <div class="table-note"><?php echo $contentView === 'article' ? '文章内容由一键建站中的文章生成能力统一管理，这里主要负责查看、编辑、预览和发布。' : '首页内容用于站点首页落地页展示，支持手动补录、一键建站生成与静态发布。'; ?></div>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
    (function () {
        var checkAll = document.getElementById('content-check-all');
        if (!checkAll) {
            return;
        }
        var items = Array.prototype.slice.call(document.querySelectorAll('.content-check-item'));
        var syncState = function () {
            var checkedCount = items.filter(function (item) { return item.checked; }).length;
            checkAll.checked = items.length > 0 && checkedCount === items.length;
            checkAll.indeterminate = checkedCount > 0 && checkedCount < items.length;
        };
        checkAll.addEventListener('change', function () {
            items.forEach(function (item) {
                item.checked = checkAll.checked;
            });
            syncState();
        });
        items.forEach(function (item) {
            item.addEventListener('change', syncState);
        });
    }());

    function beforeBatchSubmit(form) {
        try {
            // 清理之前可能注入的隐藏 ids
            Array.prototype.slice.call(form.querySelectorAll('input[type="hidden"][name="ids[]"]')).forEach(function (el) {
                el.parentNode.removeChild(el);
            });
            var checked = document.querySelectorAll('.content-check-item:checked');
            if (!checked || checked.length === 0) { alert('请先勾选需要处理的内容。'); return false; }
            checked.forEach(function (el) {
                var hidden = document.createElement('input');
                hidden.type = 'hidden';
                hidden.name = 'ids[]';
                hidden.value = el.value;
                form.appendChild(hidden);
            });
            return true;
        } catch (e) {
            alert('提交失败：' + e.message);
            return false;
        }
    }
</script>
<!-- 批量发布进度弹窗（置于 body 顶层，确保居中） -->
<div id="batchPublishModal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; z-index:99999; background:rgba(0,0,0,0.45); display:none; align-items:center; justify-content:center;">
    <div style="position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:#fff; border-radius:16px; padding:32px 36px; width:520px; max-width:92vw; box-shadow:0 20px 60px rgba(0,0,0,0.18); z-index:100000;">
        <h3 id="batchModalTitle" style="margin:0 0 6px; font-size:18px; color:#1e293b;">批量静态发布</h3>
        <p id="batchStatusText" style="margin:0 0 18px; font-size:14px; color:#64748b;">准备中...</p>
        <div style="background:#f1f5f9; border-radius:8px; height:10px; overflow:hidden; margin-bottom:10px;">
            <div id="batchProgressBar" style="height:100%; width:0%; background:linear-gradient(90deg,#6366f1,#818cf8); border-radius:8px; transition:width 0.3s;"></div>
        </div>
        <div style="display:flex; justify-content:space-between; font-size:13px; color:#94a3b8; margin-bottom:16px;">
            <span id="batchProgressLabel">0 / 0</span>
            <span id="batchProgressPercent">0%</span>
        </div>
        <div id="batchLogWrap" style="max-height:160px; overflow-y:auto; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:10px 14px; font-size:12.5px; line-height:1.7; color:#475569; margin-bottom:18px;"></div>
        <div style="display:flex; gap:10px; justify-content:flex-end;">
            <button id="batchCancelBtn" class="btn-ghost" type="button" onclick="cancelBatchPublish()">取消</button>
            <button id="batchCloseBtn" class="btn-soft" type="button" onclick="closeBatchPublish()" style="display:none;">关闭</button>
        </div>
    </div>
</div>
</body>
</html>
