<?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'])) {
        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('comment')} 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('comment')} 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('comment')} 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';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);
        $c = $db->fetch("SELECT content FROM {$db->table('comment')} WHERE id = ?", [$id]);
        $db->delete('comment', 'id = ?', [$id]);
        addLog('删除', '评论管理', '删除评论：' . mbsubstr($c['content'] ?? '', 0, 20));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
    if ($action === 'toggle') {
        $id = intval($_POST['id'] ?? 0);
        $is_check = isset($_POST['is_check']) ? 1 : 0;
        $db->update('comment', ['is_check' => $is_check, 'check_time' => time()], 'id = ?', [$id]);
        echo json_encode(['code' => 200, 'msg' => '更新成功']);
        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 (c.content LIKE ?)';
        $params[] = '%' . $keyword . '%';
    }
    $offset = ($page - 1) * $pageSize;
    $lists = $db->fetchAll("SELECT c.*, a.title as article_title FROM {$db->table('comment')} c LEFT JOIN {$db->table('article')} a ON c.content_id = a.id WHERE {$where} ORDER BY c.id DESC LIMIT {$offset}, {$pageSize}", $params);
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('comment')} c WHERE {$where}", $params)['cnt'];
    $totalPages = ceil($total / $pageSize);
    $statusMap = [0 => ['待审核', 'badge-warning'], 1 => ['通过', 'badge-success']];
    ?>
    <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 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg></div>
                <div>
                    <h1>评论管理</h1>
                    <p style="font-size:12px;color:var(--gray-500);margin:0;">管理文章评论</p>
                </div>
            </div>
        </div>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background:var(--primary-bg);color:var(--primary);"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg></div>
                <div class="stat-info">
                    <div class="stat-value"><?php echo $total; ?></div>
                    <div class="stat-label">评论总数</div>
                </div>
            </div>
        </div>
        <div class="filter-bar">
            <form method="get" style="display:flex;gap:12px;width:100%;">
                <input type="hidden" name="act" value="comment">
                <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索评论内容..." style="flex:1;min-width:200px;">
                <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=comment" 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 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg></div>
                <h3>暂无评论</h3>
                <p>还没有评论</p>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th class="id-cell">ID</th>
                        <th>评论内容</th>
                        <th style="width:100px;">文章</th>
                        <th style="width:80px;">用户</th>
                        <th style="width:140px;">时间</th>
                        <th style="width:100px;">状态</th>
                        <th style="width:250px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <?php $st = $statusMap[$item['is_check']] ?? $statusMap[0]; ?>
                    <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><tr>
                        <td class="id-cell"><?php echo $item['id']; ?></td>
                        <td>
                            <div style="font-weight:500;color:var(--gray-800);"><?php echo htmlspecialchars($item['name'] ?: ('ID:' . $item['id'])); ?></div>
                            <div style="font-size:12px;color:var(--gray-500);margin-top:4px;"><?php echo mbsubstr(htmlspecialchars($item['content']), 0, 100); ?></div>
                        </td>
                        <td><span class="badge badge-gray"><?php echo mbsubstr($item['article_title'] ?? '-', 0, 10); ?></span></td>
                        <td style="color:#64748b;"><?php echo htmlspecialchars($item['name']); ?></td>
                        <td style="font-size:12px;color:var(--gray-500);"><?php echo date('Y-m-d H:i', $item['create_time']); ?></td>
                        <td><span class="badge <?php echo $st[1]; ?>"><?php echo $st[0]; ?></span></td>
                        <td>
                            <div class="btn-group">
                                <a href="?act=comment&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-primary"><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:delComment(<?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>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php if ($totalPages > 1): ?>
            <div class="pagination" style="padding:16px;text-align:center;">
                <?php if ($page > 1): ?><a href="?act=comment&page=<?php echo $page-1; ?>"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg> 上页</a><?php endif; ?>
                <?php for ($i = max(1, $page-2); $i <= min($totalPages, $page+2); $i++): ?>
                <a href="?act=comment&page=<?php echo $i; ?>" <?php echo $i==$page?'class="active"':''; ?>><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?><a href="?act=comment&page=<?php echo $page+1; ?>"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg> 下页</a><?php endif; ?>
            </div>
            <?php endif; endif; ?>
        </div>
    </div>
    <script>
    function delComment(id) { if (confirm('确定删除？')) { fetch('?act=comment&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    
    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=comment&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)));
    }

</script>
    <?php
}
?>

