<?php
/**
 * 后台 - 勋章管理
 */
require_once __DIR__ . '/../includes/functions.php';

// 检查是否登录且是管理员
if (!isLoggedIn() || !isAdmin()) {
    setFlashMessage('error', '您没有权限访问管理后台');
    redirect(SITE_URL . '/index.php');
}

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$currentUser = getCurrentUser();

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    switch ($action) {
        case 'add':
        case 'edit':
            $medalId = isset($_POST['medal_id']) ? intval($_POST['medal_id']) : 0;
            $name = trim($_POST['name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $icon = trim($_POST['icon'] ?? '');
            $type = $_POST['type'] ?? 'like';
            $conditionType = $_POST['condition_type'] ?? 'post_liked';
            $conditionValue = intval($_POST['condition_value'] ?? 0);
            $sortOrder = intval($_POST['sort_order'] ?? 0);
            $status = isset($_POST['status']) ? 1 : 0;
            
            if (empty($name)) {
                setFlashMessage('error', '勋章名称不能为空');
            } elseif (empty($icon)) {
                setFlashMessage('error', '勋章图标不能为空');
            } else {
                try {
                    if ($medalId > 0) {
                        db()->execute(
                            "UPDATE medals SET name = ?, description = ?, icon = ?, type = ?, condition_type = ?, condition_value = ?, sort_order = ?, status = ? WHERE id = ?",
                            [$name, $description, $icon, $type, $conditionType, $conditionValue, $sortOrder, $status, $medalId]
                        );
                        setFlashMessage('success', '勋章更新成功');
                    } else {
                        db()->execute(
                            "INSERT INTO medals (name, description, icon, type, condition_type, condition_value, sort_order, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                            [$name, $description, $icon, $type, $conditionType, $conditionValue, $sortOrder, $status]
                        );
                        setFlashMessage('success', '勋章添加成功');
                    }
                    redirect(SITE_URL . '/admin/medals.php');
                } catch (Exception $e) {
                    setFlashMessage('error', '操作失败: ' . $e->getMessage());
                }
            }
            break;
            
        case 'award':
            $userId = intval($_POST['user_id'] ?? 0);
            $medalId = intval($_POST['medal_id'] ?? 0);
            
            if ($userId > 0 && $medalId > 0) {
                if (awardMedalToUser($userId, $medalId)) {
                    setFlashMessage('success', '勋章授予成功');
                } else {
                    setFlashMessage('error', '该用户已拥有此勋章');
                }
            }
            redirect(SITE_URL . '/admin/medals.php?action=user_medals&user_id=' . $userId);
            break;
            
        case 'revoke':
            $userId = intval($_POST['user_id'] ?? 0);
            $medalId = intval($_POST['medal_id'] ?? 0);
            
            if ($userId > 0 && $medalId > 0) {
                try {
                    db()->execute(
                        "DELETE FROM user_medals WHERE user_id = ? AND medal_id = ?",
                        [$userId, $medalId]
                    );
                    setFlashMessage('success', '勋章剥夺成功');
                } catch (Exception $e) {
                    setFlashMessage('error', '操作失败: ' . $e->getMessage());
                }
            }
            redirect(SITE_URL . '/admin/medals.php?action=user_medals&user_id=' . $userId);
            break;
    }
}

// 处理删除
if ($action === 'delete' && isset($_GET['id'])) {
    $medalId = intval($_GET['id']);
    try {
        db()->execute("DELETE FROM medals WHERE id = ?", [$medalId]);
        setFlashMessage('success', '勋章删除成功');
    } catch (Exception $e) {
        setFlashMessage('error', '删除失败: ' . $e->getMessage());
    }
    redirect(SITE_URL . '/admin/medals.php');
}

$pageTitle = '勋章管理';
include __DIR__ . '/header.php';
?>

<div class="admin-content">
    <?php if ($action === 'list'): ?>
        <!-- 勋章列表 -->
        <div class="content-header">
            <h2><i class="fas fa-medal"></i> 勋章管理</h2>
            <a href="?action=add" class="btn btn-primary"><i class="fas fa-plus"></i> 添加勋章</a>
        </div>
        
        <?php $flash = getFlashMessage(); if ($flash): ?>
            <div class="alert alert-<?php echo $flash['type']; ?>"><?php echo e($flash['message']); ?></div>
        <?php endif; ?>
        
        <!-- 统计卡片 - 白色块状风格 -->
        <?php
        $medals = getAllMedals();
        $totalMedals = count($medals);
        $totalUsers = db()->queryOne("SELECT COUNT(*) as count FROM users")['count'] ?? 0;
        $totalAwarded = db()->queryOne("SELECT COUNT(*) as count FROM user_medals")['count'] ?? 0;
        $avgMedals = $totalUsers > 0 ? round($totalAwarded / $totalUsers, 1) : 0;
        ?>
        <div class="stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px;">
            <!-- 勋章总数 - 可点击 -->
            <a href="?action=list" style="text-decoration: none;">
                <div class="stat-card" style="background: #2563eb; color: white; padding: 24px; border-radius: 12px; text-align: center; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.25); border: 2px solid #2563eb; transition: all 0.3s; cursor: pointer;" onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 8px 20px rgba(37, 99, 235, 0.35)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 12px rgba(37, 99, 235, 0.25)'">
                    <div style="font-size: 40px; font-weight: bold; margin-bottom: 8px;"><?php echo $totalMedals; ?></div>
                    <div style="font-size: 14px; font-weight: 500;"><i class="fas fa-medal" style="margin-right: 6px;"></i>勋章总数</div>
                </div>
            </a>
            <!-- 用户总数 - 可点击 -->
            <a href="?action=users" style="text-decoration: none;">
                <div class="stat-card" style="background: #3b82f6; color: white; padding: 24px; border-radius: 12px; text-align: center; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.25); border: 2px solid #3b82f6; transition: all 0.3s; cursor: pointer;" onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 8px 20px rgba(59, 130, 246, 0.35)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 12px rgba(59, 130, 246, 0.25)'">
                    <div style="font-size: 40px; font-weight: bold; margin-bottom: 8px;"><?php echo $totalUsers; ?></div>
                    <div style="font-size: 14px; font-weight: 500;"><i class="fas fa-users" style="margin-right: 6px;"></i>用户总数</div>
                </div>
            </a>
            <!-- 已颁发勋章 - 可点击 -->
            <a href="?action=awarded" style="text-decoration: none;">
                <div class="stat-card" style="background: #60a5fa; color: white; padding: 24px; border-radius: 12px; text-align: center; box-shadow: 0 4px 12px rgba(96, 165, 250, 0.25); border: 2px solid #60a5fa; transition: all 0.3s; cursor: pointer;" onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 8px 20px rgba(96, 165, 250, 0.35)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 12px rgba(96, 165, 250, 0.25)'">
                    <div style="font-size: 40px; font-weight: bold; margin-bottom: 8px;"><?php echo $totalAwarded; ?></div>
                    <div style="font-size: 14px; font-weight: 500;"><i class="fas fa-award" style="margin-right: 6px;"></i>已颁发勋章</div>
                </div>
            </a>
            <!-- 人均勋章数 - 静态展示 -->
            <div class="stat-card" style="background: #94a3b8; color: white; padding: 24px; border-radius: 12px; text-align: center; box-shadow: 0 4px 12px rgba(148, 163, 184, 0.25); border: 2px solid #94a3b8;">
                <div style="font-size: 40px; font-weight: bold; margin-bottom: 8px;"><?php echo $avgMedals; ?></div>
                <div style="font-size: 14px; font-weight: 500;"><i class="fas fa-chart-line" style="margin-right: 6px;"></i>人均勋章数</div>
            </div>
        </div>
        
        <!-- 勋章卡片列表 -->
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 24px;">
            <?php foreach ($medals as $medal): 
                $userCount = getMedalUserCount($medal['id']);
                $percentage = $totalUsers > 0 ? round(($userCount / $totalUsers) * 100, 1) : 0;
                $typeNames = [
                    'like' => '点赞',
                    'favorite' => '收藏',
                    'comment' => '评论',
                    'bookmark' => '收藏'
                ];
                $conditionNames = [
                    'post_liked' => '帖子被点赞',
                    'post_favorited' => '帖子被收藏',
                    'reply_count' => '回复数量'
                ];
                $typeColors = [
                    'like' => '#e74c3c',
                    'favorite' => '#f39c12',
                    'comment' => '#3498db',
                    'bookmark' => '#9b59b6'
                ];
            ?>
            <div class="medal-card" style="background: white; border-radius: 16px; padding: 24px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); border: 1px solid <?php echo $medal['status'] ? '#e8e8e8' : '#ff6b6b'; ?>; transition: all 0.3s ease;">
                <!-- 头部：图标和名称 -->
                <div style="display: flex; gap: 16px; margin-bottom: 20px;">
                    <div style="width: 64px; height: 64px; background: <?php echo $typeColors[$medal['type']] ?? '#666'; ?>15; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                        <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="" style="width: 48px; height: 48px; object-fit: contain;">
                    </div>
                    <div style="flex: 1; min-width: 0;">
                        <div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 8px;">
                            <h3 style="margin: 0; font-size: 18px; font-weight: 600; color: #1a1a1a; line-height: 1.4;"><?php echo e($medal['name']); ?></h3>
                            <?php if (!$medal['status']): ?>
                                <span class="badge" style="background: #ff6b6b; color: white; font-size: 11px; padding: 4px 8px; border-radius: 4px; flex-shrink: 0;">已禁用</span>
                            <?php endif; ?>
                        </div>
                        <p style="margin: 6px 0 0 0; color: #666; font-size: 13px; line-height: 1.5;"><?php echo e($medal['description']); ?></p>
                    </div>
                </div>
                
                <!-- 信息区域 -->
                <div style="background: #f8f9fa; border-radius: 12px; padding: 16px; margin-bottom: 20px;">
                    <div style="display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 12px;">
                        <span style="display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: #555; background: white; padding: 6px 12px; border-radius: 20px; border: 1px solid #e0e0e0;">
                            <i class="fas fa-tasks" style="color: <?php echo $typeColors[$medal['type']] ?? '#666' ?>"></i>
                            <?php echo $conditionNames[$medal['condition_type']] ?? $medal['condition_type']; ?> <?php echo $medal['condition_value']; ?>次
                        </span>
                        <span style="display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: #555; background: white; padding: 6px 12px; border-radius: 20px; border: 1px solid #e0e0e0;">
                            <i class="fas fa-tag" style="color: <?php echo $typeColors[$medal['type']] ?? '#666' ?>"></i>
                            <?php echo $typeNames[$medal['type']] ?? $medal['type']; ?>
                        </span>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: #666;">
                        <span><i class="fas fa-users" style="color: #2563eb; margin-right: 6px;"></i> <?php echo $userCount; ?> 人获得</span>
                        <span style="color: #999;">排序: <?php echo $medal['sort_order']; ?></span>
                    </div>
                </div>
                
                <!-- 获得率进度条 - 蓝白色 -->
                <div style="margin-bottom: 20px;">
                    <div style="display: flex; justify-content: space-between; font-size: 12px; color: #666; margin-bottom: 8px;">
                        <span style="font-weight: 500;">获得率</span>
                        <span style="font-weight: 600; color: #2563eb;"><?php echo $percentage; ?>%</span>
                    </div>
                    <div style="width: 100%; height: 8px; background: #e8e8e8; border-radius: 4px; overflow: hidden;">
                        <div style="width: <?php echo $percentage; ?>%; height: 100%; background: #2563eb; border-radius: 4px; transition: width 0.5s ease;"></div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div style="display: flex; gap: 12px;">
                    <a href="?action=edit&id=<?php echo $medal['id']; ?>" class="btn btn-sm" style="flex: 1; background: #eff6ff; color: #2563eb; border: 1px solid #bfdbfe; padding: 10px; border-radius: 8px; text-align: center; font-weight: 500; transition: all 0.2s; text-decoration: none;" onmouseover="this.style.background='#dbeafe'" onmouseout="this.style.background='#eff6ff'">
                        <i class="fas fa-edit"></i> 编辑
                    </a>
                    <a href="?action=delete&id=<?php echo $medal['id']; ?>" class="btn btn-sm" style="flex: 1; background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; padding: 10px; border-radius: 8px; text-align: center; font-weight: 500; transition: all 0.2s; text-decoration: none;" onmouseover="this.style.background='#fee2e2'" onmouseout="this.style.background='#fef2f2'" onclick="return confirm('确定要删除此勋章吗？')">
                        <i class="fas fa-trash"></i> 删除
                    </a>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
    <?php elseif ($action === 'add' || $action === 'edit'): ?>
        <!-- 添加/编辑勋章 -->
        <?php
        $medal = null;
        if ($action === 'edit' && isset($_GET['id'])) {
            $medal = db()->queryOne("SELECT * FROM medals WHERE id = ?", [intval($_GET['id'])]);
        }
        ?>
        <div class="content-header">
            <h2><i class="fas fa-medal"></i> <?php echo $medal ? '编辑勋章' : '添加勋章'; ?></h2>
        </div>
        
        <?php $flash = getFlashMessage(); if ($flash): ?>
            <div class="alert alert-<?php echo $flash['type']; ?>"><?php echo e($flash['message']); ?></div>
        <?php endif; ?>
        
        <div class="card" style="max-width: 600px; border-radius: 16px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); background: white;">
            <div class="card-body" style="padding: 32px;">
                <form method="POST" action="?action=<?php echo $action; ?>">
                    <?php if ($medal): ?>
                        <input type="hidden" name="medal_id" value="<?php echo $medal['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="form-group" style="margin-bottom: 24px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #333;">勋章名称</label>
                        <input type="text" name="name" class="form-control" value="<?php echo e($medal['name'] ?? ''); ?>" required style="width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px; transition: border-color 0.2s;" onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#ddd'">
                    </div>
                    
                    <div class="form-group" style="margin-bottom: 24px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #333;">勋章描述</label>
                        <input type="text" name="description" class="form-control" value="<?php echo e($medal['description'] ?? ''); ?>" style="width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px; transition: border-color 0.2s;" onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#ddd'">
                    </div>
                    
                    <div class="form-group" style="margin-bottom: 24px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #333;">勋章图标路径</label>
                        <input type="text" name="icon" class="form-control" value="<?php echo e($medal['icon'] ?? 'assets/images/Medal/'); ?>" required style="width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px; transition: border-color 0.2s;" onfocus="this.style.borderColor='#2563eb'" onblur="this.style.borderColor='#ddd'">
                        <small style="color: #888; font-size: 12px; margin-top: 6px; display: block;">例如: assets/images/Medal/Like.png</small>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div class="form-group" style="margin-bottom: 24px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #333;">勋章类型</label>
                            <select name="type" class="form-control" style="width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px; background: white;">
                                <option value="like" <?php echo ($medal['type'] ?? '') === 'like' ? 'selected' : ''; ?>>点赞</option>
                                <option value="favorite" <?php echo ($medal['type'] ?? '') === 'favorite' ? 'selected' : ''; ?>>收藏</option>
                                <option value="comment" <?php echo ($medal['type'] ?? '') === 'comment' ? 'selected' : ''; ?>>评论</option>
                            </select>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 24px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #333;">条件类型</label>
                            <select name="condition_type" class="form-control" style="width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px; background: white;">
                                <option value="post_liked" <?php echo ($medal['condition_type'] ?? '') === 'post_liked' ? 'selected' : ''; ?>>帖子被点赞数</option>
                                <option value="post_favorited" <?php echo ($medal['condition_type'] ?? '') === 'post_favorited' ? 'selected' : ''; ?>>帖子被收藏数</option>
                                <option value="reply_count" <?php echo ($medal['condition_type'] ?? '') === 'reply_count' ? 'selected' : ''; ?>>回复数量</option>
                            </select>
                        </div>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                        <div class="form-group" style="margin-bottom: 24px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #333;">条件数值</label>
                            <input type="number" name="condition_value" class="form-control" value="<?php echo $medal['condition_value'] ?? 10; ?>" required style="width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px;">
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 24px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #333;">排序</label>
                            <input type="number" name="sort_order" class="form-control" value="<?php echo $medal['sort_order'] ?? 0; ?>" style="width: 100%; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px;">
                        </div>
                    </div>
                    
                    <div class="form-group" style="margin-bottom: 24px;">
                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 500; color: #333;">
                            <input type="checkbox" name="status" <?php echo ($medal['status'] ?? 1) ? 'checked' : ''; ?> style="width: 18px; height: 18px; accent-color: #2563eb;">
                            启用此勋章
                        </label>
                    </div>
                    
                    <div class="form-actions" style="display: flex; gap: 12px; padding-top: 16px; border-top: 1px solid #eee;">
                        <button type="submit" class="btn" style="flex: 1; background: #2563eb; color: white; padding: 12px 24px; border-radius: 8px; font-weight: 500; border: none; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='#1d4ed8'" onmouseout="this.style.background='#2563eb'">保存</button>
                        <a href="?action=list" class="btn" style="flex: 1; background: #f8f9fa; color: #666; padding: 12px 24px; border-radius: 8px; font-weight: 500; text-align: center; border: 1px solid #ddd; text-decoration: none;">返回</a>
                    </div>
                </form>
            </div>
        </div>
        
    <?php elseif ($action === 'user_medals'): ?>
        <!-- 用户勋章管理 -->
        <?php
        $userId = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
        $user = null;
        $userMedals = [];
        $allMedals = getAllMedals();
        
        if ($userId > 0) {
            $user = db()->queryOne("SELECT id, username, avatar, role FROM users WHERE id = ?", [$userId]);
            if ($user) {
                $userMedals = getUserMedals($userId);
            }
        }
        ?>
        <div class="content-header">
            <h2><i class="fas fa-user-medal"></i> 用户勋章管理</h2>
            <a href="?action=users" class="btn btn-outline"><i class="fas fa-arrow-left"></i> 返回用户列表</a>
        </div>
        
        <?php $flash = getFlashMessage(); if ($flash): ?>
            <div class="alert alert-<?php echo $flash['type']; ?>"><?php echo e($flash['message']); ?></div>
        <?php endif; ?>
        
        <?php if ($user): ?>
        <!-- 用户信息卡片 - 蓝白色风格 -->
        <div style="margin-bottom: 32px; background: #ffffff; color: #1e293b; border-radius: 16px; padding: 28px; border: 1px solid #e2e8f0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
            <div style="display: flex; align-items: center; gap: 24px;">
                <div style="width: 88px; height: 88px; border-radius: 50%; border: 3px solid #bfdbfe; overflow: hidden; background: #eff6ff; display: flex; align-items: center; justify-content: center;">
                    <?php if ($user['avatar']): ?>
                        <img src="<?php echo SITE_URL . '/' . e($user['avatar']); ?>" alt="" style="width: 100%; height: 100%; object-fit: cover;">
                    <?php else: ?>
                        <i class="fas fa-user" style="font-size: 40px; color: #93c5fd;"></i>
                    <?php endif; ?>
                </div>
                <div style="flex: 1;">
                    <h3 style="margin: 0 0 8px 0; font-size: 28px; font-weight: 600; color: #1e293b;"><?php echo e($user['username']); ?> 
                        <?php if ($user['role'] >= 1): ?>
                            <span style="background: #dbeafe; color: #1e40af; padding: 4px 12px; border-radius: 20px; font-size: 13px; font-weight: 500;">管理员</span>
                        <?php endif; ?>
                    </h3>
                    <p style="margin: 0; color: #64748b; font-size: 16px;">已获得 <?php echo count($userMedals); ?> / <?php echo count($allMedals); ?> 个勋章</p>
                </div>
            </div>
        </div>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 32px;">
            <!-- 已获得的勋章 -->
            <div>
                <h3 style="margin-bottom: 20px; color: #2563eb; font-size: 18px; font-weight: 600;">
                    <i class="fas fa-check-circle"></i> 已获得的勋章 
                    <span style="background: #dbeafe; color: #1e40af; padding: 4px 12px; border-radius: 20px; font-size: 14px; margin-left: 8px;"><?php echo count($userMedals); ?></span>
                </h3>
                <?php if (empty($userMedals)): ?>
                    <div style="text-align: center; color: #888; padding: 60px 40px; background: #f8f9fa; border-radius: 16px; border: 2px dashed #ddd;">
                        <i class="fas fa-medal" style="font-size: 56px; margin-bottom: 16px; color: #ccc;"></i>
                        <p style="font-size: 15px;">该用户还没有获得任何勋章</p>
                    </div>
                <?php else: ?>
                    <div style="display: flex; flex-direction: column; gap: 16px;">
                        <?php foreach ($userMedals as $medal): ?>
                        <div style="display: flex; align-items: center; gap: 16px; padding: 20px; background: #eff6ff; border-radius: 12px; border: 1px solid #bfdbfe; transition: all 0.2s;">
                            <div style="width: 56px; height: 56px; background: white; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                                <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="" style="width: 40px; height: 40px; object-fit: contain;">
                            </div>
                            <div style="flex: 1; min-width: 0;">
                                <div style="font-weight: 600; font-size: 16px; color: #1a1a1a; margin-bottom: 4px;"><?php echo e($medal['name']); ?></div>
                                <div style="font-size: 13px; color: #666; margin-bottom: 6px;"><?php echo e($medal['description']); ?></div>
                                <div style="font-size: 12px; color: #888;">
                                    <i class="fas fa-clock" style="margin-right: 4px;"></i><?php echo date('Y-m-d H:i', strtotime($medal['awarded_at'])); ?> 获得
                                    <?php if ($medal['is_wearing']): ?>
                                        <span style="background: #2563eb; color: white; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 8px;">佩戴中</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <form method="POST" action="?action=revoke" style="margin: 0;">
                                <input type="hidden" name="user_id" value="<?php echo $userId; ?>">
                                <input type="hidden" name="medal_id" value="<?php echo $medal['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('确定要剥夺此勋章吗？')" style="padding: 8px 16px; border-radius: 8px; font-size: 13px; background: #dc2626; color: white; border: none; cursor: pointer;">
                                    <i class="fas fa-times"></i> 剥夺
                                </button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- 可授予的勋章 -->
            <div>
                <h3 style="margin-bottom: 20px; color: #2563eb; font-size: 18px; font-weight: 600;">
                    <i class="fas fa-plus-circle"></i> 可授予的勋章
                    <span style="background: #dbeafe; color: #1e40af; padding: 4px 12px; border-radius: 20px; font-size: 14px; margin-left: 8px;"><?php echo count($allMedals) - count($userMedals); ?></span>
                </h3>
                <?php
                $userMedalIds = array_column($userMedals, 'id');
                $availableMedals = array_filter($allMedals, function($m) use ($userMedalIds) {
                    return !in_array($m['id'], $userMedalIds);
                });
                ?>
                <?php if (empty($availableMedals)): ?>
                    <div style="text-align: center; color: #888; padding: 60px 40px; background: #f8f9fa; border-radius: 16px; border: 2px dashed #ddd;">
                        <i class="fas fa-trophy" style="font-size: 56px; margin-bottom: 16px; color: #ccc;"></i>
                        <p style="font-size: 15px;">该用户已获得所有勋章</p>
                    </div>
                <?php else: ?>
                    <div style="display: flex; flex-direction: column; gap: 16px;">
                        <?php foreach ($availableMedals as $medal): ?>
                        <div style="display: flex; align-items: center; gap: 16px; padding: 20px; background: #f8f9fa; border-radius: 12px; border: 1px solid #e0e0e0; transition: all 0.2s;">
                            <div style="width: 56px; height: 56px; background: white; border-radius: 12px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                                <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="" style="width: 40px; height: 40px; object-fit: contain; filter: grayscale(50%); opacity: 0.7;">
                            </div>
                            <div style="flex: 1; min-width: 0;">
                                <div style="font-weight: 600; font-size: 16px; color: #1a1a1a; margin-bottom: 4px;"><?php echo e($medal['name']); ?></div>
                                <div style="font-size: 13px; color: #666;"><?php echo e($medal['description']); ?></div>
                            </div>
                            <form method="POST" action="?action=award" style="margin: 0;">
                                <input type="hidden" name="user_id" value="<?php echo $userId; ?>">
                                <input type="hidden" name="medal_id" value="<?php echo $medal['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-success" style="padding: 8px 16px; border-radius: 8px; font-size: 13px; background: #2563eb; color: white; border: none; cursor: pointer;">
                                    <i class="fas fa-plus"></i> 授予
                                </button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php else: ?>
            <div class="alert alert-error">用户不存在</div>
        <?php endif; ?>
        
    <?php elseif ($action === 'users'): ?>
        <!-- 用户列表 -->
        <div class="content-header">
            <h2><i class="fas fa-users"></i> 用户勋章管理</h2>
        </div>
        
        <?php 
        $search = isset($_GET['search']) ? trim($_GET['search']) : '';
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        if ($search) {
            $users = db()->query(
                "SELECT id, username, avatar, role, post_count, reply_count FROM users 
                 WHERE username LIKE ? OR email LIKE ? 
                 ORDER BY id DESC LIMIT ? OFFSET ?",
                ["%$search%", "%$search%", $perPage, $offset]
            );
            $totalResult = db()->queryOne(
                "SELECT COUNT(*) as total FROM users WHERE username LIKE ? OR email LIKE ?",
                ["%$search%", "%$search%"]
            );
        } else {
            $users = db()->query(
                "SELECT id, username, avatar, role, post_count, reply_count FROM users 
                 ORDER BY id DESC LIMIT ? OFFSET ?",
                [$perPage, $offset]
            );
            $totalResult = db()->queryOne("SELECT COUNT(*) as total FROM users");
        }
        $total = $totalResult['total'] ?? 0;
        ?>
        
        <div class="card" style="margin-bottom: 24px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); background: white;">
            <div class="card-body" style="padding: 20px;">
                <form method="GET" action="" style="display: flex; gap: 12px;">
                    <input type="hidden" name="action" value="users">
                    <input type="text" name="search" class="form-control" placeholder="搜索用户名或邮箱" value="<?php echo e($search); ?>" style="flex: 1; padding: 12px 16px; border: 1px solid #ddd; border-radius: 8px; font-size: 15px;">
                    <button type="submit" class="btn" style="background: #2563eb; color: white; padding: 12px 24px; border-radius: 8px; border: none; cursor: pointer; font-weight: 500;"><i class="fas fa-search"></i> 搜索</button>
                    <?php if ($search): ?>
                        <a href="?action=users" class="btn" style="background: #f8f9fa; color: #666; padding: 12px 24px; border-radius: 8px; border: 1px solid #ddd; text-decoration: none;">清除</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <div class="table-responsive" style="background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden;">
            <table class="table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">ID</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">用户</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">角色</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">发帖</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">回复</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">勋章</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): 
                        $medalCount = db()->queryOne("SELECT COUNT(*) as count FROM user_medals WHERE user_id = ?", [$user['id']]);
                        $count = $medalCount['count'] ?? 0;
                    ?>
                    <tr style="border-bottom: 1px solid #f0f0f0;">
                        <td style="padding: 16px; color: #666;"><?php echo $user['id']; ?></td>
                        <td style="padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div style="width: 40px; height: 40px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                    <?php if ($user['avatar']): ?>
                                        <img src="<?php echo SITE_URL . '/' . e($user['avatar']); ?>" alt="" style="width: 100%; height: 100%; object-fit: cover;">
                                    <?php else: ?>
                                        <i class="fas fa-user" style="color: #999;"></i>
                                    <?php endif; ?>
                                </div>
                                <span style="font-weight: 500; color: #333;"><?php echo e($user['username']); ?></span>
                            </div>
                        </td>
                        <td style="padding: 16px;"><?php echo $user['role'] >= 1 ? '<span style="background: #2563eb; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px;">管理员</span>' : '<span style="background: #e0e0e0; color: #666; padding: 4px 12px; border-radius: 20px; font-size: 12px;">用户</span>'; ?></td>
                        <td style="padding: 16px; text-align: center; color: #666;"><?php echo $user['post_count']; ?></td>
                        <td style="padding: 16px; text-align: center; color: #666;"><?php echo $user['reply_count']; ?></td>
                        <td style="padding: 16px; text-align: center;">
                            <span style="font-weight: 600; color: <?php echo $count > 0 ? '#2563eb' : '#999'; ?>; background: <?php echo $count > 0 ? '#dbeafe' : '#f0f0f0'; ?>; padding: 6px 14px; border-radius: 20px; font-size: 13px;">
                                <?php echo $count; ?> 个
                            </span>
                        </td>
                        <td style="padding: 16px; text-align: center;">
                            <a href="?action=user_medals&user_id=<?php echo $user['id']; ?>" class="btn btn-sm" style="background: #eff6ff; color: #2563eb; padding: 8px 16px; border-radius: 8px; font-size: 13px; text-decoration: none; border: 1px solid #bfdbfe;">
                                <i class="fas fa-medal"></i> 管理勋章
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total > $perPage): ?>
            <div style="margin-top: 24px;">
                <?php echo pagination($total, $page, $perPage, "?action=users&search=" . urlencode($search) . "&"); ?>
            </div>
        <?php endif; ?>
        
    <?php elseif ($action === 'awarded'): ?>
        <!-- 已颁发勋章列表 -->
        <div class="content-header">
            <h2><i class="fas fa-award"></i> 已颁发勋章</h2>
            <a href="?action=list" class="btn btn-outline"><i class="fas fa-arrow-left"></i> 返回勋章列表</a>
        </div>
        
        <?php 
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;
        
        // 获取所有已颁发的勋章记录
        $awardedMedals = db()->query(
            "SELECT um.*, u.username, u.avatar, m.name as medal_name, m.icon as medal_icon, m.description 
             FROM user_medals um 
             JOIN users u ON um.user_id = u.id 
             JOIN medals m ON um.medal_id = m.id 
             ORDER BY um.awarded_at DESC LIMIT ? OFFSET ?",
            [$perPage, $offset]
        );
        
        $totalResult = db()->queryOne("SELECT COUNT(*) as total FROM user_medals");
        $total = $totalResult['total'] ?? 0;
        ?>
        
        <div class="table-responsive" style="background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); overflow: hidden;">
            <table class="table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">勋章</th>
                        <th style="padding: 16px; text-align: left; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">获得者</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">佩戴状态</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">颁发时间</th>
                        <th style="padding: 16px; text-align: center; font-weight: 600; color: #555; border-bottom: 1px solid #e0e0e0;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($awardedMedals as $record): ?>
                    <tr style="border-bottom: 1px solid #f0f0f0;">
                        <td style="padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div style="width: 48px; height: 48px; background: #f8f9fa; border-radius: 8px; display: flex; align-items: center; justify-content: center;">
                                    <img src="<?php echo SITE_URL . '/' . $record['medal_icon']; ?>" alt="" style="width: 36px; height: 36px; object-fit: contain;">
                                </div>
                                <div>
                                    <div style="font-weight: 600; color: #333;"><?php echo e($record['medal_name']); ?></div>
                                    <div style="font-size: 12px; color: #888;"><?php echo e($record['description']); ?></div>
                                </div>
                            </div>
                        </td>
                        <td style="padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div style="width: 36px; height: 36px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center; overflow: hidden;">
                                    <?php if ($record['avatar']): ?>
                                        <img src="<?php echo SITE_URL . '/' . e($record['avatar']); ?>" alt="" style="width: 100%; height: 100%; object-fit: cover;">
                                    <?php else: ?>
                                        <i class="fas fa-user" style="color: #999; font-size: 14px;"></i>
                                    <?php endif; ?>
                                </div>
                                <span style="font-weight: 500; color: #333;"><?php echo e($record['username']); ?></span>
                            </div>
                        </td>
                        <td style="padding: 16px; text-align: center;">
                            <?php if ($record['is_wearing']): ?>
                                <span style="background: #2563eb; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px;">佩戴中</span>
                            <?php else: ?>
                                <span style="background: #e0e0e0; color: #666; padding: 4px 12px; border-radius: 20px; font-size: 12px;">未佩戴</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding: 16px; text-align: center; color: #666; font-size: 14px;"><?php echo date('Y-m-d H:i', strtotime($record['awarded_at'])); ?></td>
                        <td style="padding: 16px; text-align: center;">
                            <a href="?action=user_medals&user_id=<?php echo $record['user_id']; ?>" class="btn btn-sm" style="background: #eff6ff; color: #2563eb; padding: 6px 12px; border-radius: 6px; font-size: 12px; text-decoration: none; border: 1px solid #bfdbfe;">
                                管理
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total > $perPage): ?>
            <div style="margin-top: 24px;">
                <?php echo pagination($total, $page, $perPage, "?action=awarded&"); ?>
            </div>
        <?php endif; ?>
        
    <?php endif; ?>
</div>

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