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


/**
 * 投稿管理 - 后台审核列表
 */

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('contribute')} WHERE id IN ($placeholders)", $ids);
        echo json_encode(['code'=>200,'msg'=>'已删除 '.count($ids).' 项']); exit;
    }

    if ($ajaxAct === 'pass') {
        $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('contribute')} SET status=1, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
        echo json_encode(['code'=>200,'msg'=>'已通过审核']); exit;
    }

    if ($ajaxAct === 'reject') {
        $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; }
        $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '审核拒绝';
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $db->query("UPDATE {$db->table('contribute')} SET status=2, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
        echo json_encode(['code'=>200,'msg'=>'已拒绝']); exit;
    }
}

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

if ($action === 'view') {
    $id = intval($_GET['id'] ?? 0);
    $row = $db->fetch("SELECT c.*, m.username, m.nickname FROM {$db->table('contribute')} c LEFT JOIN {$db->table('member')} m ON c.member_id = m.id WHERE c.id = ?", [$id]);
    if (!$row) {
        echo '<script>alert("投稿不存在");history.back();</script>';
        exit;
    }
    $channel = $db->fetch("SELECT channel_name FROM {$db->table('channel')} WHERE id = ?", [$row['channel_id']]);
    $statusMap = [0 => '待审核', 1 => '已通过', 2 => '已拒绝'];
    $typeMap = [1 => '文章', 2 => '产品'];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><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><h1>投稿详情</h1></div>
            </div>
            <div class="page-actions"><a href="?act=contribute" class="btn btn-secondary">← 返回</a></div>
        </div>
        <div class="content-card" style="padding:20px;">
            <table class="data-table" style="width:100%;">
                <tr><td style="width:120px;color:var(--gray-500);">ID</td><td><?php echo $row['id']; ?></td></tr>
                <tr><td style="color:var(--gray-500);">投稿人</td><td><?php echo htmlspecialchars($row['username'] ?? '用户' . $row['member_id']); ?></td></tr>
                <tr><td style="color:var(--gray-500);">标题</td><td><?php echo htmlspecialchars($row['title']); ?></td></tr>
                <tr><td style="color:var(--gray-500);">栏目</td><td><?php echo htmlspecialchars($channel['channel_name'] ?? '-'); ?></td></tr>
                <tr><td style="color:var(--gray-500);">类型</td><td><?php echo $typeMap[$row['content_type']] ?? '未知'; ?></td></tr>
                <tr><td style="color:var(--gray-500);">摘要</td><td><?php echo htmlspecialchars($row['description'] ?? '-'); ?></td></tr>
                <tr><td style="color:var(--gray-500);">状态</td><td><span class="badge <?php echo $row['status'] == 1 ? 'badge-success' : ($row['status'] == 0 ? 'badge-warning' : 'badge-gray'); ?>"><?php echo $statusMap[$row['status']]; ?></span></td></tr>
                <tr><td style="color:var(--gray-500);">投稿时间</td><td><?php echo $row['add_time'] ? date('Y-m-d H:i:s', $row['add_time']) : '-'; ?></td></tr>
                <tr><td style="color:var(--gray-500);">封面图</td><td><?php if ($row['litpic']): ?><img src="<?php echo htmlspecialchars($row['litpic']); ?>" style="max-width:200px;max-height:100px;"/><?php else: ?>-<?php endif; ?></td></tr>
                <tr><td style="color:var(--gray-500);vertical-align:top;">详细内容</td><td style="padding:12px;border:1px solid #e5e7eb;border-radius:8px;"><?php echo $row['content']; ?></td></tr>
            </table>
        </div>
    </div>
    <?php
    exit;
}

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

    $where = '1=1';
    $params = [];
    if (!empty($keyword)) {
        $where .= ' AND (c.title LIKE ? OR m.username LIKE ?)';
        $params[] = '%' . $keyword . '%';
        $params[] = '%' . $keyword . '%';
    }
    if ($status > -999) {
        $where .= ' AND c.status = ?';
        $params[] = $status;
    }
    if ($channel_id > 0) {
        $where .= ' AND c.channel_id = ?';
        $params[] = $channel_id;
    }

    $offset = ($page - 1) * $pageSize;
    $lists = $db->fetchAll("SELECT c.*, m.username FROM {$db->table('contribute')} c LEFT JOIN {$db->table('member')} m ON c.member_id = m.id WHERE {$where} ORDER BY c.id DESC LIMIT {$offset}, {$pageSize}", $params);
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('contribute')} c LEFT JOIN {$db->table('member')} m ON c.member_id = m.id WHERE {$where}", $params)['cnt'];
    $totalPages = ceil($total / $pageSize);

    $statusMap = [
        0 => ['text' => '待审核', 'class' => 'badge-warning'],
        1 => ['text' => '已通过', 'class' => 'badge-success'],
        2 => ['text' => '已拒绝', 'class' => 'badge-gray'],
    ];

    $totalCount = $total;
    $pendingCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('contribute')} WHERE status = 0")['cnt'] ?? 0;
    $passCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('contribute')} WHERE status = 1")['cnt'] ?? 0;

    $channels = $db->fetchAll("SELECT id, channel_name FROM {$db->table('channel')} WHERE channel_type IN (1,2) ORDER BY id ASC");
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><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></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 $totalCount; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">待审核</span><span class="page-context-value"><?php echo $pendingCount; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">已通过</span><span class="page-context-value"><?php echo $passCount; ?> 条</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;flex-wrap:wrap;">
                <input type="hidden" name="act" value="contribute">
                <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="标题/用户名搜索..." style="flex:1;min-width:180px;padding:8px 12px;border:1px solid var(--gray-200);border-radius:6px;">
                <select name="channel_id" style="padding:8px 12px;border:1px solid var(--gray-200);border-radius:6px;">
                    <option value="0">全部栏目</option>
                    <?php foreach ($channels as $ch): ?>
                    <option value="<?php echo $ch['id']; ?>" <?php echo $channel_id == $ch['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($ch['channel_name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="status" style="padding:8px 12px;border:1px solid var(--gray-200);border-radius:6px;">
                    <option value="-999">全部状态</option>
                    <option value="0" <?php echo $status === 0 ? 'selected' : ''; ?>>待审核</option>
                    <option value="1" <?php echo $status === 1 ? 'selected' : ''; ?>>已通过</option>
                    <option value="2" <?php echo $status === 2 ? 'selected' : ''; ?>>已拒绝</option>
                </select>
                <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>
            </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"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg></div>
                <h3>暂无投稿</h3>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width:44px;text-align:center;"><input type="checkbox" onclick="document.querySelectorAll('.row-check').forEach(function(cb){cb.checked=event.target.checked;});" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th>
                        <th style="width:60px;">ID</th>
                        <th>投稿信息</th>
                        <th style="width:80px;">类型</th>
                        <th style="width:80px;">状态</th>
                        <th style="width:140px;">时间</th>
                        <th style="width:200px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <tr data-id="<?php echo $item['id']; ?>">
                        <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['title']); ?></div>
                            <div style="font-size:12px;color:var(--gray-400);margin-top:2px;"><?php echo htmlspecialchars($item['username'] ?? '用户' . $item['member_id']); ?></div>
                        </td>
                        <td><span class="badge badge-gray"><?php echo $item['content_type'] == 1 ? '文章' : '产品'; ?></span></td>
                        <td><span class="badge <?php echo $statusMap[$item['status']]['class'] ?? 'badge-gray'; ?>"><?php echo $statusMap[$item['status']]['text'] ?? '未知'; ?></span></td>
                        <td style="font-size:12px;color:var(--gray-500);"><?php echo $item['add_time'] ? date('Y-m-d H:i', $item['add_time']) : '-'; ?></td>
                        <td>
                            <div class="btn-group" style="width:200px;display:flex;gap:4px;">
                                <a href="?act=contribute&action=view&id=<?php echo $item['id']; ?>" class="btn btn-primary btn-sm"><svg style="width:12px;height:12px;" 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> 查看</a>
                                <?php if ($item['status'] == 0): ?>
                                <button type="button" class="btn btn-success btn-sm" onclick="passOne(<?php echo $item['id']; ?>)"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> 通过</button>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <div class="table-footer">
                <div class="table-info">共 <?php echo $total; ?> 条记录</div>
                <div class="batch-actions" style="display:flex;gap:8px;">
                    <button type="button" class="btn btn-sm btn-success" onclick="batchPass()"><svg style="width:12px;height:12px;" 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" class="btn btn-sm btn-danger" onclick="batchDelete()"><svg style="width:12px;height:12px;" 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;text-align:center;">
                <?php if ($page > 1): ?>
                <a href="?act=contribute&page=<?php echo $page - 1; ?>&status=<?php echo $status; ?>&keyword=<?php echo urlencode($keyword); ?>" style="padding:6px 12px;border:1px solid var(--gray-200);border-radius:6px;text-decoration:none;">上一页</a>
                <?php endif; ?>
                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                <a href="?act=contribute&page=<?php echo $i; ?>&status=<?php echo $status; ?>&keyword=<?php echo urlencode($keyword); ?>" <?php echo $i == $page ? 'class="active"' : ''; ?> style="padding:6px 12px;border:1px solid var(--gray-200);border-radius:6px;text-decoration:none;<?php echo $i == $page ? 'background:#2563eb;color:#fff;' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?>
                <a href="?act=contribute&page=<?php echo $page + 1; ?>&status=<?php echo $status; ?>&keyword=<?php echo urlencode($keyword); ?>" style="padding:6px 12px;border:1px solid var(--gray-200);border-radius:6px;text-decoration:none;">下一页</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    <script>
    function passOne(id) {
        if (!confirm('确定通过此投稿？')) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=contribute', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('ajax_action=pass&ids=' + encodeURIComponent(JSON.stringify([id])));
        xhr.onload = function() {
            try { var res = JSON.parse(xhr.responseText); alert(res.msg); if (res.code == 200) location.reload(); }
            catch(e) { alert('操作失败'); }
        };
    }
    function batchPass() {
        var ids = [];
        document.querySelectorAll('.row-check:checked').forEach(function(cb) { ids.push(cb.value); });
        if (ids.length === 0) { alert('请选择要通过的项'); return; }
        if (!confirm('确定通过选中的 ' + ids.length + ' 项吗？')) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=contribute', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('ajax_action=pass&ids=' + encodeURIComponent(JSON.stringify(ids)));
        xhr.onload = function() {
            try { var res = JSON.parse(xhr.responseText); alert(res.msg); if (res.code == 200) location.reload(); }
            catch(e) { alert('操作失败'); }
        };
    }
    function batchDelete() {
        var ids = [];
        document.querySelectorAll('.row-check:checked').forEach(function(cb) { ids.push(cb.value); });
        if (ids.length === 0) { alert('请选择要删除的项'); return; }
        if (!confirm('确定删除选中的 ' + ids.length + ' 项吗？')) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=contribute', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send('ajax_action=delete&ids=' + encodeURIComponent(JSON.stringify(ids)));
        xhr.onload = function() {
            try { var res = JSON.parse(xhr.responseText); alert(res.msg); if (res.code == 200) location.reload(); }
            catch(e) { alert('操作失败'); }
        };
    }
    </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;}
    @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
}
?>

