<?php
/**
 * 我的勋章页面
 */
require_once __DIR__ . '/includes/functions.php';

// 检查是否登录
if (!isLoggedIn()) {
    redirect(SITE_URL . '/login.php');
}

$currentUser = getCurrentUser();

// 处理佩戴/取消佩戴勋章
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');
        }
    }
    
    redirect(SITE_URL . '/medals.php');
}

// 检查是否有待解锁的勋章（从通知跳转过来）
$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']);
    }
    redirect(SITE_URL . '/medals.php');
}

// 获取用户的所有勋章
$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__ . '/templates/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="container" style="max-width: 1000px; margin: 20px auto; padding: 0 15px;">
    <div class="card">
        <div class="card-header" style="padding: 20px; border-bottom: 1px solid #eee;">
            <h1 style="font-size: 24px; margin: 0;"><i class="fas fa-medal"></i> 我的勋章</h1>
            <p style="color: #666; margin: 10px 0 0 0;">已获得 <?php echo count($userMedals); ?> / <?php echo count($allMedals); ?> 个勋章</p>
        </div>

        <!-- 已佩戴的勋章 -->
        <?php if (!empty($wearingMedals)): ?>
        <div style="padding: 20px; background: #f8f9fa; border-bottom: 1px solid #eee;">
            <h3 style="font-size: 16px; margin: 0 0 15px 0; color: #666;"><i class="fas fa-check-circle"></i> 当前佩戴</h3>
            <div style="display: flex; gap: 15px; flex-wrap: wrap;">
                <?php foreach ($wearingMedals as $medal): ?>
                <div style="display: flex; align-items: center; gap: 10px; background: white; padding: 10px 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="<?php echo e($medal['name']); ?>" style="width: 40px; height: 40px; object-fit: contain;">
                    <div>
                        <div style="font-weight: bold; font-size: 14px;"><?php echo e($medal['name']); ?></div>
                        <div style="font-size: 12px; color: #999;"><?php echo e($medal['description']); ?></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- 所有勋章列表 -->
        <div style="padding: 20px;">
            <h3 style="font-size: 16px; margin: 0 0 20px 0; color: #666;"><i class="fas fa-th-large"></i> 勋章墙</h3>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;">
                <?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="medal-card" style="border: 2px solid <?php echo $hasMedal ? '#4CAF50' : '#e0e0e0'; ?>; border-radius: 12px; padding: 20px; background: <?php echo $hasMedal ? '#f8fff8' : '#fafafa'; ?>; position: relative; transition: all 0.3s;">
                    <?php if ($hasMedal): ?>
                        <div style="position: absolute; top: -10px; right: -10px; background: #4CAF50; color: white; width: 30px; height: 30px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px;">
                            <i class="fas fa-check"></i>
                        </div>
                    <?php endif; ?>
                    
                    <div style="display: flex; gap: 15px; align-items: center; margin-bottom: 15px;">
                        <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="<?php echo e($medal['name']); ?>" style="width: 60px; height: 60px; object-fit: contain; <?php echo $hasMedal ? '' : 'filter: grayscale(100%) opacity(0.5);'; ?>">
                        <div style="flex: 1;">
                            <div style="font-weight: bold; font-size: 16px; margin-bottom: 5px;"><?php echo e($medal['name']); ?></div>
                            <div style="font-size: 13px; color: #666;"><?php echo e($medal['description']); ?></div>
                        </div>
                    </div>
                    
                    <!-- 进度条 -->
                    <div style="margin-bottom: 15px;">
                        <div style="display: flex; justify-content: space-between; font-size: 12px; color: #666; margin-bottom: 5px;">
                            <span><?php echo $progress['label']; ?></span>
                            <span><?php echo $progress['percentage']; ?>%</span>
                        </div>
                        <div style="width: 100%; height: 8px; background: #e0e0e0; border-radius: 4px; overflow: hidden;">
                            <div style="width: <?php echo $progress['percentage']; ?>%; height: 100%; background: <?php echo $hasMedal ? '#4CAF50' : '#3498db'; ?>; border-radius: 4px; transition: width 0.5s ease;"></div>
                        </div>
                    </div>
                    
                    <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 15px; border-top: 1px solid #e0e0e0;">
                        <span style="font-size: 12px; color: #999;">
                            <i class="fas fa-trophy"></i> 
                            <?php echo getMedalUserCount($medal['id']); ?> 人获得
                        </span>
                        
                        <?php if ($hasMedal): ?>
                            <span style="font-size: 12px; color: #999;">
                                <i class="fas fa-clock"></i> 
                                <?php echo date('Y-m-d', strtotime($awardedAt)); ?> 获得
                            </span>
                        <?php elseif ($progress['percentage'] >= 100): ?>
                            <span style="font-size: 12px; color: #4CAF50; font-weight: bold;">
                                <i class="fas fa-unlock"></i> 可解锁
                            </span>
                        <?php else: ?>
                            <span style="font-size: 12px; color: #999;">
                                <i class="fas fa-lock"></i> 未解锁
                            </span>
                        <?php endif; ?>
                    </div>
                    
                    <div style="margin-top: 10px; text-align: right;">
                        <?php if ($hasMedal): ?>
                            <form method="POST" action="" style="margin: 0; display: inline;">
                                <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="btn btn-sm btn-outline" style="font-size: 12px;">
                                        <i class="fas fa-times"></i> 取消佩戴
                                    </button>
                                <?php else: ?>
                                    <input type="hidden" name="action" value="wear">
                                    <button type="submit" class="btn btn-sm btn-primary" style="font-size: 12px;">
                                        <i class="fas fa-check"></i> 佩戴
                                    </button>
                                <?php endif; ?>
                            </form>
                        <?php elseif ($progress['percentage'] >= 100): ?>
                            <!-- 满足条件但未解锁，显示解锁按钮 -->
                            <form method="POST" action="" style="margin: 0; display: inline;">
                                <input type="hidden" name="medal_id" value="<?php echo $medal['id']; ?>">
                                <input type="hidden" name="action" value="unlock">
                                <button type="submit" class="btn btn-sm btn-success" style="font-size: 12px; background: #4CAF50; border-color: #4CAF50;">
                                    <i class="fas fa-gift"></i> 点击解锁
                                </button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<style>
.medal-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
</style>

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