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

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$statusMap = [0 => ['待审核', 'badge-warning'], 1 => ['已通过', 'badge-success']];

function commentSubstr($value, $length)
{
    if (function_exists('mb_substr')) {
        return mb_substr($value, 0, $length, 'UTF-8');
    }
    return substr($value, 0, $length);
}

function syncCommentStatus($db, $ids, $approved)
{
    if (empty($ids)) {
        return 0;
    }
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
    if (empty($ids)) {
        return 0;
    }
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $params = array_merge([$approved ? 1 : 0, time(), $approved ? 1 : 0], $ids);
    $db->query(
        "UPDATE {$db->table('comment')} SET is_check = ?, check_time = ?, is_show = ? WHERE id IN ($placeholders)",
        $params
    );
    return count($ids);
}

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');

    $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
    $ids = json_decode($idsRaw, true);
    if (!is_array($ids)) {
        $ids = [];
    }
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));

    if (empty($ids)) {
        echo json_encode(['code' => 400, 'msg' => '请先选择要操作的评论']);
        exit;
    }

    $ajaxAct = $_POST['ajax_action'];
    if ($ajaxAct === 'delete') {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $db->query("DELETE FROM {$db->table('comment')} WHERE id IN ($placeholders)", $ids);
        addLog('删除', '评论管理', '批量删除评论 ' . count($ids) . ' 条');
        echo json_encode(['code' => 200, 'msg' => '已删除 ' . count($ids) . ' 条评论']);
        exit;
    }

    if ($ajaxAct === 'show' || $ajaxAct === 'hide') {
        $approved = $ajaxAct === 'show';
        $count = syncCommentStatus($db, $ids, $approved);
        addLog($approved ? '审核' : '隐藏', '评论管理', ($approved ? '批量通过' : '批量隐藏') . '评论 ' . $count . ' 条');
        echo json_encode(['code' => 200, 'msg' => $approved ? '已通过所选评论' : '已隐藏所选评论']);
        exit;
    }

    echo json_encode(['code' => 400, 'msg' => '不支持的操作']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'delete') {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '无效的评论ID']);
            exit;
        }
        $comment = $db->fetch("SELECT content FROM {$db->table('comment')} WHERE id = ?", [$id]);
        $db->delete('comment', 'id = ?', [$id]);
        addLog('删除', '评论管理', '删除评论：' . commentSubstr((string) ($comment['content'] ?? ''), 20));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }

    if ($action === 'toggle') {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '无效的评论ID']);
            exit;
        }
        $approved = !empty($_POST['is_check']);
        syncCommentStatus($db, [$id], $approved);
        addLog($approved ? '审核' : '隐藏', '评论管理', ($approved ? '审核通过' : '隐藏') . '评论ID ' . $id);
        echo json_encode(['code' => 200, 'msg' => '更新成功']);
        exit;
    }

    if ($action === 'save') {
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            echo '<script>alert("评论不存在");history.back();</script>';
            exit;
        }
        $approved = intval($_POST['is_check'] ?? 0) === 1;
        syncCommentStatus($db, [$id], $approved);
        addLog($approved ? '审核' : '隐藏', '评论管理', ($approved ? '审核通过' : '隐藏') . '评论ID ' . $id);
        echo '<script>alert("保存成功");location.href="?act=comment";</script>';
        exit;
    }
}

if ($action === 'edit') {
    $id = intval($_GET['id'] ?? 0);
    $row = $db->fetch(
        "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 c.id = ?",
        [$id]
    );
    if (!$row) {
        ?>
        <div class="page-container fade-in">
            <div class="content-card">
                <div class="empty-state">
                    <h3>评论不存在</h3>
                    <p>该评论可能已被删除。</p>
                    <a href="?act=comment" class="btn btn-secondary">返回列表</a>
                </div>
            </div>
        </div>
        <?php
        return;
    }
    ?>
    <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 class="page-actions"><a href="?act=comment" class="btn btn-secondary">返回列表</a></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 htmlspecialchars($row['name'] ?: '匿名用户'); ?></span></div>
            <div class="page-context-item"><span class="page-context-label">所属文章</span><span class="page-context-value"><?php echo htmlspecialchars($row['article_title'] ?: '-'); ?></span></div>
            <div class="page-context-item"><span class="page-context-label">提交时间</span><span class="page-context-value"><?php echo !empty($row['create_time']) ? date('Y-m-d H:i', $row['create_time']) : '-'; ?></span></div>
            <div class="page-context-item"><span class="page-context-label">当前状态</span><span class="page-context-value page-context-muted"><?php echo !empty($row['is_check']) ? '已通过' : '待审核'; ?></span></div>
        </div>
        <div class="content-card">
            <form method="post" action="?act=comment&action=save">
                <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                <div style="padding:24px;display:grid;gap:20px;">
                    <div>
                        <div style="font-size:13px;color:var(--gray-500);margin-bottom:8px;">评论内容</div>
                        <div style="padding:16px;border:1px solid #e2e8f0;border-radius:12px;background:#f8fafc;line-height:1.8;color:#334155;white-space:pre-wrap;"><?php echo htmlspecialchars($row['content']); ?></div>
                    </div>
                    <div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;">
                        <div>
                            <div style="font-size:13px;color:var(--gray-500);margin-bottom:6px;">联系邮箱</div>
                            <div style="font-weight:600;color:#1e293b;"><?php echo htmlspecialchars($row['email'] ?: '-'); ?></div>
                        </div>
                        <div>
                            <div style="font-size:13px;color:var(--gray-500);margin-bottom:6px;">来源 IP</div>
                            <div style="font-weight:600;color:#1e293b;"><?php echo htmlspecialchars($row['ip'] ?: '-'); ?></div>
                        </div>
                    </div>
                    <div>
                        <div style="font-size:13px;color:var(--gray-500);margin-bottom:8px;">审核结果</div>
                        <div style="display:flex;gap:12px;flex-wrap:wrap;">
                            <label class="review-option<?php echo !empty($row['is_check']) ? ' active' : ''; ?>">
                                <input type="radio" name="is_check" value="1" <?php echo !empty($row['is_check']) ? 'checked' : ''; ?>>
                                <span>审核通过并前台显示</span>
                            </label>
                            <label class="review-option<?php echo empty($row['is_check']) ? ' active' : ''; ?>">
                                <input type="radio" name="is_check" value="0" <?php echo empty($row['is_check']) ? 'checked' : ''; ?>>
                                <span>保留为待审核 / 前台隐藏</span>
                            </label>
                        </div>
                    </div>
                    <div style="display:flex;gap:12px;flex-wrap:wrap;">
                        <button type="submit" class="btn btn-primary">保存审核结果</button>
                        <button type="button" class="btn btn-secondary" onclick="quickToggleComment(<?php echo $row['id']; ?>, <?php echo !empty($row['is_check']) ? 0 : 1; ?>)">
                            <?php echo !empty($row['is_check']) ? '一键设为隐藏' : '一键通过审核'; ?>
                        </button>
                        <button type="button" class="btn btn-ghost" style="color:#EF4444;" onclick="delComment(<?php echo $row['id']; ?>)">删除评论</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script>
    document.querySelectorAll('.review-option input').forEach(function(input) {
        input.addEventListener('change', function() {
            document.querySelectorAll('.review-option').forEach(function(option) {
                option.classList.toggle('active', option.contains(input) && input.checked);
            });
        });
    });
    function delComment(id) {
        if (!confirm('确定删除这条评论？')) return;
        fetch('?act=comment&action=delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + encodeURIComponent(id)
        }).then(function(r) { return r.json(); }).then(function(d) {
            alert(d.msg || '操作完成');
            if (d.code === 200) location.href = '?act=comment';
        }).catch(function() {
            alert('删除失败');
        });
    }
    function quickToggleComment(id, isCheck) {
        fetch('?act=comment&action=toggle', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + encodeURIComponent(id) + '&is_check=' + (isCheck ? 1 : '')
        }).then(function(r) { return r.json(); }).then(function(d) {
            alert(d.msg || '操作完成');
            if (d.code === 200) location.reload();
        }).catch(function() {
            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;}
    .review-option{display:flex;align-items:center;gap:10px;padding:14px 16px;border:1px solid #cbd5e1;border-radius:12px;cursor:pointer;color:#334155;background:#fff;}
    .review-option input{accent-color:#2563eb;}
    .review-option.active{border-color:#2563eb;background:#eff6ff;color:#1d4ed8;}
    @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
    return;
}

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 ($keyword !== '') {
        $where .= ' AND (c.content LIKE ? OR c.name LIKE ?)';
        $params[] = '%' . $keyword . '%';
        $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 = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('comment')} c WHERE {$where}", $params)['cnt'] ?? 0);
    $totalPages = max(1, (int) ceil($total / $pageSize));
    $pendingCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('comment')} WHERE is_check = 0")['cnt'] ?? 0);
    ?>
    <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="page-context-bar">
            <div class="page-context-item"><span class="page-context-label">评论总数</span><span class="page-context-value"><?php echo $total; ?> 条</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 $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%;flex-wrap:wrap;">
                <input type="hidden" name="act" value="comment">
                <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索评论内容或评论人..." style="flex:1;min-width:220px;">
                <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">重置</a>
                <?php endif; ?>
            </form>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <button type="button" class="btn btn-secondary" onclick="batchAction('show')">批量通过</button>
                <button type="button" class="btn btn-secondary" onclick="batchAction('hide')">批量隐藏</button>
                <button type="button" class="btn btn-ghost" style="color:#EF4444;" onclick="batchAction('delete')">批量删除</button>
            </div>
        </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" style="width:40px;"><input type="checkbox" onclick="toggleCheckAll(this)" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th>
                        <th class="id-cell">ID</th>
                        <th>评论内容</th>
                        <th style="width:120px;">所属文章</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[intval($item['is_check'])] ?? $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:600;color:#334155;"><?php echo htmlspecialchars($item['name'] ?: ('评论 #' . $item['id'])); ?></div>
                            <div style="font-size:12px;color:#64748b;margin-top:4px;line-height:1.6;"><?php echo htmlspecialchars(commentSubstr((string) $item['content'], 100)); ?></div>
                        </td>
                        <td><span class="badge badge-gray"><?php echo htmlspecialchars(commentSubstr((string) ($item['article_title'] ?: '-'), 12)); ?></span></td>
                        <td style="font-size:12px;color:#64748b;"><?php echo !empty($item['create_time']) ? 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">审核</a>
                                <button type="button" class="btn btn-secondary" onclick="quickToggleComment(<?php echo $item['id']; ?>, <?php echo intval($item['is_check']) ? 0 : 1; ?>)">
                                    <?php echo intval($item['is_check']) ? '隐藏' : '通过'; ?>
                                </button>
                                <button type="button" class="btn btn-ghost" style="color:#EF4444;" onclick="delComment(<?php echo $item['id']; ?>)">删除</button>
                            </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; ?>&keyword=<?php echo urlencode($keyword); ?>">上页</a><?php endif; ?>
                <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                <a href="?act=comment&page=<?php echo $i; ?>&keyword=<?php echo urlencode($keyword); ?>" <?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; ?>&keyword=<?php echo urlencode($keyword); ?>">下页</a><?php endif; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    <script>
    function delComment(id) {
        if (!confirm('确定删除这条评论？')) return;
        fetch('?act=comment&action=delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + encodeURIComponent(id)
        }).then(function(r) { return r.json(); }).then(function(d) {
            alert(d.msg || '操作完成');
            if (d.code === 200) location.reload();
        }).catch(function() {
            alert('删除失败');
        });
    }
    function quickToggleComment(id, isCheck) {
        fetch('?act=comment&action=toggle', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + encodeURIComponent(id) + '&is_check=' + (isCheck ? 1 : '')
        }).then(function(r) { return r.json(); }).then(function(d) {
            alert(d.msg || '操作完成');
            if (d.code === 200) location.reload();
        }).catch(function() {
            alert('更新失败');
        });
    }
    function toggleCheckAll(cb) {
        document.querySelectorAll('.row-check').forEach(function(item) {
            item.checked = cb.checked;
        });
    }
    function getSelectedIds() {
        var ids = [];
        document.querySelectorAll('.row-check:checked').forEach(function(item) {
            ids.push(item.value);
        });
        return ids;
    }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) {
            alert('请先勾选要操作的评论');
            return;
        }
        var confirmText = action === 'delete' ? '确定删除选中的 ' + ids.length + ' 条评论？' :
            (action === 'show' ? '确定通过选中的 ' + ids.length + ' 条评论？' : '确定隐藏选中的 ' + ids.length + ' 条评论？');
        if (!confirm(confirmText)) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=comment', 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('操作失败');
                }
            }
        };
        xhr.send('ajax_action=' + encodeURIComponent(action) + '&ids=' + encodeURIComponent(JSON.stringify(ids)));
    }
    </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
}
?>
