<?php
/**
 * 用户个人中心
 */
require_once __DIR__ . '/includes/functions.php';

$userId = isset($_GET['id']) ? intval($_GET['id']) : 0;
$tab = isset($_GET['tab']) ? $_GET['tab'] : 'posts';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// 获取用户信息（包括被禁用的用户）
$user = db()->queryOne(
    "SELECT * FROM users WHERE id = ?",
    [$userId]
);

if (!$user) {
    setFlashMessage('error', '用户不存在');
    redirect(SITE_URL . '/index.php');
}

// 检查用户是否被禁用
if ($user['status'] == 0) {
    $pageTitle = '用户已被封禁';
    include __DIR__ . '/templates/header.php';
    ?>
    <div class="card">
        <div class="card-body" style="text-align: center; padding: 60px 40px;">
            <div style="width: 100px; height: 100px; margin: 0 auto 24px; background: #fef2f2; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-ban" style="font-size: 48px; color: #dc2626;"></i>
            </div>
            <h2 style="color: #dc2626; margin-bottom: 16px;">该用户已被封禁</h2>
            <p style="color: #666; margin-bottom: 24px;">此用户因违反社区规定已被管理员封禁</p>
            <a href="index.php" class="btn btn-primary">返回首页</a>
        </div>
    </div>
    <?php
    include __DIR__ . '/templates/footer.php';
    exit;
}

$perPage = 20;
$offset = ($page - 1) * $perPage;

// 根据标签获取内容
if ($tab === 'posts') {
    // 获取用户的帖子（置顶帖子优先显示）
    $items = db()->query(
        "SELECT p.*, c.name as category_name 
         FROM posts p 
         LEFT JOIN categories c ON p.category_id = c.id 
         WHERE p.user_id = ? AND p.status = 1 
         ORDER BY p.is_top DESC, p.created_at DESC 
         LIMIT ? OFFSET ?",
        [$userId, $perPage, $offset]
    );

    $totalResult = db()->queryOne(
        "SELECT COUNT(*) as total FROM posts WHERE user_id = ? AND status = 1",
        [$userId]
    );
} else {
    // 获取用户的回复
    $items = db()->query(
        "SELECT r.*, p.title as post_title, p.id as post_id 
         FROM replies r 
         LEFT JOIN posts p ON r.post_id = p.id 
         WHERE r.user_id = ? AND r.status = 1 AND p.status = 1 
         ORDER BY r.created_at DESC 
         LIMIT ? OFFSET ?",
        [$userId, $perPage, $offset]
    );

    $totalResult = db()->queryOne(
        "SELECT COUNT(*) as total FROM replies r 
         LEFT JOIN posts p ON r.post_id = p.id 
         WHERE r.user_id = ? AND r.status = 1 AND p.status = 1",
        [$userId]
    );
}

$total = $totalResult['total'];

$pageTitle = $user['username'] . ' 的个人主页';
include __DIR__ . '/templates/header.php';

// 获取用户佩戴的勋章
$wearingMedals = getUserWearingMedals($userId);
?>

<div class="card">
    <div class="card-body" style="display: flex; align-items: center; gap: 30px; padding: 30px;">
        <div class="avatar" style="width: 100px; height: 100px; font-size: 40px; cursor: <?php echo $user['avatar'] ? 'pointer' : 'default'; ?>;" onclick="<?php echo $user['avatar'] ? 'openAvatarModal()' : ''; ?>">
            <?php if ($user['avatar']): ?>
                <img src="<?php echo e($user['avatar']); ?>" alt="<?php echo e($user['username']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
            <?php else: ?>
                <i class="fas fa-user"></i>
            <?php endif; ?>
        </div>
        <div style="flex: 1;">
            <h2 style="margin-bottom: 10px;">
                <?php echo e($user['username']); ?>
                <?php if ($user['role'] == 1): ?>
                    <span class="badge admin">管理员</span>
                <?php endif; ?>
            </h2>
            <?php if ($user['signature']): ?>
                <p style="color: #666; margin-bottom: 15px;"><?php echo e($user['signature']); ?></p>
            <?php endif; ?>
            
            <!-- 佩戴的勋章 -->
            <?php if (!empty($wearingMedals)): ?>
            <div style="margin-bottom: 15px;">
                <?php foreach ($wearingMedals as $medal): ?>
                    <span style="display: inline-flex; align-items: center; gap: 5px; background: #f0f8ff; padding: 5px 12px; border-radius: 20px; margin-right: 10px; margin-bottom: 5px; border: 1px solid #3498db;">
                        <img src="<?php echo SITE_URL . '/' . $medal['icon']; ?>" alt="<?php echo e($medal['name']); ?>" style="width: 20px; height: 20px; object-fit: contain;">
                        <span style="font-size: 13px; color: #3498db; font-weight: 500;"><?php echo e($medal['name']); ?></span>
                    </span>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            
            <div style="display: flex; gap: 30px; color: #666;">
                <span><i class="fas fa-file-alt"></i> 发帖 <?php echo $user['post_count']; ?></span>
                <span><i class="fas fa-comment"></i> 回复 <?php echo $user['reply_count']; ?></span>
                <span><i class="fas fa-clock"></i> 注册 <?php echo formatTime($user['created_at']); ?></span>
            </div>
        </div>
    </div>
</div>

<div class="card" style="margin-top: 20px;">
    <div class="card-header">
        <div style="display: flex; gap: 20px;">
            <a href="?id=<?php echo $userId; ?>&tab=posts" 
               style="padding: 5px 15px; border-radius: 4px; <?php echo $tab === 'posts' ? 'background: var(--primary-color); color: #fff;' : ''; ?>">
                <i class="fas fa-file-alt"></i> 帖子 (<?php echo $user['post_count']; ?>)
            </a>
            <a href="?id=<?php echo $userId; ?>&tab=replies" 
               style="padding: 5px 15px; border-radius: 4px; <?php echo $tab === 'replies' ? 'background: var(--primary-color); color: #fff;' : ''; ?>">
                <i class="fas fa-comment"></i> 回复 (<?php echo $user['reply_count']; ?>)
            </a>
        </div>
    </div>
    <div class="card-body">
        <?php if (empty($items)): ?>
            <div style="text-align: center; padding: 40px; color: #666;">
                <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 15px;"></i>
                <p>暂无<?php echo $tab === 'posts' ? '帖子' : '回复'; ?></p>
            </div>
        <?php else: ?>
            <?php if ($tab === 'posts'): ?>
                <div class="post-list">
                    <?php foreach ($items as $post): ?>
                        <div class="post-item">
                            <div class="post-content" style="flex: 1;">
                                <div class="post-title">
                                    <?php if ($post['is_top']): ?>
                                        <span class="tag tag-top">置顶</span>
                                    <?php endif; ?>
                                    <?php if ($post['is_essence']): ?>
                                        <span class="tag tag-essence">精华</span>
                                    <?php endif; ?>
                                    <a href="post.php?id=<?php echo $post['id']; ?>">
                                        <?php echo e($post['title']); ?>
                                    </a>
                                </div>
                                <div class="post-meta">
                                    <a href="category.php?id=<?php echo $post['category_id']; ?>"><?php echo e($post['category_name']); ?></a>
                                    <span>•</span>
                                    <span><?php echo formatTime($post['created_at']); ?></span>
                                </div>
                            </div>
                            <div class="post-stats">
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo $post['view_count']; ?></div>
                                    <div class="stat-label">浏览</div>
                                </div>
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo $post['reply_count']; ?></div>
                                    <div class="stat-label">回复</div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="reply-list">
                    <?php foreach ($items as $reply): ?>
                        <div class="reply-item">
                            <div class="reply-content" style="flex: 1;">
                                <div class="reply-header">
                                    <span>回复了帖子 <a href="post.php?id=<?php echo $reply['post_id']; ?>"><?php echo e($reply['post_title']); ?></a></span>
                                    <span class="reply-time"><?php echo formatTime($reply['created_at']); ?></span>
                                </div>
                                <div class="reply-body">
                                    <?php echo nl2br(e(truncate($reply['content'], 200))); ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<?php if ($total > $perPage): ?>
    <?php echo pagination($total, $page, $perPage, 'user.php?id=' . $userId . '&tab=' . $tab); ?>
<?php endif; ?>

<?php if ($user['avatar']): ?>
<!-- 头像放大查看模态框 -->
<div id="avatar-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.85); z-index: 9999; justify-content: center; align-items: center; cursor: grab;" onclick="closeAvatarModal()">
    <div id="avatar-container" style="position: relative; max-width: 90%; max-height: 90%; overflow: hidden;" onclick="event.stopPropagation();">
        <!-- 关闭按钮 -->
        <button onclick="closeAvatarModal()" style="position: absolute; top: -40px; right: 0; background: none; border: none; color: white; font-size: 30px; cursor: pointer; padding: 5px; line-height: 1; z-index: 10;">
            <i class="fas fa-times"></i>
        </button>
        <!-- 放大后的头像 -->
        <img id="avatar-zoom-img" src="<?php echo e($user['avatar']); ?>" alt="<?php echo e($user['username']); ?>" style="max-width: 100%; max-height: 85vh; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); transition: transform 0.1s ease-out; transform-origin: center center;">
        <!-- 用户名 -->
        <div style="text-align: center; margin-top: 15px; color: white; font-size: 18px;">
            <?php echo e($user['username']); ?> 的头像
        </div>
        <!-- 缩放提示 -->
        <div style="position: absolute; bottom: -35px; left: 50%; transform: translateX(-50%); color: rgba(255,255,255,0.7); font-size: 13px; white-space: nowrap;">
            滚轮缩放 • 拖拽移动 • 双击重置
        </div>
    </div>
</div>

<script>
let currentScale = 1;
let isDragging = false;
let startX, startY, translateX = 0, translateY = 0;
const minScale = 0.5;
const maxScale = 5;
const scaleStep = 0.1;

const modal = document.getElementById('avatar-modal');
const container = document.getElementById('avatar-container');
const img = document.getElementById('avatar-zoom-img');

// 打开头像模态框
function openAvatarModal() {
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden';
    resetZoom();
}

// 关闭头像模态框
function closeAvatarModal() {
    modal.style.display = 'none';
    document.body.style.overflow = '';
    resetZoom();
}

// 重置缩放
function resetZoom() {
    currentScale = 1;
    translateX = 0;
    translateY = 0;
    updateTransform();
}

// 更新变换
function updateTransform() {
    img.style.transform = `translate(${translateX}px, ${translateY}px) scale(${currentScale})`;
}

// 滚轮缩放
container.addEventListener('wheel', function(e) {
    e.preventDefault();
    
    const delta = e.deltaY > 0 ? -scaleStep : scaleStep;
    const newScale = Math.max(minScale, Math.min(maxScale, currentScale + delta));
    
    if (newScale !== currentScale) {
        currentScale = newScale;
        updateTransform();
    }
}, { passive: false });

// 拖拽移动
container.addEventListener('mousedown', function(e) {
    if (currentScale > 1) {
        isDragging = true;
        startX = e.clientX - translateX;
        startY = e.clientY - translateY;
        modal.style.cursor = 'grabbing';
    }
});

document.addEventListener('mousemove', function(e) {
    if (isDragging) {
        e.preventDefault();
        translateX = e.clientX - startX;
        translateY = e.clientY - startY;
        updateTransform();
    }
});

document.addEventListener('mouseup', function() {
    isDragging = false;
    modal.style.cursor = 'grab';
});

// 双击重置
container.addEventListener('dblclick', function(e) {
    e.stopPropagation();
    resetZoom();
});

// ESC键关闭模态框
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeAvatarModal();
    }
});
</script>
<?php endif; ?>

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