<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$postAction = isset($_POST['action']) ? $_POST['action'] : $action;

// AJAX 批量操作（POST + ajax_action）
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    while (ob_get_level() > 0) { ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');
    $ajaxAct = $_POST['ajax_action'];

    if ($ajaxAct === 'delete') {
        $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
        $ids = json_decode($idsRaw, true);
        if (!is_array($ids)) { $ids = []; }
        $ids = array_map('intval', $ids);
        if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择要删除的项']); exit; }
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $db->query("DELETE FROM {$db->table('guestbook')} WHERE id IN ($placeholders)", $ids);
        echo json_encode(['code'=>200,'msg'=>'已删除 '.count($ids).' 项']); exit;
    }

    if ($ajaxAct === 'show') {
        $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
        $ids = json_decode($idsRaw, true);
        if (!is_array($ids)) { $ids = []; }
        $ids = array_map('intval', $ids);
        if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $db->query("UPDATE {$db->table('guestbook')} SET status=1, is_show=1 WHERE id IN ($placeholders)", $ids);
        echo json_encode(['code'=>200,'msg'=>'已通过审核']); exit;
    }

    if ($ajaxAct === 'hide') {
        $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
        $ids = json_decode($idsRaw, true);
        if (!is_array($ids)) { $ids = []; }
        $ids = array_map('intval', $ids);
        if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $db->query("UPDATE {$db->table('guestbook')} SET status=0, is_show=0 WHERE id IN ($placeholders)", $ids);
        echo json_encode(['code'=>200,'msg'=>'已隐藏']); exit;
    }
}

// POST 操作（单条）
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($postAction === 'reply') {

        $id = intval($_POST['id']);
        $reply = trim($_POST['reply'] ?? '');
        if (empty($reply)) {
            echo '<script>alert("回复内容不能为空");history.back();</script>';
            exit;
        }
        $now = time();
        $db->update('guestbook', ['reply'=>$reply, 'reply_time'=>$now, 'status'=>2, 'is_show'=>1], 'id=?', [$id]);
        @addLog('回复', '留言管理', '回复留言ID：' . $id);
        echo '<script>alert("回复成功");location.href="?act=guestbook"</script>';
        exit;
    }
    if ($action === 'delete') {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if ($id <= 0) {
            $raw = file_get_contents('php://input');
            parse_str($raw, $parsed);
            $id = isset($parsed['id']) ? intval($parsed['id']) : 0;
        }
        if ($id <= 0) { echo json_encode(['code'=>400,'msg'=>'无效ID']); exit; }
        $g = $db->fetch("SELECT title FROM {$db->table('guestbook')} WHERE id = ?", [$id]);
        $db->query("DELETE FROM {$db->table('guestbook')} WHERE id = ?", [$id]);
        @addLog('删除', '留言管理', '删除留言：' . ($g['title'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
    if ($action === 'approve') {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if ($id <= 0) {
            $raw = file_get_contents('php://input');
            parse_str($raw, $parsed);
            $id = isset($parsed['id']) ? intval($parsed['id']) : 0;
        }
        if ($id <= 0) { echo json_encode(['code'=>400,'msg'=>'无效ID']); exit; }
        $db->query("UPDATE {$db->table('guestbook')} SET status=1, is_show=1 WHERE id=?", [$id]);
        @addLog('审核', '留言管理', '审核通过留言ID：' . $id);
        echo json_encode(['code' => 200, 'msg' => '审核通过']);
        exit;
    }
}

if ($action === 'view') {
    $id = intval($_GET['id']);
    $item = $db->fetch("SELECT * FROM {$db->table('guestbook')} WHERE id = ?", [$id]);
    if (!$item): ?>
    <div style="padding:20px;text-align:center;color:#999;">留言不存在</div>
    <?php else: ?>
    <div style="font-size:14px;line-height:1.8;">
        <div style="display:flex;gap:12px;margin-bottom:16px;">
            <div style="flex:1;">
                <div style="color:#999;font-size:12px;margin-bottom:4px;">姓名</div>
                <div style="font-weight:600;"><?php echo htmlspecialchars($item['name']); ?></div>
            </div>
            <div style="flex:1;">
                <div style="color:#999;font-size:12px;margin-bottom:4px;">联系方式</div>
                <div style="font-weight:600;"><?php echo htmlspecialchars($item['phone'] ?? '-'); ?></div>
            </div>
            <div style="flex:1;">
                <div style="color:#999;font-size:12px;margin-bottom:4px;">提交时间</div>
                <div style="font-weight:600;"><?php echo date('Y-m-d H:i:s', $item['create_time']); ?></div>
            </div>
        </div>
        <div style="margin-bottom:16px;">
            <div style="color:#999;font-size:12px;margin-bottom:4px;">留言标题</div>
            <div style="font-weight:600;font-size:15px;"><?php echo htmlspecialchars($item['title']); ?></div>
        </div>
        <div style="margin-bottom:16px;">
            <div style="color:#999;font-size:12px;margin-bottom:4px;">留言内容</div>
            <div style="padding:14px;background:#f9f9f9;border-radius:8px;border:1px solid #eee;"><?php echo nl2br(htmlspecialchars($item['content'])); ?></div>
        </div>
        <?php if ($item['reply']): ?>
        <div style="margin-bottom:16px;">
            <div style="color:#999;font-size:12px;margin-bottom:4px;">管理员回复</div>
            <div style="padding:14px;background:#f0fdf4;border-radius:8px;border:1px solid #bbf7d0;color:#16a34a;">
                <?php echo nl2br(htmlspecialchars($item['reply'])); ?>
                <div style="margin-top:8px;font-size:12px;">回复时间：<?php echo $item['reply_time'] ? date('Y-m-d H:i', $item['reply_time']) : '-'; ?></div>
            </div>
        </div>
        <?php else: ?>
        <div style="padding:14px;background:#fffbeb;border-radius:8px;border:1px solid #fde68a;color:#92400e;font-size:13px;">暂无回复</div>
        <?php endif; ?>
    </div>
    <?php endif;
    exit;
}

if ($action === 'list') {
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $pageSize = 15;
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
    $where = '1=1';
    $params = [];
    if (!empty($keyword)) {
        $where .= ' AND (name LIKE ? OR title LIKE ? OR content LIKE ?)';
        $params = ['%'.$keyword.'%', '%'.$keyword.'%', '%'.$keyword.'%'];
    }
    $offset = ($page - 1) * $pageSize;
    $lists = $db->fetchAll("SELECT * FROM {$db->table('guestbook')} WHERE {$where} ORDER BY id DESC LIMIT {$offset}, {$pageSize}", $params);
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('guestbook')} WHERE {$where}", $params)['cnt'];
    $totalPages = ceil($total / $pageSize);
    $totalGuest = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('guestbook')}")['cnt'];
    $unread = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('guestbook')} WHERE status = 0")['cnt'];
    $statusMap = [0 => ['待审核', 'badge-warning'], 1 => ['已通过', 'badge-success'], 2 => ['已回复', 'badge-gray']];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon">
                    <svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                    </svg>
                </div>
                <div>
                    <h1>留言管理</h1>
                    <p style="font-size:12px;color:var(--gray-500);margin:0;">管理会员留言</p>
                </div>
            </div>
        </div>
        <div class="page-context-bar">
            <div class="page-context-item"><span class="page-context-label">留言总数</span><span class="page-context-value"><?php echo $totalGuest; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">待审核</span><span class="page-context-value"><?php echo $unread; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">分页设置</span><span class="page-context-value">每页 <?php echo $pageSize; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">批量能力</span><span class="page-context-value page-context-muted">通过、隐藏、删除</span></div>
        </div>
        <div class="filter-bar">
            <form method="get" style="display:flex;gap:12px;width:100%;">
                <input type="hidden" name="act" value="guestbook">
                <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索留言内容..." style="flex:1;">
                <button type="submit" class="btn btn-primary">
                    <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                </button>
                <?php if ($keyword): ?>
                <a href="?act=guestbook" class="btn btn-secondary">
                    <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-3.5"/></svg> 重置
                </a>
                <?php endif; ?>
            </form>
        </div>
        <div class="content-card">
            <?php if (empty($lists)): ?>
            <div class="empty-state">
                <div class="empty-icon">
                    <svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                    </svg>
                </div>
                <h3>暂无留言</h3>
                <p>还没有会员留言</p>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th class="id-cell" style="width:40px;"><input type="checkbox" id="checkAll" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th>
                        <th class="id-cell">ID</th>
                        <th>留言内容</th>
                        <th style="width:100px;">状态</th>
                        <th style="width:160px;">时间</th>
                        <th style="width:330px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <?php $st = $statusMap[$item['status']] ?? $statusMap[0]; ?>
                    <tr>
                        <td style="text-align:center;"><input type="checkbox" class="row-check" value="<?php echo $item['id']; ?>" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></td>
                        <td class="id-cell"><?php echo $item['id']; ?></td>
                        <td>
                            <div style="font-weight:500;color:var(--gray-800);"><?php echo htmlspecialchars($item['name']); ?> · <?php echo htmlspecialchars($item['title']); ?></div>
                            <div style="font-size:12px;color:var(--gray-500);margin-top:4px;"><?php echo mb_strlen($item['content']) > 60 ? mb_substr(htmlspecialchars($item['content']), 0, 60) . '...' : htmlspecialchars($item['content']); ?></div>
                            <?php if ($item['reply']): ?>
                            <div style="font-size:12px;color:var(--success);margin-top:6px;padding:8px;background:var(--success-bg);border-radius:6px;">
                                <svg style="width:13px;height:13px;vertical-align:middle;margin-right:3px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>
                                管理员回复：<?php echo htmlspecialchars($item['reply']); ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td><span class="badge <?php echo $st[1]; ?>"><?php echo $st[0]; ?></span></td>
                        <td style="font-size:12px;color:var(--gray-500);">
                            <?php echo date('Y-m-d H:i', $item['create_time']); ?><br>
                            <?php if ($item['reply_time']) { echo '<span style="color:var(--success);">'.date('m-d H:i', $item['reply_time']).'</span>'; } ?>
                        </td>
                        <td style="width:330px;">
                            <div class="btn-group" style="display:flex;gap:6px;align-items:center;width:330px;">
                                <button type="button" onclick="viewGuest(<?php echo $item['id']; ?>)" class="btn btn-ghost" title="查看" style="display:inline-flex;align-items:center;gap:5px;">
                                    <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
                                    </svg>查看
                                </button>
                                <?php if ($item['status'] == 0): ?>
                                <button type="button" onclick="approveGuest(<?php echo $item['id']; ?>)" class="btn btn-primary" title="通过审核" style="display:inline-flex;align-items:center;gap:5px;">
                                    <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <polyline points="20 6 9 17 4 12"/>
                                    </svg>通过
                                </button>
                                <?php endif; ?>
                                <button type="button" onclick="showReply(<?php echo $item['id']; ?>,'<?php echo addslashes($item['reply'] ?? ''); ?>')" class="btn btn-primary" title="回复" style="display:inline-flex;align-items:center;gap:5px;">
                                    <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
                                    </svg>回复
                                </button>
                                <button type="button" onclick="delGuest(<?php echo $item['id']; ?>)" class="btn btn-ghost" style="color:#EF4444;display:inline-flex;align-items:center;gap:5px;" title="删除">
                                    <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                        <polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                                    </svg>删除
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div style="padding:12px 16px;border-top:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
                <div style="font-size:13px;color:var(--gray-500);">已选中 <span id="selectedCount">0</span> 项</div>
                <div style="display:flex;gap:8px;">
                    <button type="button" onclick="batchAction('show')" class="btn btn-sm btn-gray" style="display:inline-flex;align-items:center;gap:5px;">
                        <svg style="width:13px;height:13px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> 批量通过
                    </button>
                    <button type="button" onclick="batchAction('hide')" class="btn btn-sm btn-gray" style="display:inline-flex;align-items:center;gap:5px;">
                        <svg style="width:13px;height:13px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="1"/><circle cx="12" cy="5" r="1"/><circle cx="12" cy="19" r="1"/></svg> 批量隐藏
                    </button>
                    <button type="button" onclick="batchAction('delete')" class="btn btn-sm btn-danger" style="display:inline-flex;align-items:center;gap:5px;">
                        <svg style="width:13px;height:13px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                        </svg> 批量删除
                    </button>
                </div>
            </div>
            <?php if ($totalPages > 1): ?>
            <div class="pagination" style="padding:16px;">
                <?php if ($page > 1): ?><a href="?act=guestbook&page=<?php echo $page-1; ?>">上一页</a><?php endif; ?>
                <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                <a href="?act=guestbook&page=<?php echo $i; ?>" <?php echo $i==$page?'class="active"':''; ?>><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?><a href="?act=guestbook&page=<?php echo $page+1; ?>">下一页</a><?php endif; ?>
            </div>
            <?php endif; endif; ?>
        </div>
    </div>

    <!-- 查看弹窗 -->
    <div id="viewModal" class="modal">
        <div class="modal-content" style="max-width:600px;">
            <div class="modal-header"><h3>留言详情</h3><button onclick="closeViewModal()" class="modal-close">×</button></div>
            <div class="modal-body" id="viewModalBody" style="padding:20px;"></div>
        </div>
    </div>

    <!-- 回复弹窗 -->
    <div id="replyModal" class="modal">
        <div class="modal-content" style="max-width:500px;">
            <div class="modal-header"><h3>回复留言</h3><button onclick="closeModal()" class="modal-close">×</button></div>
            <form method="post">
                <input type="hidden" name="action" value="reply">
                <input type="hidden" name="id" id="replyId">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                <div class="modal-body">
                    <textarea name="reply" id="replyContent" class="form-control" rows="5" placeholder="请输入回复内容" required></textarea>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success" style="display:inline-flex;align-items:center;gap:5px;">
                        <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> 提交回复
                    </button>
                    <button type="button" onclick="closeModal()" class="btn btn-secondary">取消</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    // 全选
    var checkAll = document.getElementById('checkAll');
    if (checkAll) {
        checkAll.addEventListener('change', function() {
            document.querySelectorAll('.row-check').forEach(function(cb) { cb.checked = checkAll.checked; });
            updateSelected();
        });
    }
    document.querySelectorAll('.row-check').forEach(function(cb) {
        cb.addEventListener('change', updateSelected);
    });
    function updateSelected() {
        var checked = document.querySelectorAll('.row-check:checked').length;
        var el = document.getElementById('selectedCount');
        if (el) el.textContent = checked;
    }

    // 查看
    function viewGuest(id) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '?act=guestbook&action=view&id=' + id, true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                document.getElementById('viewModalBody').innerHTML = xhr.responseText;
                document.getElementById('viewModal').classList.add('show');
            } else {
                alert('加载失败');
            }
        };
        xhr.onerror = function() { alert('网络错误'); };
        xhr.send();
    }
    function closeViewModal() { document.getElementById('viewModal').classList.remove('show'); }

    // 回复
    function showReply(id, reply) {
        document.getElementById('replyId').value = id;
        document.getElementById('replyContent').value = reply || '';
        document.getElementById('replyModal').classList.add('show');
    }
    function closeModal() { document.getElementById('replyModal').classList.remove('show'); }

    // 删除
    function delGuest(id) {
        if (!confirm('确定删除这条留言？')) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=guestbook&action=delete', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    var d = JSON.parse(xhr.responseText);
                    alert(d.msg);
                    if (d.code === 200) location.reload();
                } catch(e) { alert('删除失败'); }
            }
        };
        xhr.onerror = function() { alert('网络错误'); };
        xhr.send('id=' + encodeURIComponent(id) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }

    // 审核通过
    function approveGuest(id) {
        if (!confirm('确定通过审核？')) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=guestbook&action=approve', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    var d = JSON.parse(xhr.responseText);
                    alert(d.msg);
                    if (d.code === 200) location.reload();
                } catch(e) { alert('操作失败'); }
            } else { alert('操作失败，HTTP ' + xhr.status); }
        };
        xhr.onerror = function() { alert('网络错误'); };
        xhr.send('id=' + encodeURIComponent(id) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }

    // 批量操作
    function batchAction(act) {
        var ids = [];
        document.querySelectorAll('.row-check:checked').forEach(function(cb) { ids.push(cb.value); });
        if (ids.length === 0) { alert('请先选择要操作的项目'); return; }
        var confirmMsg = act === 'delete' ? '确定批量删除选中的 ' + ids.length + ' 条留言？' :
                         act === 'show' ? '确定批量通过审核选中的 ' + ids.length + ' 条留言？' :
                         '确定批量隐藏选中的 ' + ids.length + ' 条留言？';
        if (!confirm(confirmMsg)) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=guestbook', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    var d = JSON.parse(xhr.responseText);
                    alert(d.msg);
                    if (d.code === 200) location.reload();
                } catch(e) { alert('操作失败'); }
            } else { alert('操作失败，HTTP ' + xhr.status); }
        };
        xhr.onerror = function() { alert('网络错误'); };
        xhr.send('ajax_action=' + encodeURIComponent(act) + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }

    // ESC 关闭弹窗
    document.addEventListener('keydown', function(e) { if (e.key === 'Escape') { closeModal(); closeViewModal(); } });
    </script>
    <style>
    .page-context-bar{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:16px;}
    .page-context-item{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:14px 16px;}
    .page-context-label{display:block;font-size:12px;color:#94a3b8;margin-bottom:6px;}
    .page-context-value{display:block;font-size:14px;font-weight:700;color:#1e293b;line-height:1.6;}
    .page-context-muted{color:#475569;font-weight:600;}
    .modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;align-items:center;justify-content:center;}
    .modal.show{display:flex;}
    .modal-content{background:#fff;border-radius:12px;width:90%;max-width:600px;box-shadow:0 20px 25px rgba(0,0,0,0.1);}
    .modal-header{padding:18px 24px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;}
    .modal-header h3{font-size:16px;font-weight:600;color:var(--gray-800);}
    .modal-close{width:32px;height:32px;background:var(--gray-100);border:none;border-radius:6px;cursor:pointer;font-size:18px;}
    .modal-body{padding:24px;}
    .modal-footer{padding:16px 24px;border-top:1px solid var(--border);display:flex;justify-content:flex-end;gap:10px;}
    .btn-danger{background:#EF4444;color:#fff;border:none;}
    .btn-danger:hover{background:#DC2626;}
    .btn-sm{padding:5px 12px;font-size:12px;}
    .btn-gray{background:var(--gray-100);color:var(--gray-700);border:none;}
    .btn-gray:hover{background:var(--gray-200);}
    @media (max-width: 1200px){.page-context-bar{grid-template-columns:repeat(2,minmax(0,1fr));}}
    @media (max-width: 768px){.page-context-bar{grid-template-columns:1fr;}}
    </style>
    <?php
}
?>
