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

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

// 获取用户绑定的快捷登录信息
$user_bindings = [];
$bindings = $db->fetchAll("SELECT * FROM user_oauth_bindings WHERE user_id = $user_id");
foreach ($bindings as $binding) {
    $user_bindings[$binding['oauth_type']] = $binding;
}

// 处理绑定/解绑
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_profile') {
        $email = trim($_POST['email'] ?? '');
        
        if (empty($email)) {
            $error = '邮箱不能为空';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = '邮箱格式不正确';
        } else {
            $check = $db->fetchOne("SELECT id FROM users WHERE email = '$email' AND id != $user_id");
            if ($check) {
                $error = '邮箱已被其他用户使用';
            } else {
                $db->query("UPDATE users SET email = '$email' WHERE id = $user_id");
                $success = '资料更新成功';
                $user = currentUser();
            }
        }
    }
    
    if ($action === 'unbind') {
        $oauth_type = $_POST['oauth_type'] ?? '';
        $db->query("DELETE FROM user_oauth_bindings WHERE user_id = $user_id AND oauth_type = '$oauth_type'");
        $success = '解绑成功';
        // 刷新绑定信息
        $user_bindings = [];
        $bindings = $db->fetchAll("SELECT * FROM user_oauth_bindings WHERE user_id = $user_id");
        foreach ($bindings as $binding) {
            $user_bindings[$binding['oauth_type']] = $binding;
        }
    }
}

// 获取用户当前会员组
$current_group = getUserCurrentGroup($user_id);

// 快捷登录配置
$oauth_configs = [
    'qq' => ['name' => 'QQ', 'icon' => 'qq.svg', 'color' => '#12B7F5', 'bind_url' => '/api/qq_bind.php'],
    'wx' => ['name' => '微信', 'icon' => 'wechat.svg', 'color' => '#07C160', 'bind_url' => '/api/oauth_bind.php?type=wx'],
    'alipay' => ['name' => '支付宝', 'icon' => 'alipay.svg', 'color' => '#1677FF', 'bind_url' => '/api/oauth_bind.php?type=alipay'],
    'gitee' => ['name' => 'Gitee', 'icon' => 'gitee.svg', 'color' => '#C71D23', 'bind_url' => '/api/gitee_bind.php'],
    // 'feishu' => ['name' => '飞书', 'icon' => 'feishu.svg', 'color' => '#00C4A0', 'bind_url' => '/api/feishu_bind.php'],
];
?>

<div class="profile-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="profile-card">
        <div class="profile-avatar-section">
            <img src="<?php echo htmlspecialchars($user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" alt="Avatar" class="profile-avatar">
            <a href="?page=avatar" class="btn-small">更换头像</a>
        </div>
        
        <form method="POST" class="profile-form">
            <input type="hidden" name="action" value="update_profile">
            
            <div class="form-group">
                <label>用户名</label>
                <input type="text" value="<?php echo htmlspecialchars($user['username']); ?>" disabled>
                <small>用户名不可修改</small>
            </div>
            
            <div class="form-group">
                <label>邮箱</label>
                <input type="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" required>
            </div>
            
            <div class="form-group">
                <label>会员等级</label>
                <input type="text" value="<?php echo htmlspecialchars($current_group['name']); ?>" disabled>
                <?php if ($current_group['discount'] < 100): ?>
                    <small>当前享受 <?php echo $current_group['discount']; ?> 折优惠</small>
                <?php endif; ?>
            </div>
            
            <div class="form-group">
                <label>注册时间</label>
                <input type="text" value="<?php echo $user['created_at']; ?>" disabled>
            </div>
            
            <div class="form-group">
                <label>账户余额</label>
                <input type="text" value="¥<?php echo number_format($user['balance'], 2); ?>" disabled>
                <a href="?page=recharge" class="btn-small">充值</a>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存修改</button>
                <a href="?page=changepwd" class="btn btn-secondary">修改密码</a>
            </div>
        </form>
    </div>
    
    <!-- 快捷登录绑定 -->
    <div class="profile-card" style="margin-top: 30px;">
        <h3 style="margin-bottom: 20px;">🔗 快捷登录绑定</h3>
        <p style="color: var(--text-secondary); margin-bottom: 20px;">绑定后可使用第三方账号快速登录</p>
        
        <div class="oauth-bindings">
            <?php foreach ($oauth_configs as $type => $config): ?>
                <?php $is_bound = isset($user_bindings[$type]); ?>
                <div class="oauth-item">
                    <div class="oauth-info">
                        <div class="oauth-icon" style="background: <?php echo $config['color']; ?>;">
                            <img src="/assets/svg/<?php echo $config['icon']; ?>" style="width: 24px; height: 24px;" alt="<?php echo $config['name']; ?>">
                        </div>
                        <span class="oauth-name"><?php echo $config['name']; ?></span>
                        <?php if ($is_bound): ?>
                            <span class="oauth-status bound">✓ 已绑定</span>
                        <?php else: ?>
                            <span class="oauth-status unbind">未绑定</span>
                        <?php endif; ?>
                    </div>
                    <div class="oauth-action">
                        <?php if ($is_bound): ?>
                            <form method="POST" style="display: inline;" onsubmit="return confirm('确定解绑吗？解绑后该账号将无法用于登录');">
                                <input type="hidden" name="action" value="unbind">
                                <input type="hidden" name="oauth_type" value="<?php echo $type; ?>">
                                <button type="submit" class="btn-unbind">解绑</button>
                            </form>
                        <?php else: ?>
                            <a href="<?php echo $config['bind_url']; ?>" class="btn-bind">去绑定</a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="bind-tip">
            <p>💡 温馨提示：</p>
            <ul>
                <li>绑定后可使用第三方账号一键登录，无需输入密码</li>
                <li>一个账号可以绑定多个第三方登录方式</li>
                <li>解绑后该第三方账号将无法登录，但不影响账号正常使用</li>
            </ul>
        </div>
    </div>
</div>

<style>
.profile-card {
    max-width: 500px;
    margin: 0 auto;
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
}
.profile-avatar-section {
    text-align: center;
    margin-bottom: 30px;
}
.profile-avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
    margin-bottom: 10px;
    border: 3px solid var(--border-color);
}
.btn-small {
    display: inline-block;
    padding: 5px 12px;
    background: var(--primary-color);
    color: white;
    border-radius: 5px;
    text-decoration: none;
    font-size: 12px;
}
.btn-small:hover {
    background: var(--primary-hover);
}
.profile-form .form-group {
    margin-bottom: 20px;
}
.profile-form input[disabled] {
    background: var(--bg-secondary);
    cursor: not-allowed;
}
.form-actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}
/* 快捷登录绑定样式 */
.oauth-bindings {
    margin-bottom: 20px;
}
.oauth-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--border-color);
}
.oauth-item:last-child {
    border-bottom: none;
}
.oauth-info {
    display: flex;
    align-items: center;
    gap: 12px;
}
.oauth-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.oauth-name {
    font-weight: 500;
    min-width: 60px;
}
.oauth-status {
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 20px;
}
.oauth-status.bound {
    background: rgba(16,185,129,0.1);
    color: #10b981;
}
.oauth-status.unbind {
    background: rgba(239,68,68,0.1);
    color: #ef4444;
}
.btn-bind {
    padding: 6px 16px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border-radius: 20px;
    text-decoration: none;
    font-size: 13px;
    transition: all 0.2s;
}
.btn-bind:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(102,126,234,0.4);
}
.btn-unbind {
    padding: 6px 16px;
    background: transparent;
    border: 1px solid #ef4444;
    color: #ef4444;
    border-radius: 20px;
    cursor: pointer;
    font-size: 13px;
    transition: all 0.2s;
}
.btn-unbind:hover {
    background: #ef4444;
    color: white;
}
.bind-tip {
    margin-top: 20px;
    padding: 15px;
    background: var(--bg-secondary);
    border-radius: 12px;
    font-size: 13px;
    color: var(--text-secondary);
}
.bind-tip ul {
    margin-left: 20px;
    margin-top: 8px;
}
.bind-tip li {
    margin: 5px 0;
}
</style>