<?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('message')} 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('message')} 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('message')} 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']);
        $db->delete('message', 'id = ?', [$id]);
        addLog('删除', '站内消息', '删除消息ID ' . $id);
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
    if ($action === 'read') {
        $id = intval($_POST['id']);
        $db->update('message', ['is_read' => 1, 'read_time' => time()], 'id = ?', [$id]);
        echo json_encode(['code' => 200, 'msg' => '已标记']);
        exit;
    }
    if ($action === 'read_all') {
        $db->query("UPDATE {$db->table('message')} SET is_read=1, read_time=" . time() . " WHERE is_read=0");
        addLog('标记已读', '站内消息', '标记所有消息已读');
        echo json_encode(['code' => 200, 'msg' => '全部已读']);
        exit;
    }
}

if ($action === 'view') {
    $row = $db->fetch("SELECT * FROM {$db->table('message')} WHERE id = ?", [intval($_GET['id'])]);
    if ($row && $row['is_read'] == 0) {
        $db->update('message', ['is_read' => 1, 'read_time' => time()], 'id = ?', [$row['id']]);
    }
    ?>
    <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></div>
            </div>
            <div class="page-actions"><a href="?act=message" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <div class="content-card">
            <table class="detail-table" style="max-width:700px;">
                <tr><td style="width:100px;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 style="font-weight:600;"><?php echo htmlspecialchars($row['title']); ?></td></tr>
                <tr><td style="color:#64748b;">时间</td><td><?php echo $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 $row['is_read'] ? 'badge-success' : 'badge-warning'; ?>"><?php echo $row['is_read'] ? '已读' : '未读'; ?></span>
                </td></tr>
                <tr><td style="color:#64748b;vertical-align:top;">内容</td><td style="white-space:pre-wrap;padding:12px 0;"><?php echo htmlspecialchars($row['content']); ?></td></tr>
            </table>
        </div>
    </div>
    <script>lucide.createIcons();
    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=message&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
    exit;
}

if ($action === 'list') {
    $lists = $db->fetchAll("SELECT * FROM {$db->table('message')} ORDER BY id DESC");
    $unreadCount = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('message')} WHERE is_read = 0")['cnt'];
    $totalMessages = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('message')}")['cnt'];
    ?>
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><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 class="stat-info"><div class="stat-value"><?php echo $totalMessages; ?></div><div class="stat-label">消息总数</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:#fff7ed;color:#f97316;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 8l10 6 10-6"/><path d="M2 8v13h20V8"/><path d="M22 12l-10 6-10-6"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $unreadCount; ?></div><div class="stat-label">未读消息</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <?php if ($unreadCount > 0): ?>
        <a href="javascript:readAll();" class="btn btn-secondary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg> 全部标为已读</a>
        <?php endif; ?>
    </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:50px;">ID</th><th>发件人</th><th>收件人</th><th>标题</th><th style="width:140px;">时间</th><th style="width:100px;">状态</th><th style="width:250px;">操作</th></tr>
            </thead>
            <tbody>
                <?php foreach ($lists as $item): ?>
                <tr style="<?php echo $item['is_read'] ? '' : 'font-weight:600;'; ?>">
                    <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 $item['create_time'] ? date('Y-m-d H:i', $item['create_time']) : '-'; ?></td>
                    <td>
                        <?php if ($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"><svg style="width:14px;height:14px;" 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>
                            <a href="javascript:delMsg(<?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 endif; ?>
    </div>
    <script>
    function delMsg(id) { if (confirm('确定删除?')) { fetch('?act=message&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 readAll() { if (confirm('确定全部标记为已读?')) { fetch('?act=message&action=read_all', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'}}).then(r=>r.json()).then(d=>{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=message&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
}
?>

