<?php
require_once __DIR__ . '/../MPHX/common.php';

$user = check_user();

// 获取用户ID（从数据库获取真实的用户ID）
$user_db_id = $user['id'];

// 获取筛选参数
$category = isset($_GET['category']) ? $_GET['category'] : '';

// 验证分类参数，防止SQL注入
$allowed_categories = array('', 'general', 'maintenance', 'update', 'important', 'activity');
if (!in_array($category, $allowed_categories)) {
    $category = '';
}

// 构建查询条件
$where = "WHERE user_id = $user_db_id AND type = 'announcement'";
if ($category) {
    $where .= " AND category = '$category'";
}

// 查询通知列表
$sql = "SELECT * FROM notifications $where ORDER BY create_time DESC LIMIT 50";
$result = $DB->query($sql);

$notifications = [];
while ($row = $DB->fetch($result)) {
    $notifications[] = $row;
}
?>

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/all.min.css">
<link rel="stylesheet" href="css/style.css">

<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.bundle.min.js"></script>

<style>
    .notifications-container {
        padding: 24px;
        max-width: 900px;
        margin: 0 auto;
    }
    .panel-header {
        margin-bottom: 24px;
        text-align: center;
    }
    .panel-header h2 {
        color: #188038;
        font-size: 20px;
        font-weight: 600;
        margin: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
    }
    .panel-header p {
        color: #5f6368;
        font-size: 13px;
        margin: 8px 0 0 0;
    }
    .notification-card {
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        border: 1px solid #e8eaed;
        margin-bottom: 16px;
        transition: all 0.3s ease;
        position: relative;
    }
    .notification-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.12);
    }
    .notification-card.unread {
        border-left: 4px solid #188038;
        background: #f8f9fa;
    }
    .notification-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
    }
    .notification-title {
        font-size: 16px;
        font-weight: 500;
        color: #202124;
        margin: 0;
    }
    .notification-time {
        font-size: 12px;
        color: #5f6368;
    }
    .notification-content {
        font-size: 14px;
        color: #5f6368;
        line-height: 1.5;
        margin-bottom: 12px;
    }
    .btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        padding: 8px 16px;
        cursor: pointer;
        transition: background 0.2s;
        border: none;
        text-decoration: none;
    }
    .btn-primary {
        background: #188038;
        color: #fff;
    }
    .btn-primary:hover {
        background: #137333;
    }
    .btn-sm {
        padding: 4px 10px;
        font-size: 12px;
    }
    .btn-outline {
        background: transparent;
        border: 1px solid #e8eaed;
        color: #5f6368;
    }
    .btn-outline:hover {
        background: #f1f3f4;
        color: #202124;
    }
    .notification-type {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 8px;
    }
    .notification-type.info {
        background: #e3f2fd;
        color: #1976d2;
    }
    .notification-category {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 8px;
        margin-left: 8px;
    }
    .notification-category.general {
        background: #e3f2fd;
        color: #1976d2;
    }
    .notification-category.maintenance {
        background: #fff3e0;
        color: #ef6c00;
    }
    .notification-category.update {
        background: #e8f5e9;
        color: #2e7d32;
    }
    .notification-category.important {
        background: #ffebee;
        color: #c62828;
    }
    .notification-category.activity {
        background: #f3e5f5;
        color: #7b1fa2;
    }
    .category-filter {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 20px;
        padding: 12px;
        background: #f8f9fa;
        border-radius: 8px;
    }
    .category-filter a {
        padding: 6px 12px;
        border-radius: 16px;
        border: 1px solid #e8eaed;
        background: #fff;
        color: #5f6368;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.2s;
        text-decoration: none;
    }
    .category-filter a:hover {
        background: #e8eaed;
    }
    .category-filter a.active {
        background: #188038;
        color: #fff;
        border-color: #188038;
    }
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #5f6368;
    }
    .empty-state i {
        font-size: 48px;
        margin-bottom: 16px;
        color: #dadce0;
    }
    .notification-badge {
        position: absolute;
        top: 12px;
        right: 12px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #188038;
    }
    .notification-actions {
        display: flex;
        gap: 8px;
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid #e8eaed;
    }
    .mark-all-read {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }
    .mark-all-read .btn {
        font-size: 13px;
    }
    .toast {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        z-index: 9999;
        display: none;
    }
    .toast.success {
        background: #188038;
    }
    .toast.error {
        background: #c62828;
    }
    @media (max-width: 768px) {
        .notifications-container {
            padding: 16px;
        }
        .notification-card {
            padding: 16px;
        }
        .notification-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
        }
    }
</style>

<script>
    // 查看通知详情并自动标记已读
    function viewNotification(id, title, content) {
        // 显示详情对话框
        document.getElementById('viewTitle').textContent = title;
        document.getElementById('viewContent').textContent = content;
        $('#viewModal').modal('show');
        
        // 自动标记为已读（不刷新页面，只更新UI）
        fetch('../user/api/api_router.php', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=marknotificationread&id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 'success') {
                // 更新当前卡片状态（移除未读标记）
                var card = document.getElementById('notif-' + id);
                if (card) {
                    card.classList.remove('unread');
                    var badge = card.querySelector('.notification-badge');
                    if (badge) {
                        badge.remove();
                    }
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }

    // 标记单条通知为已读
    function markAsRead(id) {
        fetch('../user/api/api_router.php', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=marknotificationread&id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 'success') {
                showToast('标记已读成功', 'success');
                // 更新当前卡片状态
                var card = document.getElementById('notif-' + id);
                if (card) {
                    card.classList.remove('unread');
                    var badge = card.querySelector('.notification-badge');
                    if (badge) {
                        badge.remove();
                    }
                }
            } else {
                showToast(data.msg || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('网络错误', 'error');
        });
    }

    // 标记所有通知为已读
    function markAllAsRead() {
        fetch('../user/api/api_router.php', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=markallnotificationsread'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 'success') {
                showToast('全部已标记为已读', 'success');
                // 更新所有卡片状态
                var cards = document.querySelectorAll('.notification-card.unread');
                cards.forEach(function(card) {
                    card.classList.remove('unread');
                    var badge = card.querySelector('.notification-badge');
                    if (badge) {
                        badge.remove();
                    }
                });
            } else {
                showToast(data.msg || '操作失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('网络错误', 'error');
        });
    }

    // 删除通知
    function deleteNotification(id) {
        if (!confirm('确定要删除这条通知吗？')) {
            return;
        }
        
        fetch('../user/api/api_router.php', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=deletenotification&id=' + id
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 'success') {
                showToast('删除成功', 'success');
                // 移除当前卡片
                var card = document.getElementById('notif-' + id);
                if (card) {
                    card.remove();
                }
            } else {
                showToast(data.msg || '删除失败', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('网络错误', 'error');
        });
    }

    // 显示提示消息
    function showToast(message, type) {
        const toast = document.createElement('div');
        toast.className = 'toast ' + type;
        toast.textContent = message;
        document.body.appendChild(toast);
        toast.style.display = 'block';
        
        setTimeout(() => {
            toast.style.display = 'none';
            document.body.removeChild(toast);
        }, 2000);
    }
</script>

<div class="notifications-container">
    <div class="panel-header">
        <h2><i class="fas fa-bullhorn"></i> <?php echo L('title', 'notifications'); ?></h2>
        <p><?php echo L('my_notifications', 'notifications'); ?></p>
    </div>
    
    <div class="mark-all-read">
        <div class="category-filter" style="margin-bottom: 0; padding: 8px;">
            <a href="notifications.php" <?php echo !$category ? 'class="active"' : ''; ?>><?php echo L('all', 'common'); ?></a>
            <a href="notifications.php?category=general" <?php echo $category === 'general' ? 'class="active"' : ''; ?>><?php echo L('type_other', 'notifications'); ?></a>
            <a href="notifications.php?category=maintenance" <?php echo $category === 'maintenance' ? 'class="active"' : ''; ?>>维护</a>
            <a href="notifications.php?category=update" <?php echo $category === 'update' ? 'class="active"' : ''; ?>>更新</a>
            <a href="notifications.php?category=important" <?php echo $category === 'important' ? 'class="active"' : ''; ?>>重要</a>
            <a href="notifications.php?category=activity" <?php echo $category === 'activity' ? 'class="active"' : ''; ?>>活动</a>
        </div>
        <button class="btn btn-primary btn-sm" onclick="markAllAsRead()">
            <i class="fas fa-check-double"></i> <?php echo L('mark_all_read', 'notifications'); ?>
        </button>
    </div>
    
    <?php if (empty($notifications)): ?>
    <div class="empty-state">
        <i class="fas fa-bell-slash"></i>
        <p><?php echo L('no_notifications', 'notifications'); ?></p>
    </div>
    <?php else: ?>
        <?php foreach ($notifications as $notif): ?>
        <div class="notification-card <?php echo $notif['is_read'] == 0 ? 'unread' : ''; ?>" id="notif-<?php echo intval($notif['id']); ?>">
            <?php if ($notif['is_read'] == 0): ?>
            <div class="notification-badge"></div>
            <?php endif; ?>
            
            <?php
            $category_map = array(
                'general' => '通用',
                'maintenance' => '维护',
                'update' => '更新',
                'important' => '重要',
                'activity' => '活动'
            );
            $category_display = isset($category_map[$notif['category']]) ? $category_map[$notif['category']] : $notif['category'];
            ?>
            
            <span class="notification-type info"><?php echo L('notifications', 'menu'); ?></span>
            <?php if ($notif['category']): ?>
            <span class="notification-category <?php echo htmlspecialchars($notif['category']); ?>"><?php echo htmlspecialchars($category_display); ?></span>
            <?php endif; ?>
            
            <div class="notification-header">
                <h4 class="notification-title"><?php echo htmlspecialchars($notif['title']); ?></h4>
                <span class="notification-time"><?php echo htmlspecialchars($notif['create_time']); ?></span>
            </div>
            <div class="notification-content"><?php echo htmlspecialchars($notif['content']); ?></div>
            
            <div class="notification-actions">
                <button class="btn btn-outline btn-sm" onclick="viewNotification(<?php echo $notif['id']; ?>, '<?php echo addslashes($notif['title']); ?>', '<?php echo addslashes($notif['content']); ?>')">
                    <i class="fas fa-eye"></i> <?php echo L('view_detail', 'order'); ?>
                </button>
                <button class="btn btn-outline btn-sm" onclick="deleteNotification(<?php echo $notif['id']; ?>)">
                    <i class="fas fa-trash"></i> <?php echo L('delete', 'common'); ?>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- 查看公告详情模态框 -->
<div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewModalLabel"><?php echo L('title', 'notifications'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <h5 id="viewTitle" style="color: #188038; margin-bottom: 15px;"></h5>
                <div id="viewContent" style="white-space: pre-wrap; line-height: 1.6;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal"><?php echo L('confirm', 'common'); ?></button>
            </div>
        </div>
    </div>
</div>
