<?php

/**
 * @id 30
 * @name 文章防误删保护器
 * @version 1.0.0
 * @description 管理系统文章的删除保护列表，可自由添加或移除保护，防止重要文章被误删除
 * @price 0
 * @type 工具
 * @width 700
 * @height 500
 * @thumbnail /img/id30.png
 */

$plugin_identifier = '30_articleprotect';
$plugin_json_file = __DIR__ . '/Plugin.json';

function getAllArticles($page = 1, $page_size = 20, $search = '')
{
    global $conn;
    $offset = ($page - 1) * $page_size;
    $params = [];
    $where = '';

    if (!empty($search)) {
        $where = "WHERE title LIKE ?";
        $params[] = '%' . $search . '%';
    }

    $sql = "SELECT id, title, category_id, status, created_at FROM posts $where ORDER BY id DESC LIMIT ? OFFSET ?";
    $params[] = $page_size;
    $params[] = $offset;

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        return ['articles' => [], 'total' => 0];
    }

    $types = str_repeat('s', count($params) - 2) . 'ii';
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    $articles = [];
    while ($row = $result->fetch_assoc()) {
        $articles[] = [
            'id' => $row['id'],
            'title' => $row['title'],
            'category_id' => $row['category_id'],
            'status' => $row['status'],
            'created_at' => $row['created_at']
        ];
    }

    $total_sql = "SELECT COUNT(*) FROM posts $where";
    $total_stmt = $conn->prepare($total_sql);
    if ($total_stmt) {
        if (!empty($search)) {
            $total_stmt->bind_param('s', $params[0]);
        }
        $total_stmt->execute();
        $total_result = $total_stmt->get_result();
        $total = $total_result->fetch_row()[0];
    } else {
        $total = 0;
    }

    return ['articles' => $articles, 'total' => $total];
}

function getProtectedArticles($file)
{
    if (!file_exists($file)) {
        return [];
    }
    $data = json_decode(file_get_contents($file), true);
    return isset($data['protected_articles']) ? $data['protected_articles'] : array();
}

function saveProtectedArticles($file, $list)
{
    $data = file_exists($file) ? json_decode(file_get_contents($file), true) : array();
    if (!$data) $data = array();
    $data['protected_articles'] = $list;
    return file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX) !== false;
}

$action = isset($_POST['action']) ? $_POST['action'] : (isset($_POST['plugin_action']) ? $_POST['plugin_action'] : '');
if ($action) {
    header('Content-Type: application/json; charset=utf-8');
    $article_id = isset($_POST['article_id']) ? intval($_POST['article_id']) : 0;

    switch ($action) {
        case 'add_protection':
            if (empty($article_id)) {
                echo json_encode(['success' => false, 'message' => '文章ID不能为空']);
                exit;
            }
            $protected = getProtectedArticles($plugin_json_file);
            foreach ($protected as $item) {
                if ($item['id'] === $article_id) {
                    echo json_encode(['success' => false, 'message' => '该文章已在保护列表中']);
                    exit;
                }
            }
            $protected[] = ['id' => $article_id, 'title' => htmlspecialchars(isset($_POST['title']) ? $_POST['title'] : '')];
            echo json_encode(['success' => saveProtectedArticles($plugin_json_file, $protected), 'message' => '添加保护成功']);
            exit;

        case 'remove_protection':
            if (empty($article_id)) {
                echo json_encode(['success' => false, 'message' => '文章ID不能为空']);
                exit;
            }
            $protected = getProtectedArticles($plugin_json_file);
            $new_protected = array_filter($protected, function ($item) use ($article_id) {
                return $item['id'] !== $article_id;
            });
            echo json_encode(['success' => saveProtectedArticles($plugin_json_file, array_values($new_protected)), 'message' => '移除保护成功']);
            exit;

        case 'get_protection_list':
            $list = getProtectedArticles($plugin_json_file);
            $ids = [];
            foreach ($list as $it) {
                if (isset($it['id']) && is_numeric($it['id'])) $ids[] = intval($it['id']);
            }
            $dbArticles = [];
            if (!empty($ids) && isset($conn) && $conn instanceof mysqli) {
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $sql = "SELECT id, title FROM posts WHERE id IN ($placeholders)";
                $stmt = $conn->prepare($sql);
                if ($stmt) {
                    $types = str_repeat('i', count($ids));
                    $stmt->bind_param($types, ...$ids);
                    $stmt->execute();
                    $res = $stmt->get_result();
                    while ($row = $res->fetch_assoc()) {
                        $dbArticles[intval($row['id'])] = $row['title'];
                    }
                    $stmt->close();
                }
            }
            foreach ($list as &$it) {
                $pid = isset($it['id']) ? intval($it['id']) : 0;
                if ($pid > 0 && isset($dbArticles[$pid])) {
                    $it['exists'] = true;
                    $it['title'] = $dbArticles[$pid]; // 实时使用数据库中的最新标题
                } else {
                    $it['exists'] = false;
                }
            }
            unset($it);
            echo json_encode(['success' => true, 'list' => $list], JSON_UNESCAPED_UNICODE);
            exit;

        case 'get_articles':
            $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
            $search = isset($_POST['search']) ? trim($_POST['search']) : '';
            $result = getAllArticles($page, 20, $search);
            echo json_encode(['success' => true, 'articles' => $result['articles'], 'total' => $result['total']]);
            exit;
    }
}

$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$article_result = getAllArticles($page, 20, $search);
$all_articles = $article_result['articles'];
$total_articles = $article_result['total'];
$total_pages = ceil($total_articles / 20);

$protected_list = getProtectedArticles($plugin_json_file);
$protected_ids = array_map(function ($item) {
    return $item['id'];
}, $protected_list);
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>文章保护管理</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #fff;
            padding: 15px;
            margin: 0;
        }

        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }

        ::-webkit-scrollbar-track {
            background: #f0f0f0;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb {
            background: #009688;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #0fa597;
        }

        .container {
            max-width: 760px;
            margin: 0 auto;
        }

        .header {
            background: #fff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            border: 1px solid #e8e8e8;
            margin-right: 10px;
        }

        .header h2 {
            font-size: 16px;
            color: #333;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .header p {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
            margin: 0;
        }

        .stats {
            display: flex;
            gap: 15px;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #e8e8e8;
        }

        .stat-item {
            display: flex;
            align-items: center;
            gap: 5px;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 4px;
            transition: background 0.2s;
        }

        .stat-item:hover {
            background: #f0f0f0;
        }

        .stat-item.active {
            background: #e6f7ff;
        }

        .stat-label {
            font-size: 12px;
            color: #666;
        }

        .stat-value {
            font-size: 14px;
            font-weight: 600;
            color: #009688;
        }

        .search-bar {
            margin-top: 10px;
            display: flex;
            gap: 10px;
        }

        .search-input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 14px;
        }

        .search-input:focus {
            outline: none;
            border-color: #009688;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
        }

        .search-btn {
            padding: 0 16px;
            background: #009688;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s;
        }

        .search-btn:hover {
            background: #0fa597;
        }

        .article-list {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            border: 1px solid #e8e8e8;
            overflow: hidden;
            margin-right: 10px;
        }

        .list-header {
            display: flex;
            background: #fafafa;
            padding: 8px 15px;
            border-bottom: 1px solid #e8e8e8;
            font-size: 12px;
            font-weight: 500;
            color: #333;
        }

        .col-check {
            width: 35px;
        }

        .col-id {
            width: 60px;
            font-size: 12px;
            color: #999;
        }

        .col-title {
            flex: 1;
            font-size: 13px;
            color: #333;
        }

        .col-action {
            width: 80px;
            text-align: center;
        }

        .article-item {
            display: flex;
            align-items: center;
            height: 50px;
            padding: 0 15px;
            border-bottom: 1px solid #f0f0f0;
            transition: background 0.2s;
        }

        .article-item:last-child {
            border-bottom: none;
        }

        .article-item:hover {
            background: #f5f5f5;
        }

        .col-check input[type="checkbox"] {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }

        .btn-toggle {
            padding: 4px 10px;
            border: none;
            border-radius: 4px;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .btn-protect {
            background: #8c8c8c;
            color: #fff;
        }

        .btn-protect:hover {
            background: #595959;
        }

        .btn-unprotect {
            background: #009688;
            color: #fff;
        }

        .btn-unprotect:hover {
            background: #0fa597;
        }

        .protected-badge,
        .normal-badge,
        .missing-badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            margin-left: 5px;
            color: #fff;
        }

        .protected-badge {
            background: #009688;
        }

        .normal-badge {
            background: #8c8c8c;
        }

        .missing-badge {
            background: #f44336;
        }

        .legend {
            display: flex;
            gap: 20px;
            margin-top: 10px;
            padding: 10px 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            border: 1px solid #e8e8e8;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: #666;
        }

        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 2px;
        }

        .legend-normal {
            background: #8c8c8c;
        }

        .legend-protected {
            background: #009688;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 5px;
            margin-top: 15px;
            padding: 10px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            border: 1px solid #e8e8e8;
        }

        .page-btn {
            padding: 4px 10px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            transition: all 0.2s;
        }

        .page-btn:hover {
            border-color: #009688;
            color: #009688;
        }

        .page-btn.active {
            background: #009688;
            color: #fff;
            border-color: #009688;
        }

        .page-btn:disabled {
            background: #f5f5f5;
            color: #999;
            border-color: #d9d9d9;
            cursor: not-allowed;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <p>管理哪些文章不可删除。被保护的文章在点击删除时会提示"该文章已被保护，无法删除"。</p>
            <div class="stats">
                <div class="stat-item" onclick="filterArticles('all')">
                    <span class="stat-label">总文章数：</span>
                    <span class="stat-value" id="stat-total"><?php echo $total_articles; ?></span>
                </div>
                <div class="stat-item" onclick="filterArticles('protected')">
                    <span class="stat-label">受保护：</span>
                    <span class="stat-value" id="stat-protected" style="color:#009688"><?php echo count($protected_list); ?></span>
                </div>
                <div class="stat-item" onclick="filterArticles('normal')">
                    <span class="stat-label">未保护：</span>
                    <span class="stat-value" id="stat-normal" style="color:#8c8c8c"><?php echo $total_articles - count($protected_list); ?></span>
                </div>
            </div>
            <div class="search-bar">
                <input type="text" id="search-input" class="search-input" placeholder="搜索文章标题..." value="<?php echo htmlspecialchars($search); ?>">
                <button class="search-btn" onclick="performSearch()">搜索</button>
            </div>
        </div>
        <div class="article-list">
            <div class="list-header">
                <div class="col-check">保护</div>
                <div class="col-id">ID</div>
                <div class="col-title">文章标题</div>
                <div class="col-action">操作</div>
            </div>
            <?php foreach ($all_articles as $article):
                $is_protected = in_array($article['id'], $protected_ids);
                $item_class = $is_protected ? 'protected' : 'normal';
            ?>
                <div class="article-item <?php echo $item_class; ?>" data-id="<?php echo $article['id']; ?>">
                    <div class="col-check">
                        <input type="checkbox" <?php echo $is_protected ? 'checked' : ''; ?> onchange="toggleProtection('<?php echo $article['id']; ?>','<?php echo htmlspecialchars($article['title']); ?>',this)">
                    </div>
                    <div class="col-id"><?php echo $article['id']; ?></div>
                    <div class="col-title">
                        <?php echo htmlspecialchars($article['title']); ?>
                        <?php if ($is_protected): ?><span class="protected-badge">保护</span>
                        <?php else: ?><span class="normal-badge">可删除</span><?php endif; ?>
                    </div>
                    <div class="col-action">
                        <?php if ($is_protected): ?><button class="btn-toggle btn-unprotect" onclick="removeProtection('<?php echo $article['id']; ?>')">移除保护</button>
                        <?php else: ?><button class="btn-toggle btn-protect" onclick="addProtection('<?php echo $article['id']; ?>','<?php echo htmlspecialchars($article['title']); ?>')">添加保护</button><?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php if ($total_pages > 1): ?>
            <div class="pagination">
                <button class="page-btn" onclick="goToPage(1)" <?php echo $page == 1 ? 'disabled' : ''; ?>>首页</button>
                <button class="page-btn" onclick="goToPage(<?php echo $page - 1; ?>)" <?php echo $page == 1 ? 'disabled' : ''; ?>>上一页</button>
                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                    <button class="page-btn <?php echo $i == $page ? 'active' : ''; ?>" onclick="goToPage(<?php echo $i; ?>)"><?php echo $i; ?></button>
                <?php endfor; ?>
                <button class="page-btn" onclick="goToPage(<?php echo $page + 1; ?>)" <?php echo $page == $total_pages ? 'disabled' : ''; ?>>下一页</button>
                <button class="page-btn" onclick="goToPage(<?php echo $total_pages; ?>)" <?php echo $page == $total_pages ? 'disabled' : ''; ?>>尾页</button>
            </div>
        <?php endif; ?>
        <div class="legend">
            <div class="legend-item">
                <div class="legend-color legend-normal"></div><span>未保护（可删除）</span>
            </div>
            <div class="legend-item">
                <div class="legend-color legend-protected"></div><span>已保护（不可删除）</span>
            </div>
        </div>
    </div>
    <script src="../assets/js/toast.js"></script>
    <script>
        let currentFilter = 'all';
        let currentView = 'all';
        let protectedCount = <?php echo count($protected_list); ?>;
        let totalCount = <?php echo $total_articles; ?>;
        let protectedCache = [];

        function updateStats(protectedDelta) {
            protectedCount += protectedDelta;
            document.getElementById('stat-protected').textContent = protectedCount;
            document.getElementById('stat-normal').textContent = totalCount - protectedCount;
        }

        function setActiveStat(filter) {
            document.querySelectorAll('.stat-item').forEach((item, i) => item.classList.toggle('active', (filter === 'all' && i === 0) || (filter === 'protected' && i === 1) || (filter === 'normal' && i === 2)));
        }

        function applyDomFilter(filter) {
            document.querySelectorAll('.article-item').forEach(item => {
                item.style.display = filter === 'all' ? 'flex' : (filter === 'protected' ? item.classList.contains('protected') : item.classList.contains('normal')) ? 'flex' : 'none';
            });
        }

        function filterArticles(filter) {
            setActiveStat(filter);
            currentFilter = filter;
            if (filter === 'protected') {
                currentView = 'protected';
                loadProtectedList(document.getElementById('search-input').value || '');
                return;
            }

            if (currentView !== 'all') {
                currentView = 'all';
                loadArticles(1, document.getElementById('search-input').value || '', filter);
                return;
            }
            applyDomFilter(filter);
        }

        function updateArticleItemStyle(id, status, title) {
            const item = document.querySelector('.article-item[data-id="' + id + '"]');
            if (!item) return;
            const checkbox = item.querySelector('.col-check input[type="checkbox"]');
            const titleCol = item.querySelector('.col-title'),
                actionCol = item.querySelector('.col-action');
            item.classList.remove('normal', 'protected');
            item.classList.add(status);
            if (checkbox) checkbox.checked = (status === 'protected');
            const badgeHtml = status === 'protected' ? '<span class="protected-badge">保护</span>' : '<span class="normal-badge">可删除</span>';
            const titleText = titleCol.childNodes[0].textContent.trim();
            titleCol.innerHTML = titleText + badgeHtml;
            actionCol.innerHTML = status === 'protected' ?
                '<button class="btn-toggle btn-unprotect" onclick="removeProtection(\'' + id + '\')">移除保护</button>' :
                '<button class="btn-toggle btn-protect" onclick="addProtection(\'' + id + '\',\'' + titleText + '\')">添加保护</button>';
            if (currentFilter !== 'all') {
                if ((currentFilter === 'protected' && status === 'normal') || (currentFilter === 'normal' && status === 'protected')) {
                    item.style.display = 'none';
                }
            }
        }

        function toggleProtection(id, title, checkbox) {
            checkbox.checked ? addProtection(id, title) : removeProtection(id);
        }

        function addProtection(id, title) {
            fetch('/admin/Plugin.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: 'plugin=30_articleprotect&plugin_action=add_protection&article_id=' + encodeURIComponent(id) + '&title=' + encodeURIComponent(title)
                })
                .then(r => r.json())
                .then(data => {
                    showToast(data.message, data.success ? 'success' : 'error');
                    if (data.success) {
                        protectedIdSet.add(parseInt(id, 10));
                        updateArticleItemStyle(id, 'protected', title);
                        updateStats(1);
                        if (currentView === 'protected') {
                            loadProtectedList(document.getElementById('search-input').value || '');
                        }
                    }
                })
                .catch(err => showToast('请求失败: ' + err.message, 'error'));
        }

        function removeProtection(id) {
            fetch('/admin/Plugin.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: 'plugin=30_articleprotect&plugin_action=remove_protection&article_id=' + encodeURIComponent(id)
                })
                .then(r => r.json())
                .then(data => {
                    showToast(data.message, data.success ? 'success' : 'error');
                    if (data.success) {
                        protectedIdSet.delete(parseInt(id, 10));
                        updateArticleItemStyle(id, 'normal', '');
                        updateStats(-1);
                        if (currentView === 'protected') {
                            document.querySelector('.article-item[data-id="' + id + '"]')?.remove();
                        }
                    }
                })
                .catch(err => showToast('请求失败: ' + err.message, 'error'));
        }

        function performSearch() {
            const search = document.getElementById('search-input').value;
            if (currentView === 'protected') {
                loadProtectedList(search);
                return;
            }
            loadArticles(1, search);
        }

        function goToPage(page) {
            page = parseInt(page, 10) || 1;
            if (page < 1) page = 1;
            if (page > state.totalPages) page = state.totalPages;
            loadArticles(page, document.getElementById('search-input').value || '');
        }

        const state = {
            page: <?php echo intval($page); ?>,
            pageSize: 20,
            total: <?php echo intval($total_articles); ?>,
            totalPages: <?php echo intval(max(1, $total_pages)); ?>
        };

        const protectedIdSet = new Set(<?php echo json_encode(array_values($protected_ids), JSON_UNESCAPED_UNICODE); ?>);

        function renderList(articles) {
            const list = document.querySelector('.article-list');
            if (!list) return;
            while (list.firstChild) list.removeChild(list.firstChild);

            const header = document.createElement('div');
            header.className = 'list-header';
            header.innerHTML = '<div class="col-check">保护</div><div class="col-id">ID</div><div class="col-title">文章标题</div><div class="col-action">操作</div>';
            list.appendChild(header);

            (articles || []).forEach(article => {
                const id = String(article.id || '');
                const title = String(article.title || '');
                const isProtected = protectedIdSet.has(parseInt(id, 10));
                const exists = article && article.exists === false ? false : true;

                const item = document.createElement('div');
                item.className = 'article-item ' + (isProtected ? 'protected' : 'normal');
                item.dataset.id = id;

                const colCheck = document.createElement('div');
                colCheck.className = 'col-check';
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.checked = isProtected;
                checkbox.addEventListener('change', function () {
                    toggleProtection(id, title, this);
                });
                colCheck.appendChild(checkbox);

                const colId = document.createElement('div');
                colId.className = 'col-id';
                colId.textContent = id;

                const colTitle = document.createElement('div');
                colTitle.className = 'col-title';
                colTitle.appendChild(document.createTextNode(title));
                const badge = document.createElement('span');
                badge.className = isProtected ? 'protected-badge' : 'normal-badge';
                badge.textContent = isProtected ? '保护' : '可删除';
                colTitle.appendChild(badge);
                if (currentView === 'protected' && !exists) {
                    const missing = document.createElement('span');
                    missing.className = 'missing-badge';
                    missing.textContent = '文章不存在';
                    colTitle.appendChild(missing);
                }

                const colAction = document.createElement('div');
                colAction.className = 'col-action';
                const btn = document.createElement('button');
                btn.className = 'btn-toggle ' + (isProtected ? 'btn-unprotect' : 'btn-protect');
                btn.textContent = isProtected ? '移除保护' : '添加保护';
                btn.addEventListener('click', function () {
                    isProtected ? removeProtection(id) : addProtection(id, title);
                });
                colAction.appendChild(btn);

                item.appendChild(colCheck);
                item.appendChild(colId);
                item.appendChild(colTitle);
                item.appendChild(colAction);
                list.appendChild(item);
            });

            if (currentView === 'all' && currentFilter !== 'all') applyDomFilter(currentFilter);
        }

        function renderPagination() {
            const legend = document.querySelector('.legend');
            if (!legend) return;

            let pagination = document.querySelector('.pagination');
            if (!pagination) {
                pagination = document.createElement('div');
                pagination.className = 'pagination';
                legend.parentNode.insertBefore(pagination, legend);
            }
            pagination.style.display = state.totalPages > 1 ? '' : 'none';
            while (pagination.firstChild) pagination.removeChild(pagination.firstChild);
            if (state.totalPages <= 1) return;

            function addBtn(text, targetPage, disabled, active) {
                const b = document.createElement('button');
                b.className = 'page-btn' + (active ? ' active' : '');
                b.textContent = text;
                if (disabled) b.disabled = true;
                b.addEventListener('click', function () {
                    if (disabled) return;
                    goToPage(targetPage);
                });
                pagination.appendChild(b);
            }

            addBtn('首页', 1, state.page === 1, false);
            addBtn('上一页', state.page - 1, state.page === 1, false);
            const start = Math.max(1, state.page - 2);
            const end = Math.min(state.totalPages, state.page + 2);
            for (let i = start; i <= end; i++) addBtn(String(i), i, false, i === state.page);
            addBtn('下一页', state.page + 1, state.page === state.totalPages, false);
            addBtn('尾页', state.totalPages, state.page === state.totalPages, false);
        }

        function loadArticles(page, search, afterFilter) {
            const params = new URLSearchParams();
            params.set('plugin', '30_articleprotect');
            params.set('plugin_action', 'get_articles');
            params.set('page', String(page));
            params.set('search', String(search || ''));

            fetch('/admin/Plugin.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: params.toString()
                })
                .then(r => r.json())
                .then(data => {
                    if (!data || !data.success) {
                        showToast((data && data.message) ? data.message : '加载失败', 'error');
                        return;
                    }
                    state.page = page;
                    state.total = parseInt(data.total || 0, 10) || 0;
                    state.totalPages = Math.max(1, Math.ceil(state.total / state.pageSize));
                    totalCount = state.total;
                    document.getElementById('stat-total').textContent = String(state.total);
                    document.getElementById('stat-normal').textContent = String(Math.max(0, state.total - protectedCount));
                    renderList(data.articles || []);
                    renderPagination();
                    if (afterFilter && afterFilter !== 'all') {
                        currentFilter = afterFilter;
                        setActiveStat(afterFilter);
                        applyDomFilter(afterFilter);
                    }
                })
                .catch(err => showToast('请求失败: ' + err.message, 'error'));
        }

        function loadProtectedList(search) {
            const params = new URLSearchParams();
            params.set('plugin', '30_articleprotect');
            params.set('plugin_action', 'get_protection_list');

            fetch('/admin/Plugin.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: params.toString()
                })
                .then(r => r.json())
                .then(data => {
                    if (!data || !data.success) {
                        showToast((data && data.message) ? data.message : '加载失败', 'error');
                        return;
                    }
                    protectedCache = Array.isArray(data.list) ? data.list : [];
                    protectedIdSet.clear();
                    protectedCache.forEach(it => protectedIdSet.add(parseInt(it.id, 10)));

                    const kw = String(search || '').trim().toLowerCase();
                    const filtered = kw ? protectedCache.filter(it => String(it.title || '').toLowerCase().includes(kw) || String(it.id || '').includes(kw)) : protectedCache;
                    renderList(filtered);

                    const pagination = document.querySelector('.pagination');
                    if (pagination) pagination.style.display = 'none';
                })
                .catch(err => showToast('请求失败: ' + err.message, 'error'));
        }

        // 回车键搜索
        document.getElementById('search-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    </script>
</body>

</html>
<?php
function qk_articleprotect_tool($params = [])
{
    return '';
}
if (!isset($_POST['plugin'])) echo qk_articleprotect_tool([]);
?>
