<?php
// 功能：举报管理页面文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。

if (!defined('ADMIN_LOADED')) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access Denied');
}

global $conn;

if (isset($_GET['delete_report'])) {
    $report_id = intval($_GET['delete_report']);
    $sql = "DELETE FROM reports WHERE id = ?";
    $result = execute_non_query($conn, $sql, array($report_id));
    $redirect_url = '?tab=reports';
    if (isset($_GET['status'])) {
        $redirect_url .= '&status=' . urlencode($_GET['status']);
    }
    if (isset($_GET['search'])) {
        $redirect_url .= '&search=' . urlencode($_GET['search']);
    }
    handleAjaxResponse($result !== false && $result['affected_rows'] > 0, '举报记录已成功删除！', '举报记录删除失败！', $redirect_url);
}

if (isset($_GET['action']) && $_GET['action'] == 'status' && isset($_GET['id']) && isset($_GET['status'])) {
    $report_id = intval($_GET['id']);
    $status = intval($_GET['status']);
    $sql = "UPDATE reports SET status = ? WHERE id = ?";
    $result = execute_non_query($conn, $sql, array($status, $report_id));
    $redirect_url = '?tab=reports';
    if (isset($_GET['status'])) {
        $redirect_url .= '&status=' . urlencode($_GET['status']);
    }
    if (isset($_GET['search'])) {
        $redirect_url .= '&search=' . urlencode($_GET['search']);
    }
    handleAjaxResponse($result !== false && $result['affected_rows'] > 0, '举报状态已更新！', '举报状态更新失败！', $redirect_url);
}

$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
if ($status_filter === 'unprocessed' || $status_filter === 'unreviewed') $status_filter = '0';
if ($status_filter === 'processed' || $status_filter === 'reviewed') $status_filter = '1';
$search = isset($search) ? $search : (isset($_GET['search']) ? trim($_GET['search']) : '');
$current_page = isset($current_page) ? max(1, intval($current_page)) : 1;
$posts_per_page = isset($posts_per_page) ? max(1, min(1000, intval($posts_per_page))) : 30;
$offset = max(0, ($current_page - 1) * $posts_per_page);

$sql = "SELECT r.id, r.content_id as reported_id, r.content_type as reported_type, r.reason, r.user_id as reported_by, u.username as reporter_username, r.created_at, r.status FROM reports r LEFT JOIN users u ON r.user_id = u.id";
$where_conditions = array();
$params = array();

if ($status_filter != 'all') {
    $status_value = is_numeric($status_filter) ? intval($status_filter) : (($status_filter == 'processed' || $status_filter == 'reviewed') ? 1 : 0);
    $where_conditions[] = "r.status = ?";
    $params[] = $status_value;
}

if (!empty($search)) {
    $where_conditions[] = "(r.reason LIKE ? OR u.username LIKE ?)";
    $searchPattern = '%' . $search . '%';
    $params[] = $searchPattern;
    $params[] = $searchPattern;
}

if (!empty($where_conditions)) {
    $sql .= " WHERE " . implode(" AND ", $where_conditions);
}

$count_sql = "SELECT COUNT(*) as count FROM reports r LEFT JOIN users u ON r.user_id = u.id";
if (!empty($where_conditions)) {
    $count_sql .= " WHERE " . implode(" AND ", $where_conditions);
}

$count_result = execute_query($conn, $count_sql, $params);
$total_reports = 0;
if ($count_result !== false) {
    $row = $count_result->fetch_assoc();
    $total_reports = $row['count'];
    $count_result->close();
}
$total_pages = $total_reports > 0 ? ceil($total_reports / $posts_per_page) : 1;

$sql .= " ORDER BY r.created_at DESC LIMIT ?, ?";
$params[] = $offset;
$params[] = $posts_per_page;

$result = execute_query($conn, $sql, $params);
$post_ids = [];
$comment_ids = [];
$user_ids = [];
$temp_reports = [];
$comment_post_ids = [];

if ($result !== false) {
    while ($row = $result->fetch_assoc()) {
        if ($row['reported_type'] == 'post') {
            $post_ids[] = $row['reported_id'];
        } elseif ($row['reported_type'] == 'comment') {
            $comment_ids[] = $row['reported_id'];
        } elseif ($row['reported_type'] == 'user') {
            $user_ids[] = $row['reported_id'];
        }
        $temp_reports[] = $row;
    }
    $result->close();
}

$post_titles = [];
if (!empty($post_ids)) {
    $post_placeholders = implode(',', array_fill(0, count($post_ids), '?'));
    $post_sql = "SELECT id, title FROM posts WHERE id IN ($post_placeholders)";
    $post_result = execute_query($conn, $post_sql, $post_ids);
    if ($post_result !== false) {
        while ($row = $post_result->fetch_assoc()) {
            $post_titles[$row['id']] = $row['title'];
        }
        $post_result->close();
    }
}

$comment_contents = [];
if (!empty($comment_ids)) {
    $comment_placeholders = implode(',', array_fill(0, count($comment_ids), '?'));
    $comment_sql = "SELECT id, content, post_id FROM comments WHERE id IN ($comment_placeholders)";
    $comment_result = execute_query($conn, $comment_sql, $comment_ids);
    if ($comment_result !== false) {
        while ($row = $comment_result->fetch_assoc()) {
            $comment_contents[$row['id']] = $row['content'];
            $comment_post_ids[$row['id']] = $row['post_id'];
        }
        $comment_result->close();
    }
}

$user_names = [];
if (!empty($user_ids)) {
    $user_placeholders = implode(',', array_fill(0, count($user_ids), '?'));
    $user_sql = "SELECT id, username FROM users WHERE id IN ($user_placeholders)";
    $user_result = execute_query($conn, $user_sql, $user_ids);
    if ($user_result !== false) {
        while ($row = $user_result->fetch_assoc()) {
            $user_names[$row['id']] = $row['username'];
        }
        $user_result->close();
    }
}

$type_map = array('post' => '文章', 'comment' => '评论', 'user' => '用户');

$filtered_reports = array();
foreach ($temp_reports as $row) {
    $reported_title = '';
    $reported_full = '';
    if ($row['reported_type'] == 'post') {
        $reported_title = isset($post_titles[$row['reported_id']]) ? strip_tags($post_titles[$row['reported_id']]) : '已删除的文章';
        $reported_full = $reported_title;
    } elseif ($row['reported_type'] == 'comment') {
        $content = isset($comment_contents[$row['reported_id']]) ? $comment_contents[$row['reported_id']] : '已删除的评论';
        $content = strip_tags($content);
        $reported_full = $content;
        $reported_title = (mb_strlen($content, 'UTF-8') > 20 ? mb_substr($content, 0, 20, 'UTF-8') . '...' : $content);
    } elseif ($row['reported_type'] == 'user') {
        $reported_title = isset($user_names[$row['reported_id']]) ? $user_names[$row['reported_id']] : '已删除的用户';
        $reported_full = $reported_title;
    }
    $row['reported_title'] = $reported_title;
    $row['reported_full'] = $reported_full;
    $row['reason_full'] = strip_tags($row['reason']);
    $filtered_reports[] = $row;
}


?>

<div class="section-header">
    <h2>举报管理</h2>
</div>
<div class="admin-card">
    <div class="table-container">
        <table class="admin-table reports-manage">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>内容</th>
                    <th>类型</th>
                    <th>原因</th>
                    <th>时间</th>
                    <th>
                        <div class="audit-header-wrap">
                            <span id="audit-header" class="audit-header-trigger" onclick="toggleAuditMenu()">审核</span>
                            <div id="audit-dropdown-menu" class="audit-dropdown-menu" style="display: none;">
                                <div class="audit-dropdown-item" onclick="filterAuditStatus('all')">全部</div>
                                <div class="audit-dropdown-item" onclick="filterAuditStatus('0')">未审核</div>
                                <div class="audit-dropdown-item" onclick="filterAuditStatus('1')">已审核</div>
                            </div>
                        </div>
                    </th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($filtered_reports)): ?>
                    <tr><td colspan="7" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>
                <?php else: ?>
                    <?php foreach ($filtered_reports as $report): ?>
                        <?php
                        $content_tip = htmlspecialchars($report['reported_full'], ENT_QUOTES, 'UTF-8');
                        $reason_tip = htmlspecialchars($report['reason_full'], ENT_QUOTES, 'UTF-8');
                        $reason_display = mb_strlen($report['reason_full'], 'UTF-8') > 20 ? mb_substr($report['reason_full'], 0, 20, 'UTF-8') . '...' : $report['reason_full'];
                        
                        ?>
                        <tr>
                            <td><?php echo $report['id']; ?></td>
                            <td>
                                <span class="report-content-text" data-qk-tip="<?php echo $content_tip; ?>"><?php echo escape($report['reported_title']); ?></span>
                            </td>
                            <td><?php echo isset($type_map[$report['reported_type']]) ? $type_map[$report['reported_type']] : $report['reported_type']; ?></td>
                            <td>
                                <span class="report-reason-text" data-qk-tip="<?php echo $reason_tip; ?>"><?php echo escape($reason_display); ?></span>
                            </td>
                            <td><?php echo date('Y-m-d', strtotime($report['created_at'])); ?></td>
                            <td class="review-cell">
                                <label class="theme-switch">
                                    <input type="checkbox" class="form-checkbox" <?php echo $report['status'] ? 'checked' : ''; ?> onchange="toggleReportStatus(<?php echo $report['id']; ?>, this.checked ? 1 : 0)">
                                    <span class="slider round"></span>
                                </label>
                            </td>
                            <td class="action-cell">
                                <?php if ($report['reported_type'] == 'post'): ?>
                                    <a href="/post_id<?php echo $report['reported_id']; ?>.html" target="_blank" class="btn btn-sm btn-secondary">预览</a>
                                <?php elseif ($report['reported_type'] == 'comment'): ?>
                                    <a href="/post_id<?php echo $comment_post_ids[$report['reported_id']] ?? '#'; ?>.html" target="_blank" class="btn btn-sm btn-secondary">预览</a>
                                <?php endif; ?>
                                <a href="#" onclick="deleteReport(<?php echo $report['id']; ?>); return false;" class="btn btn-sm btn-danger">删除</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>
<style>
    .admin-table.reports-manage {
        table-layout: auto !important;
        border-collapse: collapse !important;
        border-spacing: 0 !important;
    }

    .admin-table.reports-manage tbody tr {
        height: 76px !important;
        line-height: 76px !important;
        box-sizing: border-box !important;
        margin: 0 !important;
        padding: 0 !important;
        display: table-row !important;
    }

    .admin-table.reports-manage th,
    .admin-table.reports-manage td {
        min-width: 100px;
        padding: 0 20px !important;
        height: 74.5px !important;
        line-height: 74.5px !important;
        box-sizing: border-box !important;
        vertical-align: middle !important;
        margin: 0 !important;
        border: none !important;
        border-bottom: 1px solid #e5e7eb !important;
        outline: none !important;
    }

    .admin-table.reports-manage th:first-child,
    .admin-table.reports-manage td:first-child {
        width: 70px !important;
        min-width: 70px !important;
        max-width: 70px !important;
    }

    .admin-table.reports-manage th:nth-child(2),
    .admin-table.reports-manage td:nth-child(2) {
        min-width: 200px;
        max-width: 200px;
    }

    .admin-table.reports-manage th:nth-child(3),
    .admin-table.reports-manage td:nth-child(3) {
        min-width: 100px;
    }

    .admin-table.reports-manage th:nth-child(4),
    .admin-table.reports-manage td:nth-child(4) {
        width: 200px !important;
        min-width: 200px !important;
        max-width: 200px !important;
    }

    .admin-table.reports-manage th:nth-child(5),
    .admin-table.reports-manage td:nth-child(5) {
        min-width: 100px;
    }

    .admin-table.reports-manage th:nth-child(6),
    .admin-table.reports-manage td:nth-child(6) {
        width: 120px !important;
        min-width: 120px !important;
        max-width: 120px !important;
       
    }

    .admin-table.reports-manage th:nth-child(7),
    .admin-table.reports-manage td:nth-child(7) {
        min-width: 140px !important;
        text-align: right !important;
    }

    .audit-header-wrap {
        position: relative;
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    #audit-header.audit-header-trigger {
        display: inline-flex;
        align-items: center;
        position: relative;
        padding-right: 30px;
        cursor: pointer;
        font-weight: 600;
    }

    #audit-header.audit-header-trigger::after {
        content: '';
        position: absolute;
        right: 6px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 16px;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23666' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3 6l5 5 5-5'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 16px;
        pointer-events: none;
    }

    #audit-dropdown-menu.audit-dropdown-menu {
        border: 1px solid #ddd;
        border-radius: 0px;
        background-color: #fff;
        box-shadow: none;
        max-height: 300px;
        overflow-y: auto;
        padding: 0;
        width: 125px;
    }

    #audit-dropdown-menu .audit-dropdown-item {
        height: 30px;
        line-height: 30px;
        padding: 0 10px;
        font-size: 14px;
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #333;
    }

    #audit-dropdown-menu .audit-dropdown-item:hover {
        background-color: var(--primary-color);
        color: #fff;
    }

    .admin-table.reports-manage td .theme-switch {
        vertical-align: middle !important;
        display: inline-block !important;
        margin: 0 !important;
        position: relative !important;
        top: 1px !important;
        margin-right: 10px !important;
    }


    .admin-table.reports-manage .action-cell {
        text-align: right !important;
        white-space: nowrap !important;
    }

   

    .admin-table.reports-manage .action-cell .btn-sm:first-child {
        margin-left: 0 !important;
    }

    .admin-table.reports-manage .report-content-text[data-qk-tip],
    .admin-table.reports-manage .report-reason-text[data-qk-tip] {
        display: inline;
        line-height: 1.4 !important;
        vertical-align: middle;
        cursor: default;
    }






    @media (max-width: 768px) {
        .admin-table.reports-manage {
            table-layout: auto !important;
            width: 100% !important;
            min-width: auto !important;
        }

        .admin-table.reports-manage th,
        .admin-table.reports-manage td {
            height: 40px !important;
            line-height: 1.4 !important;
            padding: 8px 6px !important;
            font-size: 14px !important;
            white-space: nowrap !important;
            overflow: visible !important;
            text-overflow: clip !important;
            min-width: auto !important;
            max-width: none !important;
            width: auto !important;
        }

        .admin-table.reports-manage td:last-child {
            display: flex !important;
            align-items: center !important;
            gap: 8px !important;
            flex-wrap: wrap !important;
            justify-content: flex-end !important;
            padding: 8px 10px !important;
            min-height: 70px !important;
            height: auto !important;
            line-height: 1.4 !important;
        }


        .admin-table.reports-manage th:nth-child(2),
        .admin-table.reports-manage td:nth-child(2) {
            display: none !important;
        }

        .admin-table.reports-manage th:nth-child(5),
        .admin-table.reports-manage td:nth-child(5) {
            display: none !important;
        }

        .admin-table.reports-manage th:nth-child(6),
        .admin-table.reports-manage td:nth-child(6) {
            width: 70px !important;
            min-width: 70px !important;
            max-width: 70px !important;
            text-align: center !important;
            padding: 8px 4px !important;
        }

        .admin-table.reports-manage th:nth-child(4),
        .admin-table.reports-manage td:nth-child(4) {
            width: 60px !important;
            min-width: 60px !important;
            max-width: 60px !important;
            text-align: center !important;
            padding: 8px 4px !important;
        }


    }
</style>
<script>
    const TYPE_MAP = {
        'post': '文章',
        'comment': '评论',
        'user': '用户'
    };

    function getTypeName(type) {
        return TYPE_MAP[type] || type;
    }

    function closeAllReportMenus() {
        const menu = document.getElementById('audit-dropdown-menu');
        if (menu) {
            menu.style.display = 'none';
        }
    }

    window.addEventListener('scroll', function() {
        closeAllReportMenus();
    }, { passive: true });

    function toggleAuditMenu() {
        const auditHeader = document.getElementById('audit-header');
        const auditDropdownMenu = document.getElementById('audit-dropdown-menu');
        if (!auditHeader || !auditDropdownMenu) return;

        const isOpen = auditDropdownMenu.style.display === 'block';
        if (isOpen) {
            auditDropdownMenu.style.display = 'none';
            return;
        }

        if (auditDropdownMenu.parentElement !== document.body) {
            document.body.appendChild(auditDropdownMenu);
        }

        const rect = auditHeader.getBoundingClientRect();
        auditDropdownMenu.style.position = 'fixed';
        auditDropdownMenu.style.top = (rect.bottom - 23) + 'px';
        auditDropdownMenu.style.left = rect.left + 'px';
        auditDropdownMenu.style.zIndex = '2147483647';
        auditDropdownMenu.style.display = 'block';
    }

    function filterAuditStatus(status) {
        const auditDropdownMenu = document.getElementById('audit-dropdown-menu');
        if (auditDropdownMenu) auditDropdownMenu.style.display = 'none';
        changeStatus(status);
    }

    function changeStatus(status) {
        if (typeof HeaderPagination !== 'undefined') {
            const urlParams = new URLSearchParams(window.location.search);
            if (status === 'all') {
                urlParams.delete('status');
            } else {
                urlParams.set('status', status);
            }
            urlParams.delete('page');
            urlParams.delete('posts_per_page');
            for (const key of Array.from(urlParams.keys())) {
                if (key.match(/^p\d+_s\d+$/)) urlParams.delete(key);
            }
            const pageSize = HeaderPagination.state && HeaderPagination.state.pageSize ? HeaderPagination.state.pageSize : 30;
            let newUrl = '?tab=reports&p1_s' + pageSize;
            for (const [key, value] of urlParams.entries()) {
                if (key !== 'tab') newUrl += '&' + key + '=' + encodeURIComponent(value);
            }
            window.history.pushState({}, document.title, newUrl);

            HeaderPagination.state.page = 1;
            HeaderPagination.load();
        }
    }

    function updateReportList(reports) {
        const tbody = document.querySelector('.admin-table.reports-manage tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (!reports || reports.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align:center !important;height:75px;line-height:75px;font-size:16px;color:#64748b;">当前列表暂无数据</td></tr>';
            return;
        }

        reports.forEach(report => {
            const row = document.createElement('tr');
            const previewHtml = report.reported_type == 'post' ?
                `<a href="/post_id${report.reported_id}.html" target="_blank" class="btn btn-sm btn-secondary">预览</a>` :
                report.reported_type == 'comment' ?
                `<a href="/post_id${report.comment_post_id || report.reported_id}.html" target="_blank" class="btn btn-sm btn-secondary">预览</a>` : '';

            let reportedFull = '';
            if (report.reported_type == 'post') {
                reportedFull = report.reported_title || '';
            } else if (report.reported_type == 'comment') {
                reportedFull = report.reported_full || report.reported_title || '';
            } else if (report.reported_type == 'user') {
                reportedFull = report.reported_title || '';
            }
            const reasonFull = report.reason_full || report.reason || '';
            const reasonDisplay = reasonFull.length > 20 ? reasonFull.substring(0, 20) + '...' : reasonFull;

            row.innerHTML = `
            <td>${report.id}</td>
            <td><span class="report-content-text" data-qk-tip="${escapeHtmlAttr(reportedFull)}">${escapeHtml(report.reported_title || '')}</span></td>
            <td>${getTypeName(report.reported_type)}</td>
            <td><span class="report-reason-text" data-qk-tip="${escapeHtmlAttr(reasonFull)}">${escapeHtml(reasonDisplay)}</span></td>
            <td>${typeof window.formatDateYMD === 'function' ? window.formatDateYMD(report.created_at) : '-'}</td>
            <td class="review-cell">
                <label class="theme-switch">
                    <input type="checkbox" class="form-checkbox" ${report.status ? 'checked' : ''} onchange="toggleReportStatus(${report.id}, this.checked ? 1 : 0)">
                    <span class="slider round"></span>
                </label>
            </td>
            <td class="action-cell">
                ${previewHtml}
                <a href="#" onclick="deleteReport(${report.id}); return false;" class="btn btn-sm btn-danger">删除</a>
            </td>
        `;
            tbody.appendChild(row);
        });
    }

    function escapeHtml(str) {
        if (typeof str !== 'string') return '';
        return str.replace(/&/g, '&amp;')
                  .replace(/</g, '&lt;')
                  .replace(/>/g, '&gt;');
    }

    function escapeHtmlAttr(str) {
        if (typeof str !== 'string') return '';
        return str.replace(/&/g, '&amp;')
                  .replace(/"/g, '&quot;')
                  .replace(/'/g, '&#39;')
                  .replace(/</g, '&lt;')
                  .replace(/>/g, '&gt;');
    }

    function renderReportsList(pageData) {
        const reports = (pageData && (pageData.reports || pageData.data?.reports)) || [];
        updateReportList(reports);
    }

    function toggleReportStatus(reportId, status) {
        const url = '/admin/admin.php?tab=reports&action=status&id=' + reportId + '&status=' + status;
        fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.text())
            .then(data => {
                try {
                    const response = JSON.parse(data);
                    if (response.success) {
                        showToast(response.message || '状态更新成功', 'info', 2000);
                        if (typeof HeaderPagination !== 'undefined') HeaderPagination.load();
                    } else {
                        showToast(response.message || '状态更新失败', 'error', 2000);
                        if (event.target) event.target.checked = !event.target.checked;
                    }
                } catch (e) {
                    if (data.includes('success')) {
                        showToast('状态更新成功', 'info', 2000);
                        if (typeof HeaderPagination !== 'undefined') HeaderPagination.load();
                    }
                }
            })
            .catch(error => {
                console.error('状态更新失败:', error);
                showToast('状态更新失败！', 'error');
                if (event.target) event.target.checked = !event.target.checked;
            });
    }

    function deleteReport(reportId) {
        const url = '/admin/admin.php?tab=reports&delete_report=' + reportId;
        fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.text())
            .then(data => {
                try {
                    const response = JSON.parse(data);
                    if (response.success) {
                        showToast(response.message || '举报删除成功', 'success', 2000);
                        if (typeof HeaderPagination !== 'undefined') HeaderPagination.load();
                    } else {
                        showToast(response.message || '举报删除失败', 'error', 2000);
                    }
                } catch (e) {
                    if (data.includes('success')) {
                        showToast('举报删除成功', 'success', 2000);
                        if (typeof HeaderPagination !== 'undefined') HeaderPagination.load();
                    }
                }
            })
            .catch(error => {
                console.error('删除举报失败:', error);
                showToast('举报删除失败', 'error', 2000);
            });
    }
</script>
