<?php
$user_id = $_SESSION['user_id'];
$user = currentUser();

$error = '';
$success = '';

// 创建上传目录
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['avatar'])) {
    $file = $_FILES['avatar'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $max_size = 2 * 1024 * 1024; // 2MB
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $error = '上传失败，错误代码：' . $file['error'];
    } elseif (!in_array($file['type'], $allowed_types)) {
        $error = '只支持 JPG、PNG、GIF、WEBP 格式的图片';
    } elseif ($file['size'] > $max_size) {
        $error = '图片大小不能超过 2MB';
    } else {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'avatar_' . $user_id . '_' . time() . '.' . $ext;
        $target = UPLOAD_DIR . $filename;
        
        if (move_uploaded_file($file['tmp_name'], $target)) {
            $avatar_url = UPLOAD_URL . $filename;
            $db->query("UPDATE users SET avatar = '$avatar_url' WHERE id = $user_id");
            $success = '头像上传成功';
            $user = currentUser(); // 刷新
        } else {
            $error = '保存文件失败';
        }
    }
}
?>

<div class="avatar-container">
    <div class="page-header">
        <h2>上传头像</h2>
    </div>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="avatar-card">
        <div class="current-avatar">
            <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="Current Avatar" id="avatarPreview">
            <p>当前头像</p>
        </div>
        
        <form method="POST" enctype="multipart/form-data" class="avatar-form">
            <div class="form-group">
                <label>选择新头像</label>
                <input type="file" name="avatar" accept="image/*" id="avatarInput" required>
                <small>支持 JPG、PNG、GIF、WEBP，大小不超过 2MB</small>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">上传头像</button>
                <a href="?page=profile" class="btn btn-secondary">返回</a>
            </div>
        </form>
    </div>
</div>

<style>
.avatar-card {
    max-width: 400px;
    margin: 0 auto;
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
    text-align: center;
}
.current-avatar {
    margin-bottom: 30px;
}
.current-avatar img {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid var(--border-color);
}
.current-avatar p {
    margin-top: 10px;
    color: var(--text-secondary);
    font-size: 13px;
}
.avatar-form .form-group {
    margin-bottom: 20px;
    text-align: left;
}
.avatar-form .form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
}
.avatar-form .form-group input {
    width: 100%;
    padding: 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
}
.form-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
}
</style>

<script>
document.getElementById('avatarInput')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('avatarPreview').src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
});
</script>