<?php
ob_start();
requireAdmin();

$message = '';
$error = '';

// 处理发送
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send') {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $type = $_POST['type'] ?? 'system';
    $target_type = $_POST['target_type'] ?? 'all';
    $target_user = trim($_POST['target_user'] ?? '');
    
    if (empty($title) || empty($content)) {
        $error = '标题和内容不能为空';
    } else {
        $title = $db->escape($title);
        $content = $db->escape($content);
        $type = $db->escape($type);
        
        if ($target_type === 'all') {
            // 发送给全体用户
            $db->query("INSERT INTO notifications (user_id, title, content, type) VALUES (0, '$title', '$content', '$type')");
            $message = '已成功发送给全体用户';
        } elseif ($target_type === 'user' && !empty($target_user)) {
            // 发送给指定用户
            $user = $db->fetchOne("SELECT id FROM users WHERE username = '$target_user' OR email = '$target_user'");
            if ($user) {
                $db->query("INSERT INTO notifications (user_id, title, content, type) VALUES ({$user['id']}, '$title', '$content', '$type')");
                $message = "已成功发送给用户：{$target_user}";
            } else {
                $error = '用户不存在';
            }
        } else {
            $error = '请选择发送对象';
        }
    }
}

// 处理删除
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $db->query("UPDATE notifications SET status = 0 WHERE id = $id");
    header('Location: ?page=admin_notifications');
    exit;
}

// 获取发送记录
$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 15;
$offset = ($page - 1) * $perpage;

$total = $db->fetchOne("SELECT COUNT(*) as cnt FROM notifications WHERE status = 1")['cnt'] ?? 0;
$records = $db->fetchAll("
    SELECT n.*, u.username 
    FROM notifications n 
    LEFT JOIN users u ON n.user_id = u.id 
    WHERE n.status = 1 
    ORDER BY n.id DESC 
    LIMIT $offset, $perpage
");
?>

<style>
.admin-notifications {
    max-width: 100%;
    padding: 4px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 28px;
}

.page-header h2 {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
}

.send-card {
    background: white;
    border-radius: 20px;
    padding: 28px;
    margin-bottom: 32px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    border: 1px solid #f0f0f0;
}

.card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
    font-weight: 500;
    color: #374151;
}

.form-group input,
.form-group select,
.form-group textarea {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    font-size: 14px;
    transition: all 0.2s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102,126,234,0.1);
}

.target-user-group {
    display: none;
}

.target-user-group.show {
    display: block;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 12px 24px;
    border-radius: 12px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    background: #667eea;
    color: white;
    font-size: 15px;
}

.btn:hover {
    background: #5a67d8;
}

.alert {
    padding: 14px 18px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.alert-success {
    background: #d1fae5;
    color: #065f46;
}

.alert-error {
    background: #fef2f2;
    color: #991b1b;
}

.table-wrapper {
    background: white;
    border-radius: 20px;
    padding: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    border: 1px solid #f0f0f0;
    overflow-x: auto;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
}

.data-table th {
    padding: 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: #64748b;
    border-bottom: 1px solid #e2e8f0;
}

.data-table td {
    padding: 14px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 14px;
}

.data-table tbody tr:hover {
    background: #f8fafc;
}

.type-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.type-system { background: #e0e7ff; color: #4338ca; }
.type-order { background: #d1fae5; color: #065f46; }
.type-ticket { background: #fef3c7; color: #92400e; }
.type-announcement { background: #fee2e2; color: #991b1b; }

.target-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    background: #f1f5f9;
    color: #64748b;
}

.action-btn {
    color: #ef4444;
    text-decoration: none;
    font-size: 13px;
    cursor: pointer;
}

.action-btn:hover {
    text-decoration: underline;
}

.pagination {
    display: flex;
    justify-content: center;
    gap: 8px;
    margin-top: 24px;
}

.page-link {
    padding: 8px 14px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    color: #64748b;
    text-decoration: none;
}

.page-link.active {
    background: #667eea;
    color: white;
    border-color: #667eea;
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
    }
}
</style>

<div class="admin-notifications">
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:bell.svg?color=%23667eea" width="26" height="26" alt="">
            站内信管理
        </h2>
    </div>
    
    <?php if ($message): ?>
        <div class="alert alert-success">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%23065f46" width="20" height="20" alt="">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-error">
            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23991b1b" width="20" height="20" alt="">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <!-- 发送站内信卡片 -->
    <div class="send-card">
        <div class="card-header">
            <img src="https://api.iconify.design/mdi:send.svg?color=%23667eea" width="22" height="22" alt="">
            <h3>发送站内信</h3>
        </div>
        
        <form method="POST">
            <input type="hidden" name="action" value="send">
            
            <div class="form-row">
                <div class="form-group">
                    <label><img src="https://api.iconify.design/mdi:tag.svg?color=%23667eea" width="16" height="16" alt="">消息类型</label>
                    <select name="type">
                        <option value="system">系统消息</option>
                        <option value="announcement">公告</option>
                        <option value="order">订单相关</option>
                        <option value="ticket">工单相关</option>
                    </select>
                </div>
                <div class="form-group">
                    <label><img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="16" height="16" alt="">发送对象</label>
                    <select name="target_type" id="targetType" onchange="toggleTargetUser()">
                        <option value="all">全体用户</option>
                        <option value="user">指定用户</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group target-user-group" id="targetUserGroup">
                <label><img src="https://api.iconify.design/mdi:account.svg?color=%23667eea" width="16" height="16" alt="">用户名/邮箱</label>
                <input type="text" name="target_user" placeholder="输入用户名或邮箱">
            </div>
            
            <div class="form-group">
                <label><img src="https://api.iconify.design/mdi:format-title.svg?color=%23667eea" width="16" height="16" alt="">消息标题</label>
                <input type="text" name="title" required placeholder="请输入消息标题">
            </div>
            
            <div class="form-group">
                <label><img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="16" height="16" alt="">消息内容</label>
                <textarea name="content" rows="5" required placeholder="请输入消息内容"></textarea>
            </div>
            
            <button type="submit" class="btn">
                <img src="https://api.iconify.design/mdi:send.svg?color=white" width="18" height="18" alt="">
                发送站内信
            </button>
        </form>
    </div>
    
    <!-- 发送记录 -->
    <div class="table-wrapper">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>标题</th>
                    <th>类型</th>
                    <th>接收用户</th>
                    <th>发送时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($records)): ?>
                    <tr>
                        <td colspan="6" style="text-align: center; padding: 40px; color: #94a3b8;">
                            <img src="https://api.iconify.design/mdi:bell-off.svg?color=%2394a3b8" width="32" height="32" alt="">
                            <p>暂无发送记录</p>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($records as $rec): ?>
                        <tr>
                            <td>#<?php echo $rec['id']; ?></td>
                            <td><?php echo htmlspecialchars($rec['title']); ?></td>
                            <td>
                                <span class="type-badge type-<?php echo $rec['type']; ?>">
                                    <?php 
                                    $type_names = ['system' => '系统', 'order' => '订单', 'ticket' => '工单', 'announcement' => '公告'];
                                    echo $type_names[$rec['type']] ?? $rec['type'];
                                    ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($rec['user_id'] == 0): ?>
                                    <span class="target-badge">全体用户</span>
                                <?php else: ?>
                                    <span class="target-badge"><?php echo htmlspecialchars($rec['username'] ?? '用户#'.$rec['user_id']); ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($rec['created_at'])); ?></td>
                            <td>
                                <a href="?page=admin_notifications&delete=<?php echo $rec['id']; ?>" class="action-btn" onclick="return confirm('确定删除这条消息吗？')">
                                    删除
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= ceil($total / $perpage); $i++): ?>
                <a href="?page=admin_notifications&p=<?php echo $i; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<script>
function toggleTargetUser() {
    const select = document.getElementById('targetType');
    const group = document.getElementById('targetUserGroup');
    if (select.value === 'user') {
        group.classList.add('show');
    } else {
        group.classList.remove('show');
    }
}
</script>