<?php
ob_start();
/**
 * 2026企业CMS - 后台文章管理
 */
require_once __DIR__ . '/header.php';
$pageTitle = '文章管理';
$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

// 处理删除
if ($action === 'delete' && $id) {
    check_permission('editor');
    $a = db_query_one("SELECT `title` FROM `articles` WHERE `id`=?",[$id]);
    db_exec("DELETE FROM `articles` WHERE `id`=?", [$id]);
    add_log('delete', 'articles', '删除文章: ' . ($a['title'] ?? ''));
    header('Location: /admin/articles.php?msg=' . urlencode('删除成功！'));
    exit;
}

// 处理批量操作
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['batch_action'])) {
    check_permission('editor');
    if (!csrf_validate($_POST['csrf_token'] ?? '')) {
        die('CSRF 验证失败');
    }
    $ids = $_POST['ids'] ?? [];
    if (!empty($ids)) {
        $in = str_repeat('?,', count($ids)-1) . '?';
        if ($_POST['batch_action'] === 'delete') {
            db_exec("DELETE FROM `articles` WHERE `id` IN ({$in})", $ids);
            add_log('batch_delete', 'articles', '批量删除文章: ' . count($ids) . '条');
        } elseif ($_POST['batch_action'] === 'publish') {
            db_exec("UPDATE `articles` SET `status`=1 WHERE `id` IN ({$in})", $ids);
        } elseif ($_POST['batch_action'] === 'draft') {
            db_exec("UPDATE `articles` SET `status`=0 WHERE `id` IN ({$in})", $ids);
        }
    }
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}

// 处理保存（添加/编辑）
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    check_permission('editor');
    $title    = trim($_POST['title'] ?? '');
    $slug     = trim($_POST['slug'] ?? '');
    $summary  = trim($_POST['summary'] ?? '');
    $content  = $_POST['content'] ?? '';
    $catId    = intval($_POST['category_id'] ?? 1);
    $seoTitle = trim($_POST['seo_title'] ?? '');
    $seoKeys  = trim($_POST['seo_keywords'] ?? '');
    $seoDesc  = trim($_POST['seo_description'] ?? '');
    $isTop    = intval($_POST['is_top'] ?? 0);
    $isRec    = intval($_POST['is_recommend'] ?? 0);
    $status   = intval($_POST['status'] ?? 1);
    
    if (!$slug) $slug = generate_slug($title);
    if (!$summary && $content) $summary = str_cut(strip_tags($content), 200);
    
    if ($action === 'add') {
        db_exec(
            "INSERT INTO `articles` (`title`,`slug`,`summary`,`content`,`category_id`,`seo_title`,`seo_keywords`,`seo_description`,`is_top`,`is_recommend`,`status`,`author_id`,`published_at`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())",
            [$title, $slug, $summary, $content, $catId, $seoTitle, $seoKeys, $seoDesc, $isTop, $isRec, $status, $_SESSION['admin_id']]
        );
        $newId = db_last_insert_id();
        add_log('add', 'articles', '发布文章: ' . $title);
        header('Location: /admin/articles.php?msg=' . urlencode('发布成功！'));
        exit;
    } elseif ($action === 'edit' && $id) {
        db_exec(
            "UPDATE `articles` SET `title`=?,`slug`=?,`summary`=?,`content`=?,`category_id`=?,`seo_title`=?,`seo_keywords`=?,`seo_description`=?,`is_top`=?,`is_recommend`=?,`status`=? WHERE `id`=?",
            [$title, $slug, $summary, $content, $catId, $seoTitle, $seoKeys, $seoDesc, $isTop, $isRec, $status, $id]
        );
        add_log('edit', 'articles', '编辑文章: ' . $title);
        header('Location: /admin/articles.php?msg=' . urlencode('保存成功！'));
        exit;
    }
}

// 获取编辑数据
$article = [];
if ($action === 'edit' && $id) {
    $article = db_query_one("SELECT * FROM `articles` WHERE `id`=?", [$id]);
    if (!$article) { header('Location: /admin/articles.php'); exit; }
}
if ($action === 'add' || $action === 'edit'):
    $categories = db_query("SELECT * FROM `categories` WHERE `status`=1 ORDER BY `sort_order` ASC");
?>
<div class="page-header">
    <h2><?php echo htmlspecialchars($action, ENT_QUOTES, "UTF-8")==='add'?'发布文章':'编辑文章'; ?></h2>
    <a href="/admin/articles.php" class="btn">← 返回列表</a>
</div>
<div class="form-card">
    <form method="post" action="">
        <input type="hidden" name="csrf_token" value="<?= csrf_generate() ?>">
        <div class="form-row">
            <div class="form-group" style="flex:2;">
                <label>文章标题 <span style="color:red;">*</span></label>
                <input type="text" name="title" value="<?php echo xss_clean($article['title'] ?? ''); ?>" required>
            </div>
            <div class="form-group">
                <label>URL别名 (Slug)</label>
                <input type="text" name="slug" value="<?php echo xss_clean($article['slug'] ?? ''); ?>" placeholder="自动生成">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>分类</label>
                <select name="category_id">
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo $cat['id']; ?>" <?php echo ($article['category_id'] ?? 1)==$cat['id']?'selected':''; ?>><?php echo xss_clean($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>状态</label>
                <select name="status">
                    <option value="1" <?php echo ($article['status'] ?? 1)==1?'selected':''; ?>>发布</option>
                    <option value="0" <?php echo ($article['status'] ?? 1)==0?'selected':''; ?>>草稿</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label>摘要</label>
            <textarea name="summary" rows="3"><?php echo xss_clean($article['summary'] ?? ''); ?></textarea>
        </div>
        <div class="form-group">
            <label>正文内容 <span style="color:red;">*</span></label>
            <textarea name="content" id="content-editor" style="min-height:400px;"><?php echo $article['content'] ?? ''; ?></textarea>
        </div>
        <hr style="margin:30px 0;border:none;border-top:1px solid #eee;">
        <h3 style="margin-bottom:15px;font-size:16px;color:#333;">SEO设置</h3>
        <div class="form-row">
            <div class="form-group">
                <label>SEO标题</label>
                <input type="text" name="seo_title" value="<?php echo xss_clean($article['seo_title'] ?? ''); ?>">
            </div>
            <div class="form-group">
                <label>SEO关键词</label>
                <input type="text" name="seo_keywords" value="<?php echo xss_clean($article['seo_keywords'] ?? ''); ?>" placeholder="逗号分隔">
            </div>
        </div>
        <div class="form-group">
            <label>SEO描述</label>
            <textarea name="seo_description" rows="2"><?php echo xss_clean($article['seo_description'] ?? ''); ?></textarea>
        </div>
        <hr style="margin:30px 0;border:none;border-top:1px solid #eee;">
        <div class="form-row">
            <div class="form-group">
                <label><input type="checkbox" name="is_top" value="1" <?php echo ($article['is_top'] ?? 0)?'checked':''; ?>> 置顶</label>
            </div>
            <div class="form-group">
                <label><input type="checkbox" name="is_recommend" value="1" <?php echo ($article['is_recommend'] ?? 0)?'checked':''; ?>> 推荐</label>
            </div>
        </div>
        <div style="margin-top:30px;">
            <button type="submit" name="save" class="btn btn-primary" style="margin-right:10px;">保存</button>
            <a href="/admin/articles.php" class="btn">取消</a>
        </div>
    </form>
</div>
<script src="https://cdn.ckeditor.com/4.25.1-lts/full/ckeditor.js"></script>
<script>if(typeof CKEDITOR!=='undefined'){CKEDITOR.replace('content-editor');}</script>
<?php
require_once __DIR__ . '/footer.php';
exit;
endif;

// 文章列表
$page  = max(1, intval($_GET['page'] ?? 1));
$pageSize = 15;
$where = '1=1';
$params = [];
if (!empty($_GET['q'])) {
    $where .= ' AND (`title` LIKE ? OR `content` LIKE ?)';
    $q = '%' . $_GET['q'] . '%';
    $params[] = $q; $params[] = $q;
}
$total = db_count('articles', $where, $params);
$offset = ($page - 1) * $pageSize;
$articles = db_query("SELECT a.*,c.`name` as cat_name FROM `articles` a LEFT JOIN `categories` c ON a.`category_id`=c.`id` WHERE {$where} ORDER BY a.`is_top` DESC,a.`id` DESC LIMIT {$offset},{$pageSize}", $params);
?>
<div class="page-header">
    <h2>文章管理</h2>
    <a href="/admin/articles.php?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> 发布文章</a>
</div>

<form method="post" action="" id="batchForm">
    <input type="hidden" name="csrf_token" value="<?= csrf_generate() ?>">
    <div class="search-bar">
        <input type="text" name="q" placeholder="搜索文章标题或内容..." value="<?php echo xss_clean($_GET['q'] ?? ''); ?>">
        <button type="submit" formmethod="get"><i class="fas fa-search"></i> 搜索</button>
        <select name="batch_action" style="padding:8px;border:1px solid #ddd;border-radius:4px;" onchange="doBatch(this)">
            <option value="">批量操作</option>
            <option value="publish">发布</option>
            <option value="draft">设为草稿</option>
            <option value="delete">删除</option>
        </select>
    </div>
    
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th style="width:30px;"><input type="checkbox" onclick="toggleSelectAll(this)"></th>
                    <th>标题</th>
                    <th>分类</th>
                    <th>浏览</th>
                    <th>状态</th>
                    <th>发布时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($articles as $a): ?>
                <tr>
                    <td><input type="checkbox" name="ids[]" value="<?php echo $a['id']; ?>"></td>
                    <td>
                        <?php echo $a['is_top']?'<span style="color:#e74c3c;">[置顶]</span> ':''; ?>
                        <?php echo $a['is_recommend']?'<span style="color:#2c82e0;">[推荐]</span> ':''; ?>
                        <a href="/article/<?php echo $a['slug']; ?>.html" target="_blank"><?php echo xss_clean(str_cut($a['title'], 40)); ?></a>
                    </td>
                    <td><?php echo xss_clean($a['cat_name'] ?? '未分类'); ?></td>
                    <td><?php echo $a['views']; ?></td>
                    <td>
                        <?php if ($a['status']==1): ?><span class="badge badge-success">已发布</span>
                        <?php else: ?><span class="badge badge-danger">草稿</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo date('Y-m-d', strtotime($a['published_at'] ?: $a['created_at'])); ?></td>
                    <td class="actions">
                        <a href="/admin/articles.php?action=edit&id=<?php echo $a['id']; ?>" class="btn btn-sm btn-primary">编辑</a>
                        <form method="post" action="/admin/articles.php?action=delete&id=<?php echo $a['id']; ?>" style="display:inline;" onsubmit="return confirm('确定要删除吗？')">
                            <input type="hidden" name="csrf_token" value="<?= csrf_generate() ?>">
                            <button type="submit" class="btn btn-sm btn-danger">删除</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</form>

<?php if ($total > $pageSize): ?>
<div class="pagination">
    <?php for ($i=1; $i<=ceil($total/$pageSize); $i++): ?>
    <a href="/admin/articles.php?page=<?php echo $i; ?>" <?php echo $i==$page?'class="current"':''; ?>><?php echo $i; ?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<script>
function doBatch(sel) {
    if (!sel.value) return;
    if (sel.value === 'delete' && !confirm('确定要删除选中的文章吗？')) { sel.value=''; return; }
    document.getElementById('batchForm').submit();
}
</script>
<?php require_once __DIR__ . '/footer.php'; ?>
