<?php
require_once __DIR__ . '/../includes/functions.php';

$currentUser = getCurrentUser();

// 如果没有登录，跳转到登录页
if (!$currentUser) {
    header('Location: ' . SITE_URL . '/mobile/login.php');
    exit;
}

$db = Database::getInstance();

// 获取消息列表 - 适配不同版本的通知表结构
// 先检查通知表有哪些字段
$tableColumns = $db->query("SHOW COLUMNS FROM notifications");
$columnNames = array_column($tableColumns, 'Field');

// 根据实际字段构建查询
$hasPostId = in_array('post_id', $columnNames);
$hasRelatedId = in_array('related_id', $columnNames);
$hasTargetType = in_array('target_type', $columnNames);
$hasTargetId = in_array('target_id', $columnNames);
$hasType = in_array('type', $columnNames);

if ($hasPostId) {
    // 旧版结构，使用 post_id
    $notifications = $db->query(
        "SELECT n.*, u.username, u.avatar, p.title as post_title 
         FROM notifications n 
         LEFT JOIN users u ON n.sender_id = u.id 
         LEFT JOIN posts p ON n.post_id = p.id 
         WHERE n.user_id = ? 
         ORDER BY n.created_at DESC 
         LIMIT 50",
        [$currentUser['id']]
    );
} elseif ($hasRelatedId && $hasTargetType) {
    // 新版结构，使用 related_id 和 target_type
    // 使用 GROUP BY 去重，避免同一回复的多个通知重复显示
    $notifications = $db->query(
        "SELECT n.*, u.username, u.avatar, p.title as post_title 
         FROM notifications n 
         LEFT JOIN users u ON n.sender_id = u.id 
         LEFT JOIN posts p ON (n.target_type = 'post' AND n.related_id = p.id) 
         WHERE n.user_id = ? 
         GROUP BY n.id
         ORDER BY n.created_at DESC 
         LIMIT 50",
        [$currentUser['id']]
    );
} else {
    // 最简结构
    $notifications = $db->query(
        "SELECT n.*, u.username, u.avatar 
         FROM notifications n 
         LEFT JOIN users u ON n.sender_id = u.id 
         WHERE n.user_id = ? 
         ORDER BY n.created_at DESC 
         LIMIT 50",
        [$currentUser['id']]
    );
}

// 标记所有消息为已读
$db->query("UPDATE notifications SET is_read = 1 WHERE user_id = ? AND is_read = 0", [$currentUser['id']]);

$pageTitle = '消息通知';
include __DIR__ . '/includes/header.php';

// 辅助函数：获取通知链接
function getNotificationLink($notification) {
    $type = $notification['type'] ?? '';
    $targetType = $notification['target_type'] ?? '';
    $targetId = intval($notification['target_id'] ?? 0);
    $relatedId = intval($notification['related_id'] ?? 0);
    $postId = intval($notification['post_id'] ?? 0);
    
    // 勋章相关通知
    if ($type === 'medal_unlock' || $type === 'medal_unlocked') {
        return SITE_URL . '/mobile/medals.php';
    }
    
    // 帖子相关通知（点赞、收藏帖子）
    if ($targetType === 'post' && $targetId > 0) {
        return SITE_URL . '/mobile/post.php?id=' . $targetId;
    }
    
    // 回复相关通知 - 优先使用 targetId 查找
    if ($targetType === 'reply' && $targetId > 0) {
        $db = Database::getInstance();
        $reply = $db->queryOne("SELECT post_id FROM replies WHERE id = ?", [$targetId]);
        if ($reply) {
            return SITE_URL . '/mobile/post.php?id=' . $reply['post_id'] . '&highlight=' . $targetId . '#reply-' . $targetId;
        }
    }
    
    // 如果 targetId 找不到，尝试用 relatedId
    if ($targetType === 'reply' && $relatedId > 0) {
        $db = Database::getInstance();
        $reply = $db->queryOne("SELECT post_id FROM replies WHERE id = ?", [$relatedId]);
        if ($reply) {
            return SITE_URL . '/mobile/post.php?id=' . $reply['post_id'] . '&highlight=' . $relatedId . '#reply-' . $relatedId;
        }
    }
    
    // 旧版兼容 - 如果只有post_id
    if ($postId > 0) {
        return SITE_URL . '/mobile/post.php?id=' . $postId;
    }
    
    // 如果通知内容包含"回复"字样，尝试从related_id查找
    if ($relatedId > 0 && stripos($notification['content'] ?? '', '回复') !== false) {
        $db = Database::getInstance();
        $reply = $db->queryOne("SELECT post_id FROM replies WHERE id = ?", [$relatedId]);
        if ($reply) {
            return SITE_URL . '/mobile/post.php?id=' . $reply['post_id'] . '&highlight=' . $relatedId . '#reply-' . $relatedId;
        }
    }
    
    return '';
}

// 辅助函数：获取通知图标
function getNotificationIcon($notification) {
    $type = $notification['type'] ?? '';
    
    switch ($type) {
        case 'like':
            return ['fas fa-thumbs-up', '#ff6b6b'];
        case 'favorite':
            return ['fas fa-star', '#ffd700'];
        case 'reply':
            return ['fas fa-comment', '#3498db'];
        case 'follow':
            return ['fas fa-user-plus', '#9b59b6'];
        case 'medal_unlock':
        case 'medal_unlocked':
            return ['fas fa-trophy', '#ff9800'];
        default:
            return ['fas fa-bell', '#999'];
    }
}

// 辅助函数：判断是否是系统消息
function isSystemNotification($notification) {
    $type = $notification['type'] ?? '';
    return in_array($type, ['medal_unlock', 'medal_unlocked']);
}

// 辅助函数：获取勋章信息
function getMedalInfo($medalId) {
    if ($medalId <= 0) return null;
    $db = Database::getInstance();
    return $db->queryOne("SELECT * FROM medals WHERE id = ?", [$medalId]);
}
?>

<!-- 返回按钮 -->
<div class="mobile-back-bar">
    <a href="javascript:history.back();" class="mobile-back-btn">
        <i class="fas fa-arrow-left"></i> 返回
    </a>
</div>

<div class="mobile-section">
    <div class="mobile-section-title">
        <i class="fas fa-bell" style="color: var(--primary-color);"></i>
        <span>消息通知</span>
    </div>
    
    <?php if (empty($notifications)): ?>
    <div class="mobile-empty">
        <i class="fas fa-bell-slash"></i>
        <p>暂无消息通知</p>
    </div>
    <?php else: ?>
    <div class="mobile-notification-list">
        <?php foreach ($notifications as $notification): 
            $link = getNotificationLink($notification);
            $iconInfo = getNotificationIcon($notification);
            $isSystem = isSystemNotification($notification);
            $isUnread = empty($notification['is_read']);
            
            // 获取勋章信息（如果是勋章通知）
            $medalInfo = null;
            if ($isSystem && !empty($notification['related_id'])) {
                $medalInfo = getMedalInfo($notification['related_id']);
            }
        ?>
        <div class="mobile-notification-item <?php echo $isUnread ? 'unread' : ''; ?>" 
             <?php if ($link): ?>onclick="location.href='<?php echo $link; ?>'"<?php endif; ?>
             style="<?php echo $link ? 'cursor: pointer;' : ''; ?>">
            <div class="mobile-notification-avatar" style="background: <?php echo $iconInfo[1]; ?>20;">
                <?php if ($isSystem): ?>
                    <!-- 系统消息显示奖杯图标 -->
                    <i class="fas fa-trophy" style="color: <?php echo $iconInfo[1]; ?>;"></i>
                <?php elseif (!empty($notification['avatar']) && $notification['avatar'] != 'NULL'): ?>
                    <?php
                    // 处理头像路径
                    $notifAvatarUrl = $notification['avatar'];
                    if (!preg_match('/^https?:\/\//', $notifAvatarUrl) && !preg_match('/^\//', $notifAvatarUrl)) {
                        $notifAvatarUrl = SITE_URL . '/' . $notifAvatarUrl;
                    }
                    ?>
                    <img src="<?php echo e($notifAvatarUrl); ?>" alt="" onerror="this.style.display='none'; this.parentElement.querySelector('.avatar-fallback').style.display='flex';">
                    <i class="fas fa-user avatar-fallback" style="display: none;"></i>
                <?php else: ?>
                    <i class="fas fa-user" style="color: <?php echo $iconInfo[1]; ?>"></i>
                <?php endif; ?>
            </div>
            <div class="mobile-notification-content">
                <div class="mobile-notification-header">
                    <?php if ($isSystem): ?>
                        <span class="mobile-notification-system">系统消息</span>
                    <?php elseif (!empty($notification['username'])): ?>
                        <span class="mobile-notification-username"><?php echo e($notification['username']); ?></span>
                    <?php endif; ?>
                    <span class="mobile-notification-type" style="color: <?php echo $iconInfo[1]; ?>">
                        <i class="<?php echo $iconInfo[0]; ?>"></i>
                        <?php echo getNotificationTypeText($notification['type'] ?? ''); ?>
                    </span>
                </div>
                
                <div class="mobile-notification-text" title="<?php echo e(strip_tags($notification['content'] ?? '')); ?>">
                    <?php
                    // 截断过长的回复内容
                    $content = strip_tags($notification['content'] ?? '');
                    if (mb_strlen($content) > 60) {
                        $content = mb_substr($content, 0, 60) . '...';
                    }
                    echo e($content);
                    ?>
                </div>
                
                <?php if ($medalInfo): ?>
                <!-- 勋章解锁显示 -->
                <div class="mobile-notification-medal">
                    <img src="<?php echo SITE_URL . '/' . $medalInfo['icon']; ?>" alt="<?php echo e($medalInfo['name']); ?>">
                    <div class="mobile-notification-medal-info">
                        <div class="mobile-notification-medal-name"><?php echo e($medalInfo['name']); ?></div>
                        <div class="mobile-notification-medal-desc"><?php echo e($medalInfo['description']); ?></div>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($notification['post_title'])): ?>
                <div class="mobile-notification-post">
                    <i class="fas fa-file-alt"></i> <?php echo e($notification['post_title']); ?>
                </div>
                <?php endif; ?>
                
                <div class="mobile-notification-footer">
                    <span class="mobile-notification-time">
                        <i class="far fa-clock"></i> <?php echo formatTime($notification['created_at']); ?>
                    </span>
                    <?php if ($link): ?>
                    <span class="mobile-notification-view">
                        <i class="fas fa-eye"></i> 查看
                    </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<style>
.mobile-back-bar {
    background: #fff;
    padding: 10px 15px;
    border-bottom: 1px solid #f0f0f0;
}
.mobile-back-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    color: #666;
    font-size: 14px;
    text-decoration: none;
}
.mobile-back-btn i {
    font-size: 12px;
}
.mobile-empty {
    text-align: center;
    padding: 60px 20px;
    color: #999;
}
.mobile-empty i {
    font-size: 48px;
    margin-bottom: 15px;
    color: #ddd;
}
.mobile-notification-list {
    display: flex;
    flex-direction: column;
}
.mobile-notification-item {
    display: flex;
    gap: 12px;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    transition: background 0.2s;
}
.mobile-notification-item:active {
    background: #f5f5f5;
}
.mobile-notification-item.unread {
    background: #f0f8ff;
}
.mobile-notification-item.unread .mobile-notification-text {
    font-weight: 500;
}
.mobile-notification-avatar {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    overflow: hidden;
    background: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}
.mobile-notification-avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.mobile-notification-avatar i {
    font-size: 20px;
}
.mobile-notification-avatar .avatar-fallback {
    position: absolute;
    display: none;
}
.mobile-notification-content {
    flex: 1;
    min-width: 0;
}
.mobile-notification-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
    flex-wrap: wrap;
}
.mobile-notification-system {
    font-size: 13px;
    color: #ff9800;
    font-weight: 600;
}
.mobile-notification-username {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}
.mobile-notification-type {
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
}
.mobile-notification-text {
    font-size: 14px;
    color: #333;
    line-height: 1.5;
    margin-bottom: 8px;
}
.mobile-notification-medal {
    display: flex;
    align-items: center;
    gap: 10px;
    background: #fff8e1;
    padding: 10px;
    border-radius: 8px;
    margin-bottom: 8px;
}
.mobile-notification-medal img {
    width: 40px;
    height: 40px;
    object-fit: contain;
}
.mobile-notification-medal-info {
    flex: 1;
}
.mobile-notification-medal-name {
    font-weight: bold;
    font-size: 14px;
    color: #333;
}
.mobile-notification-medal-desc {
    font-size: 12px;
    color: #666;
}
.mobile-notification-post {
    font-size: 12px;
    color: #666;
    background: #f5f5f5;
    padding: 6px 10px;
    border-radius: 4px;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.mobile-notification-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.mobile-notification-time {
    font-size: 12px;
    color: #999;
    display: flex;
    align-items: center;
    gap: 4px;
}
.mobile-notification-view {
    font-size: 12px;
    color: var(--primary-color);
    display: flex;
    align-items: center;
    gap: 4px;
}
</style>

<?php include __DIR__ . '/includes/footer.php'; ?>
