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

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

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;
    }

    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $ajaxAct = $_POST['ajax_action'];

    if ($ajaxAct === 'delete') {
        $db->query("DELETE FROM {$db->table('message')} WHERE id IN ($placeholders)", $ids);
        addLog('删除', '站内消息', '批量删除消息 ' . count($ids) . ' 条');
        echo json_encode(['code' => 200, 'msg' => '已删除 ' . count($ids) . ' 条消息']);
        exit;
    }

    if ($ajaxAct === 'read') {
        $db->query(
            "UPDATE {$db->table('message')} SET is_read = 1, read_time = ? WHERE id IN ($placeholders)",
            array_merge([time()], $ids)
        );
        addLog('标记已读', '站内消息', '批量标记已读 ' . count($ids) . ' 条');
        echo json_encode(['code' => 200, 'msg' => '已标记所选消息为已读']);
        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;
        }
        $db->delete('message', 'id = ?', [$id]);
        addLog('删除', '站内消息', '删除消息ID ' . $id);
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }

    if ($action === 'read') {
        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;
        }
        $db->update('message', ['is_read' => 1, 'read_time' => time()], 'id = ?', [$id]);
        addLog('标记已读', '站内消息', '标记消息已读 ID ' . $id);
        echo json_encode(['code' => 200, 'msg' => '已标记为已读']);
        exit;
    }

    if ($action === 'read_all') {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $db->query("UPDATE {$db->table('message')} SET is_read = 1, read_time = ? WHERE is_read = 0", [time()]);
        addLog('标记已读', '站内消息', '全部消息标记已读');
        echo json_encode(['code' => 200, 'msg' => '全部消息已标记为已读']);
        exit;
    }
}

if ($action === 'view') {
    $row = $db->fetch("SELECT * FROM {$db->table('message')} WHERE id = ?", [intval($_GET['id'] ?? 0)]);
    if ($row && intval($row['is_read']) === 0) {
        $db->update('message', ['is_read' => 1, 'read_time' => time()], 'id = ?', [$row['id']]);
        $row['is_read'] = 1;
        $row['read_time'] = time();
    }
    ?>
    <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="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22 6 12 13 2 6"/></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=message" 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['from_name'] ?? '') ?: ('ID:' . ($row['from_id'] ?? 0))); ?></span></div>
            <div class="page-context-item"><span class="page-context-label">收件人</span><span class="page-context-value"><?php echo htmlspecialchars(($row['to_name'] ?? '') ?: ('ID:' . ($row['to_id'] ?? 0))); ?></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_read']) ? '已读' : '未读'; ?></span></div>
        </div>
        <div class="content-card">
            <?php if (!$row): ?>
            <div class="empty-state">
                <h3>消息不存在</h3>
                <p>该消息可能已被删除。</p>
            </div>
            <?php else: ?>
            <table class="detail-table" style="max-width:760px;">
                <tr><td style="width:100px;color:#64748b;">标题</td><td style="font-weight:600;"><?php echo htmlspecialchars($row['title']); ?></td></tr>
                <tr><td style="color:#64748b;">发件人</td><td><?php echo htmlspecialchars(($row['from_name'] ?: ('ID:' . $row['from_id']))); ?></td></tr>
                <tr><td style="color:#64748b;">收件人</td><td><?php echo htmlspecialchars(($row['to_name'] ?: ('ID:' . $row['to_id']))); ?></td></tr>
                <tr><td style="color:#64748b;">时间</td><td><?php echo !empty($row['create_time']) ? date('Y-m-d H:i', $row['create_time']) : '-'; ?></td></tr>
                <tr><td style="color:#64748b;">状态</td><td><span class="badge <?php echo !empty($row['is_read']) ? 'badge-success' : 'badge-warning'; ?>"><?php echo !empty($row['is_read']) ? '已读' : '未读'; ?></span></td></tr>
                <tr><td style="color:#64748b;vertical-align:top;">内容</td><td style="white-space:pre-wrap;padding:12px 0;line-height:1.8;"><?php echo htmlspecialchars($row['content']); ?></td></tr>
            </table>
            <div style="padding:0 24px 24px;display:flex;gap:12px;flex-wrap:wrap;">
                <button type="button" class="btn btn-ghost" style="color:#EF4444;" onclick="delMsg(<?php echo intval($row['id']); ?>)">删除消息</button>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <script>
    function delMsg(id) {
        if (!confirm('确定删除这条消息？')) return;
        fetch('?act=message&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=message';
        }).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;}
    @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
    exit;
}

if ($action === 'list') {
    $lists = $db->fetchAll("SELECT * FROM {$db->table('message')} ORDER BY id DESC");
    $unreadCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('message')} WHERE is_read = 0")['cnt'] ?? 0);
    $totalMessages = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('message')}")['cnt'] ?? 0);
    ?>
    <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="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22 6 12 13 2 6"/></svg></div>
                <div>
                    <h1>站内消息</h1>
                    <p style="font-size:12px;color:#64748b;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 $totalMessages; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">未读消息</span><span class="page-context-value"><?php echo $unreadCount; ?> 条</span></div>
            <div class="page-context-item"><span class="page-context-label">管理重点</span><span class="page-context-value">优先处理未读消息</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">
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <?php if ($unreadCount > 0): ?>
                <button type="button" class="btn btn-secondary" onclick="readAll()">全部标记已读</button>
                <?php endif; ?>
                <button type="button" class="btn btn-secondary" onclick="batchAction('read')">批量标记已读</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"><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>
                <p>当前没有站内消息</p>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width:44px;text-align:center;"><input type="checkbox" onclick="toggleCheckAll(this)" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th>
                        <th style="width:50px;">ID</th>
                        <th>发件人</th>
                        <th>收件人</th>
                        <th>标题</th>
                        <th style="width:140px;">时间</th>
                        <th style="width:100px;">状态</th>
                        <th style="width:280px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <tr style="<?php echo intval($item['is_read']) ? '' : 'font-weight:600;'; ?>">
                        <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><?php echo htmlspecialchars(($item['from_name'] ?: ('ID:' . $item['from_id']))); ?></td>
                        <td><?php echo htmlspecialchars(($item['to_name'] ?: ('ID:' . $item['to_id']))); ?></td>
                        <td><?php echo htmlspecialchars($item['title']); ?></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>
                            <?php if (!empty($item['is_read'])): ?>
                            <span class="badge badge-success">已读</span>
                            <?php else: ?>
                            <span class="badge badge-warning">未读</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="btn-group">
                                <a href="?act=message&action=view&id=<?php echo $item['id']; ?>" class="btn btn-primary">查看</a>
                                <?php if (empty($item['is_read'])): ?>
                                <button type="button" class="btn btn-secondary" onclick="markRead(<?php echo $item['id']; ?>)">标记已读</button>
                                <?php endif; ?>
                                <button type="button" class="btn btn-ghost" style="color:#EF4444;" onclick="delMsg(<?php echo $item['id']; ?>)">删除</button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
    <script>
    function delMsg(id) {
        if (!confirm('确定删除这条消息？')) return;
        fetch('?act=message&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 markRead(id) {
        fetch('?act=message&action=read', {
            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 readAll() {
        if (!confirm('确定把全部消息标记为已读？')) return;
        fetch('?act=message&action=read_all', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).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 + ' 条消息？'
            : '确定标记选中的 ' + ids.length + ' 条消息为已读？';
        if (!confirm(confirmText)) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=message', 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
}
?>
