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



    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
        requireAdminCsrfToken(true);
        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('article')} 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('article')} SET status=1, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $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('article')} SET status=0, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已隐藏']); exit;
        }
    }


$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$channelId = isset($_GET['channel_id']) ? intval($_GET['channel_id']) : 0;
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$pageSize = 15;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        requireAdminCsrfToken();
        $id = intval($_POST['id']);
        $data = [
            'channel_id' => intval($_POST['channel_id']),
            'title' => trim($_POST['title']),
            'short_title' => trim($_POST['short_title']),
            'litpic' => trim($_POST['litpic']),
            'flag' => implode(',', isset($_POST['flag']) ? $_POST['flag'] : []),
            'tags' => trim($_POST['tags']),
            'source' => trim($_POST['source']),
            'author' => trim($_POST['author']),
            'summary' => trim($_POST['summary']),
            'content' => isset($_POST['content']) ? $_POST['content'] : '',
            'seo_title' => trim($_POST['seo_title']),
            'seo_keywords' => trim($_POST['seo_keywords']),
            'seo_description' => trim($_POST['seo_description']),
            'sort_order' => intval($_POST['sort_order']),
            'status' => isset($_POST['status']) ? 1 : 0,
            'release_time' => isset($_POST['release_time']) && !empty($_POST['release_time']) ? strtotime($_POST['release_time']) : time(),
            'update_time' => time()
        ];
        if ($id > 0) {
            $db->update('article', $data, 'id = ?', [$id]);
            addLog('修改', '文章管理', '修改文章 ' . $data['title']);
        } else {
            $data['create_time'] = time();
            $db->insert('article', $data);
            addLog('添加', '文章管理', '添加文章 ' . $data['title']);
        }
        echo '<script>alert("保存成功");location.href="?act=article"</script>';
        exit;
    }
    if ($action === 'delete') {
        requireAdminCsrfToken(true);
        $id = intval($_POST['id']);
        $article = $db->fetch("SELECT title FROM {$db->table('article')} WHERE id = ?", [$id]);
        $db->delete('article', 'id = ?', [$id]);
        addLog('删除', '文章管理', '删除文章 ' . ((isset($article['title']) ? $article['title'] : $id)));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $where = '1=1';
    $params = [];
    if ($channelId > 0) { $where .= ' AND channel_id = ?'; $params[] = $channelId; }
    if (!empty($keyword)) { $where .= ' AND (title LIKE ? OR tags LIKE ?)'; $params[] = '%'.$keyword.'%'; $params[] = '%'.$keyword.'%'; }
    if ($status !== '') { $where .= ' AND status = ?'; $params[] = intval($status); }
    $offset = ($page - 1) * $pageSize;
    $articles = $db->fetchAll("SELECT * FROM {$db->table('article')} WHERE {$where} ORDER BY id DESC LIMIT {$offset}, {$pageSize}", $params);
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('article')} WHERE {$where}", $params)['cnt'];
    $totalPages = ceil($total / $pageSize);
    $channels = $db->fetchAll("SELECT id, channel_name FROM {$db->table('channel')} WHERE channel_type = 1 ORDER BY list_order ASC");
    $totalArticles = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('article')}")['cnt'];
    $publishedCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('article')} WHERE status = 1")['cnt'];
    $draftCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('article')} WHERE status = 0")['cnt'];
    $todayCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('article')} WHERE FROM_UNIXTIME(create_time, '%Y-%m-%d') = CURDATE()")['cnt'];
    ?>
    <div class="stats-grid">
        <div class="stat-card"><div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg></div><div class="stat-info"><div class="stat-value"><?php echo $totalArticles; ?></div><div class="stat-label">文章总数</div></div></div>
        <div class="stat-card"><div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div><div class="stat-info"><div class="stat-value"><?php echo $publishedCount; ?></div><div class="stat-label">显示</div></div></div>
        <div class="stat-card"><div class="stat-icon" style="background:#fffbeb;color:#f59e0b;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg></div><div class="stat-info"><div class="stat-value"><?php echo $draftCount; ?></div><div class="stat-label">隐藏</div></div></div>
        <div class="stat-card"><div class="stat-icon" style="background:#fef2f2;color:#ef4444;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg></div><div class="stat-info"><div class="stat-value"><?php echo $todayCount; ?></div><div class="stat-label">今日更新</div></div></div>
    </div>
    <div class="filter-bar">
        <form method="get" style="display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
            <input type="hidden" name="act" value="article">
            <select name="channel_id" class="form-control" style="width:160px;">
                <option value="0">全部分类</option>
                <?php foreach ($channels as $ch): ?>
                <option value="<?php echo $ch['id']; ?>" <?php echo $channelId == $ch['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($ch['channel_name']); ?></option>
                <?php endforeach; ?>
            </select>
            <input type="text" name="keyword" class="form-control" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索标题/标签" style="width:200px;">
            <select name="status" class="form-control" style="width:120px;">
                <option value="">全部状态</option>
                <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>显示</option>
                <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>隐藏</option>
            </select>
            <button type="submit" class="btn btn-primary">筛选</button>
            <a href="?act=article&action=add" class="btn btn-success">+ 添加文章</a>
        </form>
    </div>
    <div class="content-card">
        <?php if (empty($articles)): ?>
        <div class="empty-state"><div class="empty-icon"><svg style="width:40px;height:40px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="10" y1="12" x2="14" y2="16"/><line x1="14" y1="12" x2="10" y2="16"/></svg></div><h3>暂无文章</h3><p>创建第一篇文章吧</p></div>
        <?php else: ?>
        <table class="data-table">
            <thead><tr><th style="width:40px;"><input type="checkbox" id="checkAll" onchange="toggleCheckAll(this)" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th><th style="width:50px;">ID</th><th style="width:400px;">标题</th><th style="width:100px;">所属栏目</th><th style="width:100px;">属性</th><th style="width:140px;">发布时间</th><th style="width:60px;">点击</th><th style="width:100px;">状态</th><th style="width:250px;">操作</th></tr></thead>
            <tbody>
                <?php foreach ($articles as $item): ?>
                <?php $channel = $db->fetch("SELECT channel_name FROM {$db->table('channel')} WHERE id = ?", [$item['channel_id']]); $flags = $item['flag'] ? explode(',', $item['flag']) : []; ?>
                <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>
                        <?php if ($item['litpic']): ?><img src="<?php echo htmlspecialchars($item['litpic']); ?>" style="width:40px;height:30px;object-fit:cover;border-radius:4px;margin-right:8px;vertical-align:middle;"><?php endif; ?>
                        <a href="/public/index.php?m=article&id=<?php echo $item['id']; ?>" target="_blank" style="color:#334155;text-decoration:none;"><?php echo htmlspecialchars($item['title']); ?></a>
                    </td>
                    <td style="font-size:12px;color:#64748b;"><?php echo htmlspecialchars((isset($channel['channel_name']) ? $channel['channel_name'] : '-')); ?></td>
                    <td>
                        <?php if (in_array('top', $flags)): ?><span class="badge badge-danger" style="margin-right:4px;">置顶</span><?php endif; ?>
                        <?php if (in_array('recommend', $flags)): ?><span class="badge badge-warning" style="margin-right:4px;">推荐</span><?php endif; ?>
                        <?php if (in_array('hot', $flags)): ?><span class="badge" style="background:#f60;color:#fff;margin-right:4px;">热门</span><?php endif; ?>
                    </td>
                    <td style="font-size:12px;color:#64748b;font-family:monospace;"><?php echo $item['release_time'] ? date('Y-m-d H:i', $item['release_time']) : '-'; ?></td>
                    <td style="font-family:monospace;"><?php echo $item['click']; ?></td>
                    <td>
                        <?php if ($item['status'] == 1): ?>
                        <span class="badge badge-success">显示</span>
                        <?php else: ?>
                        <span class="badge badge-secondary">隐藏</span>
                        <?php endif; ?>
                    </td>
                    <td>
                            <a href="?act=article&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-primary" style="margin-bottom:4px;"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                            <a href="javascript:delArticle(<?php echo $item['id']; ?>);" class="btn btn-ghost" style="color:#EF4444;"><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> 删除</a>
                        </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?><a href="?act=article&page=<?php echo $page - 1; ?>&channel_id=<?php echo $channelId; ?>&keyword=<?php echo urlencode($keyword); ?>&status=<?php echo $status; ?>">&laquo; 上一页</a><?php endif; ?>
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?act=article&page=<?php echo $i; ?>&channel_id=<?php echo $channelId; ?>&keyword=<?php echo urlencode($keyword); ?>&status=<?php echo $status; ?>" <?php echo $i == $page ? 'class="active"' : ''; ?>><?php echo $i; ?></a>
            <?php endfor; ?>
            <?php if ($page < $totalPages): ?><a href="?act=article&page=<?php echo $page + 1; ?>&channel_id=<?php echo $channelId; ?>&keyword=<?php echo urlencode($keyword); ?>&status=<?php echo $status; ?>">下一页 &raquo;</a><?php endif; ?>
        </div>
        <?php endif; endif; ?>
    </div>
    <script>
    function delArticle(id) { if (confirm('确定删除?')) { fetch('?act=article&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    function toggleStatus(id, label) {
        var cb = label.querySelector('.status-toggle');
        var newVal = cb.checked ? 0 : 1;
        fetch('/admin/main.php?act=article&action=toggle', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&status='+newVal+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'}).then(r=>r.text()).then(function(text) { try { var d = JSON.parse(text); if (d.code==200) { cb.checked = !cb.checked; cb.parentElement.style.background = newVal ? '#10b981' : '#cbd5e1'; cb.parentElement.querySelector('div').style.left = newVal ? '19px' : '3px'; } else { alert(d.msg); } } catch(e) { alert('请求失败'); } }).catch(function(e) { alert('请求失败'); });
    }
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=article&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }

</script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $defaults = ['id'=>'','channel_id'=>0,'title'=>'','short_title'=>'','litpic'=>'','flag'=>'','tags'=>'','source'=>'','author'=>'','summary'=>'','content'=>'','seo_title'=>'','seo_keywords'=>'','seo_description'=>'','sort_order'=>100,'status'=>1,'release_time'=>time()];
    if ($action === 'add' && isset($_GET['channel_id'])) {
        $defaults['channel_id'] = intval($_GET['channel_id']);
    }
    $editData = $defaults;
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('article')} WHERE id = ?", [intval($_GET['id'])]);
    }
    $releaseTime = isset($editData['release_time']) && $editData['release_time'] ? (is_string($editData['release_time']) ? strtotime($editData['release_time']) : $editData['release_time']) : time();
    $channels = $db->fetchAll("SELECT id, parent_id, channel_name FROM {$db->table('channel')} WHERE channel_type = 1 ORDER BY list_order ASC");

    function renderChannelSelect($channels, $parentId = 0, $selected = 0, $depth = 0) {
        foreach ($channels as $ch) {
            if ($ch['parent_id'] == $parentId) {
                echo '<option value="' . $ch['id'] . '"' . ($selected == $ch['id'] ? ' selected' : '') . '>' . str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $depth) . $ch['channel_name'] . '</option>';
                renderChannelSelect($channels, $ch['id'], $selected, $depth + 1);
            }
        }
    }

    $flagChecked = $editData['flag'] ? explode(',', $editData['flag']) : [];
    $isEdit = $action === 'edit';
    ?>
    <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="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></div>
                <div>
                    <h1><?php echo $isEdit ? '编辑文章' : '发布文章'; ?></h1>
                    <p style="font-size:12px;color:#64748b;margin:0;">填写文章信息</p>
                </div>
            </div>
            <div class="page-actions"><a href="?act=article" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=article&action=save" id="articleForm">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <div style="display:grid;grid-template-columns:820px 360px;gap:20px;align-items:start;">
                <div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg> 基本信息</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>文章标题 <span class="required">*</span></label><input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($editData['title']); ?>" placeholder="请输入文章标题" required></div>
                            <div class="form-group"><label>短标题</label><input type="text" name="short_title" class="form-control" value="<?php echo htmlspecialchars($editData['short_title']); ?>" placeholder="短标题（留空使用原标题）"></div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>所属栏目 <span class="required">*</span></label>
                                    <select name="channel_id" class="form-control" required>
                                        <option value="">请选择栏目</option>
                                        <?php renderChannelSelect($channels, 0, $editData['channel_id']); ?>
                                    </select>
                                </div>
                                <div class="form-group"><label>标签</label><input type="text" name="tags" class="form-control" value="<?php echo htmlspecialchars($editData['tags']); ?>" placeholder="多个标签用逗号分隔"></div>
                            </div>
                            <div class="form-row">
                                <div class="form-group"><label>文章来源</label><input type="text" name="source" class="form-control" value="<?php echo htmlspecialchars($editData['source']); ?>" placeholder="如：原创、转载"></div>
                                <div class="form-group"><label>作者</label><input type="text" name="author" class="form-control" value="<?php echo htmlspecialchars($editData['author']); ?>" placeholder="作者姓名"></div>
                            </div>
                            <div class="form-group"><label>摘要</label><textarea name="summary" class="form-control" rows="3" placeholder="文章摘要"><?php echo htmlspecialchars($editData['summary']); ?></textarea></div>
                            <div class="form-group">
                                <label>属性</label>
                                <div style="display:flex;gap:16px;">
                                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;"><input type="checkbox" name="flag[]" value="top" <?php echo in_array('top', $flagChecked) ? 'checked' : ''; ?>> 置顶</label>
                                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;"><input type="checkbox" name="flag[]" value="recommend" <?php echo in_array('recommend', $flagChecked) ? 'checked' : ''; ?>> 推荐</label>
                                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;"><input type="checkbox" name="flag[]" value="hot" <?php echo in_array('hot', $flagChecked) ? 'checked' : ''; ?>> 热门</label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="21" x2="9" y2="9"/></svg> 文章内容</div>
                        <div class="form-section-body cms-ueditor-wrap">
                            <script src="/public/ueditor/ueditor.config.js"></script>
                            <script src="/public/ueditor/ueditor.all.min.js"></script>
                            <script type="text/plain" id="article_content_editor" name="content" style="width:780px;height:360px;"></script>
                            <script>
                            (function(){
                                var editorContent = <?php echo json_encode(isset($editData['content']) ? $editData['content'] : '', JSON_UNESCAPED_UNICODE); ?>;
                                function initEditor(){
                                    if (!window.UE) { alert('UEditor资源加载失败'); return; }
                                    try { if (UE.instants && UE.instants['article_content_editor']) UE.instants['article_content_editor'].destroy(); } catch(e) {}
                                    window.articleContentEditor = UE.getEditor('article_content_editor', {
                                        initialFrameWidth: 780,
                                        initialFrameHeight: 360,
                                        autoHeightEnabled: false,
                                        autoFloatEnabled: false,
                                        scaleEnabled: false,
                                        serverUrl: '/public/ueditor/php/controller.php'
                                    });
                                    articleContentEditor.ready(function(){ articleContentEditor.setContent(editorContent || ''); });
                                }
                                if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initEditor); else setTimeout(initEditor, 0);
                            })();
                            </script>
                            <style>
                            .cms-ueditor-wrap{overflow:visible !important;padding:20px !important;box-sizing:border-box;height:500px !important;margin:0 !important;display:block;}
                            .cms-ueditor-wrap .edui-editor{display:block !important;width:780px !important;max-width:780px !important;box-sizing:border-box;}
                            .cms-ueditor-wrap .edui-editor-toolbarbox,.cms-ueditor-wrap .edui-editor-iframeholder{width:780px !important;max-width:780px !important;box-sizing:border-box;}
                            </style>
                        </div>
                    </div>
                </div>
                <div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg> 封面图片</div>
                        <div class="form-section-body">
                            <div id="litpicPreview" class="upload-preview" style="cursor:pointer;<?php echo !empty($editData['litpic']) ? '' : ''; ?>" onclick="document.getElementById('litpicUpload').click();">
                                <?php if (!empty($editData['litpic'])): ?>
                                <img src="<?php echo htmlspecialchars($editData['litpic']); ?>" style="width:100%;height:100%;object-fit:cover;">
                                <?php else: ?>
                                <div class="placeholder"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><span style="font-size:12px;color:#94a3b8;margin-top:4px;">点击上传封面图片</span></div>
                                <?php endif; ?>
                            </div>
                            <input type="file" id="litpicUpload" accept="image/*" style="display:none;" onchange="handleLitpicUpload(this)">
                            <input type="text" name="litpic" id="litpicInput" value="<?php echo htmlspecialchars($editData['litpic']); ?>" placeholder="或输入图片地址" style="width:100%;margin-top:10px;" class="form-control">
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg> 发布设置</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>排序</label><input type="number" name="sort_order" class="form-control" value="<?php echo $editData['sort_order']; ?>" min="0"></div>
                            <div class="form-group"><label>发布时间</label><input type="datetime-local" name="release_time" class="form-control" value="<?php echo date('Y-m-d\TH:i', $releaseTime); ?>" style="width:100%;"></div>
                            <div class="form-group">
                                <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                                    <input type="checkbox" name="status" value="1" <?php echo $editData['status'] ? 'checked' : ''; ?> id="statusToggle" style="display:none;">
                                    <div id="statusSwitch" style="width:44px;height:24px;background:<?php echo $editData['status'] ? '#10b981' : '#cbd5e1'; ?>;border-radius:12px;position:relative;transition:all 0.2s;"><div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['status'] ? '23px' : '3px'; ?>;transition:all 0.2s;"></div></div>
                                    <span id="statusLabel" style="font-weight:500;color:<?php echo $editData['status'] ? '#10b981' : '#64748b'; ?>;"><?php echo $editData['status'] ? '显示' : '隐藏'; ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-section">
                        <div class="form-section-header"><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> SEO优化</div>
                        <div class="form-section-body">
                            <div class="form-group"><label>SEO标题</label><input type="text" name="seo_title" class="form-control" value="<?php echo htmlspecialchars($editData['seo_title']); ?>" placeholder="留空使用文章标题"></div>
                            <div class="form-group"><label>SEO关键字</label><input type="text" name="seo_keywords" class="form-control" value="<?php echo htmlspecialchars($editData['seo_keywords']); ?>" placeholder="关键字1,关键字2"></div>
                            <div class="form-group"><label>SEO描述</label><textarea name="seo_description" class="form-control" rows="3" placeholder="文章描述"><?php echo htmlspecialchars($editData['seo_description']); ?></textarea></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-actions" style="background:#fff;padding:20px;border-radius:8px;margin-top:20px;">
                <button type="submit" class="btn btn-success btn-lg"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> <?php echo $isEdit ? '保存' : '发布'; ?></button>
                <a href="?act=article" class="btn btn-secondary btn-lg">取消</a>
            </div>
        </form>
    </div>
    <script>
    document.getElementById('statusToggle').addEventListener('change', function() {
        var sw = document.getElementById('statusSwitch');
        var lb = document.getElementById('statusLabel');
        if (this.checked) { sw.style.background = '#10b981'; sw.querySelector('div').style.left = '23px'; lb.textContent = '显示'; lb.style.color = '#10b981'; }
        else { sw.style.background = '#cbd5e1'; sw.querySelector('div').style.left = '3px'; lb.textContent = '隐藏'; lb.style.color = '#64748b'; }
    });
    function uploadFile(file, targetId, previewId) {
        var formData = new FormData();
        formData.append('file', file);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=upload', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                var d = JSON.parse(xhr.responseText);
                if (d.code === 200) {
                    document.getElementById(targetId).value = d.data.url;
                    var preview = document.getElementById(previewId);
                    preview.innerHTML = '<img src="' + d.data.url + '" style="width:100%;height:100%;object-fit:cover;">';
                } else { alert(d.msg); }
            }
        };
        xhr.send(formData);
    }
    function handleLitpicUpload(input) {
        var file = input.files[0];
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) { alert('图片大小不能超过5MB'); return; }
        uploadFile(file, 'litpicInput', 'litpicPreview');
    }
    document.getElementById('litpicInput').addEventListener('input', function(e) {
        var preview = document.getElementById('litpicPreview');
        if (e.target.value) {
            preview.innerHTML = '<img src="' + e.target.value + '" style="width:100%;height:100%;object-fit:cover;">';
        } else {
            preview.innerHTML = '<div class="placeholder"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><span style="font-size:12px;color:#94a3b8;margin-top:4px;">点击上传封面图片</span></div>';
        }
    });
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=article&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }

</script>
    <?php
}
?>

