<?php
ob_start();
$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>
            <img src="https://api.iconify.design/mdi:camera.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            上传头像
        </h2>
        <p class="page-desc">更换您的个人头像</p>
    </div>
    
    <?php if ($success): ?>
        <div class="alert alert-success">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $success; ?>
        </div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error">
            <img src="https://api.iconify.design/mdi:alert-circle.svg?color=%23ef4444" width="20" height="20" style="margin-right: 8px;" alt="">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <div class="avatar-card">
        <!-- 当前头像 -->
        <div class="current-avatar">
            <div class="avatar-preview-wrapper">
                <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="Current Avatar" id="avatarPreview" onerror="this.src='/assets/uploads/default_avatar.png'">
                
            </div>
            <p>当前头像</p>
        </div>
        
        <!-- 上传提示 -->
        <div class="upload-tip">
            <img src="https://api.iconify.design/mdi:information.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
            <span>支持 JPG、PNG、GIF、WEBP 格式，大小不超过 2MB</span>
        </div>
        
        <form method="POST" enctype="multipart/form-data" class="avatar-form">
            <div class="form-group">
                <label>
                    <img src="https://api.iconify.design/mdi:image.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                    选择新头像
                </label>
                <div class="file-input-wrapper">
                    <input type="file" name="avatar" accept="image/*" id="avatarInput" required>
                    <label for="avatarInput" class="file-input-label">
                        <img src="https://api.iconify.design/mdi:cloud-upload.svg?color=%23667eea" width="18" height="18" style="margin-right: 6px;" alt="">
                        选择图片
                    </label>
                    <span class="file-name" id="fileNameDisplay">未选择文件</span>
                </div>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <img src="https://api.iconify.design/mdi:check.svg?color=white" width="18" height="18" style="margin-right: 6px;" alt="">
                    上传头像
                </button>
                <a href="?page=profile" class="btn btn-secondary">
                    <img src="https://api.iconify.design/mdi:arrow-left.svg?color=currentColor" width="18" height="18" style="margin-right: 6px;" alt="">
                    返回
                </a>
            </div>
        </form>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.avatar-container {
    max-width: 480px;
    margin: 0 auto;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 28px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 6px;
}
.page-desc {
    font-size: 14px;
    color: var(--text-secondary);
    margin-left: 36px;
}

/* 提示消息 */
.alert {
    display: flex;
    align-items: center;
    padding: 14px 20px;
    border-radius: var(--radius-md);
    margin-bottom: 24px;
    font-size: 14px;
}
.alert-success {
    background: #d1fae5;
    color: #065f46;
    border: 1px solid #a7f3d0;
}
.alert-error {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #991b1b;
}

/* 头像卡片 */
.avatar-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 36px 32px;
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
    text-align: center;
}

/* 当前头像 */
.current-avatar {
    margin-bottom: 28px;
}
.avatar-preview-wrapper {
    position: relative;
    width: 140px;
    height: 140px;
    margin: 0 auto;
}
.avatar-preview-wrapper img {
    width: 140px;
    height: 140px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid var(--border-color);
    transition: all 0.2s;
}
.avatar-overlay {
    position: absolute;
    bottom: 4px;
    right: 4px;
    width: 36px;
    height: 36px;
    background: var(--primary-color);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.avatar-overlay:hover {
    background: var(--primary-hover);
    transform: scale(1.05);
}
.current-avatar p {
    margin-top: 12px;
    color: var(--text-secondary);
    font-size: 13px;
}

/* 上传提示 */
.upload-tip {
    display: inline-flex;
    align-items: center;
    padding: 8px 16px;
    background: var(--bg-secondary);
    border-radius: 30px;
    margin-bottom: 24px;
    font-size: 13px;
    color: var(--text-secondary);
}

/* 表单 */
.avatar-form .form-group {
    margin-bottom: 28px;
    text-align: left;
}
.avatar-form .form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-weight: 500;
    font-size: 14px;
    color: var(--text-primary);
}

/* 文件上传 */
.file-input-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}
.file-input-wrapper input[type="file"] {
    display: none;
}
.file-input-label {
    display: inline-flex;
    align-items: center;
    padding: 12px 20px;
    background: var(--bg-secondary);
    border: 1.5px dashed var(--border-color);
    border-radius: var(--radius-md);
    cursor: pointer;
    font-size: 14px;
    color: var(--text-primary);
    transition: all 0.2s;
    white-space: nowrap;
}
.file-input-label:hover {
    border-color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.file-name {
    font-size: 13px;
    color: var(--text-muted);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
}

/* 按钮 */
.form-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
    padding-top: 8px;
}
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 12px 28px;
    border-radius: var(--radius-md);
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
    text-decoration: none;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
}

/* 响应式 */
@media (max-width: 768px) {
    .avatar-card {
        padding: 28px 20px;
    }
    .form-actions {
        flex-direction: column;
    }
    .btn {
        width: 100%;
    }
    .file-input-wrapper {
        flex-direction: column;
        align-items: flex-start;
    }
    .file-name {
        width: 100%;
    }
}
</style>

<script>
document.getElementById('avatarInput')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        document.getElementById('fileNameDisplay').textContent = file.name;
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('avatarPreview').src = e.target.result;
        };
        reader.readAsDataURL(file);
    } else {
        document.getElementById('fileNameDisplay').textContent = '未选择文件';
    }
});

// 点击头像覆盖层触发文件选择
document.querySelector('.avatar-overlay')?.addEventListener('click', function() {
    document.getElementById('avatarInput').click();
});
</script>