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

$currentUser = getCurrentUser();

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

$db = Database::getInstance();

// 处理佩戴/取消佩戴勋章
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['medal_id'])) {
    $medalId = intval($_POST['medal_id']);
    $action = $_POST['action'] ?? 'wear';
    
    if ($action === 'unlock') {
        // 手动解锁勋章
        $result = unlockMedal($currentUser['id'], $medalId);
        if ($result['success']) {
            setFlashMessage('success', $result['message']);
        } else {
            setFlashMessage('error', $result['message']);
        }
    } else {
        // 检查用户是否拥有该勋章
        if (hasUserMedal($currentUser['id'], $medalId)) {
            toggleWearMedal($currentUser['id'], $medalId, $action === 'wear');
        }
    }
    
    header('Location: ' . SITE_URL . '/mobile/medals.php');
    exit;
}

// 检查是否有待解锁的勋章
$unlockMedalId = isset($_GET['unlock']) ? intval($_GET['unlock']) : 0;
if ($unlockMedalId > 0) {
    $result = unlockMedal($currentUser['id'], $unlockMedalId);
    if ($result['success']) {
        setFlashMessage('success', $result['message']);
    } else {
        setFlashMessage('error', $result['message']);
    }
    header('Location: ' . SITE_URL . '/mobile/medals.php');
    exit;
}

// 获取用户的所有勋章
$userMedals = getUserMedals($currentUser['id']);
$wearingMedals = getUserWearingMedals($currentUser['id']);
$allMedals = getAllMedals();

// 确保是数组
if (!is_array($userMedals)) $userMedals = [];
if (!is_array($wearingMedals)) $wearingMedals = [];
if (!is_array($allMedals)) $allMedals = [];

// 获取用户进度数据
$userStats = $db->queryOne("SELECT post_count, reply_count FROM users WHERE id = ?", [$currentUser['id']]);
$postCount = intval($userStats['post_count'] ?? 0);
$replyCount = intval($userStats['reply_count'] ?? 0);

// 获取帖子被点赞数
$likedCount = $db->queryOne(
    "SELECT COUNT(*) as count FROM likes l INNER JOIN posts p ON l.target_id = p.id WHERE l.target_type = 'post' AND p.user_id = ?",
    [$currentUser['id']]
);
$totalLikes = intval($likedCount['count'] ?? 0);

// 获取帖子被收藏数
$favoritedCount = $db->queryOne(
    "SELECT COUNT(*) as count FROM favorites f INNER JOIN posts p ON f.target_id = p.id WHERE f.target_type = 'post' AND p.user_id = ?",
    [$currentUser['id']]
);
$totalFavorites = intval($favoritedCount['count'] ?? 0);

$pageTitle = '我的勋章';
include __DIR__ . '/includes/header.php';

// 辅助函数：获取进度信息
function getMedalProgress($medal, $replyCount, $totalLikes, $totalFavorites) {
    $current = 0;
    $target = intval($medal['condition_value']);
    $label = '';
    
    switch ($medal['condition_type']) {
        case 'reply_count':
            $current = $replyCount;
            $label = '已回复 ' . $current . ' / ' . $target . ' 次';
            break;
        case 'post_liked':
            $current = $totalLikes;
            $label = '被点赞 ' . $current . ' / ' . $target . ' 次';
            break;
        case 'post_favorited':
            $current = $totalFavorites;
            $label = '被收藏 ' . $current . ' / ' . $target . ' 次';
            break;
    }
    
    $percentage = min(100, round(($current / $target) * 100));
    
    return [
        'current' => $current,
        'target' => $target,
        'percentage' => $percentage,
        'label' => $label
    ];
}
?>

<!-- 返回按钮 -->
<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-medal" style="color: var(--primary-color);"></i>
        <span>我的勋章</span>
    </div>
    
    <!-- 已获得数量 -->
    <div style="padding: 15px; background: #f8f9fa; border-bottom: 1px solid #f0f0f0;">
        <div style="font-size: 14px; color: #666;">
            已获得 <strong style="color: var(--primary-color); font-size: 18px;"><?php echo count($userMedals); ?></strong> / <?php echo count($allMedals); ?> 个勋章
        </div>
    </div>
    
    <!-- 已佩戴的勋章 -->
    <?php if (!empty($wearingMedals)): ?>
    <div style="padding: 15px; border-bottom: 1px solid #f0f0f0;">
        <div style="font-size: 13px; color: #666; margin-bottom: 10px;">
            <i class="fas fa-check-circle"></i> 当前佩戴
        </div>
        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
            <?php foreach ($wearingMedals as $medal): ?>
            <div style="display: flex; align-items: center; gap: 8px; background: white; padding: 8px 12px; border-radius: 20px; border: 1px solid var(--primary-color);">
                <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="<?php echo e($medal['name']); ?>" style="width: 24px; height: 24px; object-fit: contain;">
                <span style="font-size: 13px;"><?php echo e($medal['name']); ?></span>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- 勋章列表 -->
    <div class="mobile-medal-list">
        <?php foreach ($allMedals as $medal): 
            $hasMedal = false;
            $isWearing = false;
            $awardedAt = null;
            
            foreach ($userMedals as $um) {
                if ($um['id'] == $medal['id']) {
                    $hasMedal = true;
                    $isWearing = $um['is_wearing'];
                    $awardedAt = $um['awarded_at'];
                    break;
                }
            }
            
            $progress = getMedalProgress($medal, $replyCount, $totalLikes, $totalFavorites);
        ?>
        <div class="mobile-medal-item <?php echo $hasMedal ? 'has-medal' : ''; ?>">
            <div class="mobile-medal-icon">
                <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="<?php echo e($medal['name']); ?>">
                <?php if ($hasMedal): ?>
                <div class="mobile-medal-check">
                    <i class="fas fa-check"></i>
                </div>
                <?php endif; ?>
            </div>
            <div class="mobile-medal-info">
                <div class="mobile-medal-name"><?php echo e($medal['name']); ?></div>
                <div class="mobile-medal-desc"><?php echo e($medal['description']); ?></div>
                
                <!-- 进度条 -->
                <div class="mobile-medal-progress">
                    <div class="mobile-medal-progress-bar">
                        <div class="mobile-medal-progress-fill" style="width: <?php echo $progress['percentage']; ?>%;"></div>
                    </div>
                    <div class="mobile-medal-progress-text"><?php echo $progress['label']; ?></div>
                </div>
                
                <div class="mobile-medal-meta">
                    <span><i class="fas fa-trophy"></i> <?php echo getMedalUserCount($medal['id']); ?> 人获得</span>
                    <?php if ($hasMedal): ?>
                        <span><i class="fas fa-clock"></i> <?php echo date('Y-m-d', strtotime($awardedAt)); ?></span>
                    <?php elseif ($progress['percentage'] >= 100): ?>
                        <span style="color: var(--primary-color);"><i class="fas fa-unlock"></i> 可解锁</span>
                    <?php else: ?>
                        <span style="color: #999;"><i class="fas fa-lock"></i> 未解锁</span>
                    <?php endif; ?>
                </div>
                
                <?php if ($hasMedal): ?>
                <form method="POST" action="" class="mobile-medal-action">
                    <input type="hidden" name="medal_id" value="<?php echo $medal['id']; ?>">
                    <?php if ($isWearing): ?>
                        <input type="hidden" name="action" value="unwear">
                        <button type="submit" class="mobile-medal-btn unwear">
                            <i class="fas fa-times"></i> 取消佩戴
                        </button>
                    <?php else: ?>
                        <input type="hidden" name="action" value="wear">
                        <button type="submit" class="mobile-medal-btn wear">
                            <i class="fas fa-check"></i> 佩戴
                        </button>
                    <?php endif; ?>
                </form>
                <?php elseif ($progress['percentage'] >= 100): ?>
                <form method="POST" action="" class="mobile-medal-action">
                    <input type="hidden" name="medal_id" value="<?php echo $medal['id']; ?>">
                    <input type="hidden" name="action" value="unlock">
                    <button type="submit" class="mobile-medal-btn unlock">
                        <i class="fas fa-gift"></i> 点击解锁
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</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-medal-list {
    padding: 10px;
}
.mobile-medal-item {
    display: flex;
    gap: 12px;
    padding: 15px;
    background: #fafafa;
    border-radius: 12px;
    margin-bottom: 10px;
    border: 2px solid #e0e0e0;
}
.mobile-medal-item.has-medal {
    background: #f8fff8;
    border-color: var(--primary-color);
}
.mobile-medal-icon {
    position: relative;
    width: 60px;
    height: 60px;
    flex-shrink: 0;
}
.mobile-medal-icon img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
.mobile-medal-item:not(.has-medal) .mobile-medal-icon img {
    filter: grayscale(100%) opacity(0.5);
}
.mobile-medal-check {
    position: absolute;
    top: -5px;
    right: -5px;
    width: 22px;
    height: 22px;
    background: var(--primary-color);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
}
.mobile-medal-info {
    flex: 1;
    min-width: 0;
}
.mobile-medal-name {
    font-weight: bold;
    font-size: 15px;
    margin-bottom: 4px;
}
.mobile-medal-desc {
    font-size: 12px;
    color: #666;
    margin-bottom: 10px;
}
.mobile-medal-progress {
    margin-bottom: 10px;
}
.mobile-medal-progress-bar {
    width: 100%;
    height: 6px;
    background: #e0e0e0;
    border-radius: 3px;
    overflow: hidden;
    margin-bottom: 5px;
}
.mobile-medal-progress-fill {
    height: 100%;
    background: var(--primary-color);
    border-radius: 3px;
    transition: width 0.3s ease;
}
.mobile-medal-progress-text {
    font-size: 11px;
    color: #999;
}
.mobile-medal-meta {
    display: flex;
    justify-content: space-between;
    font-size: 11px;
    color: #999;
    margin-bottom: 10px;
}
.mobile-medal-action {
    margin: 0;
}
.mobile-medal-btn {
    padding: 6px 12px;
    border-radius: 15px;
    font-size: 12px;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}
.mobile-medal-btn.wear {
    background: var(--primary-color);
    color: white;
}
.mobile-medal-btn.unwear {
    background: #f0f0f0;
    color: #666;
}
.mobile-medal-btn.unlock {
    background: #ff9800;
    color: white;
}
</style>

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