<?php
ob_start();
require_once __DIR__ . '/../../config.php';$user_id = $_SESSION['user_id'];
$user = currentUser();

// 检查是否已绑定
$is_binded = !empty($user['union_id']) && $user['union_type'] == 'wechat';

// 处理解绑
if (isset($_GET['unbind']) && $is_binded) {
    $db->query("UPDATE users SET union_id = NULL, union_type = NULL WHERE id = $user_id");
    header('Location: ?page=bind_wechat&success=unbind');
    exit;
}
?>

<div class="bind-wechat-container">
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:wechat.svg?color=%2307C160" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            微信绑定
        </h2>
    </div>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success">
            <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="20" height="20" alt="">
            <?php echo $_GET['success'] == 'bind' ? '微信绑定成功！' : '微信解绑成功！'; ?>
        </div>
    <?php endif; ?>

    <?php if ($is_binded): ?>
        <!-- 已绑定状态 -->
        <div class="bind-card binded">
            <div class="bind-icon">
                <img src="https://api.iconify.design/mdi:wechat.svg?color=%23ffffff" width="48" height="48" alt="">
            </div>
            <div class="bind-info">
                <h3>已绑定微信</h3>
                <p>您可以使用微信验证码登录</p>
            </div>
            <a href="?page=bind_wechat&unbind=1" class="btn btn-danger" onclick="return confirm('确定解绑微信吗？解绑后将无法使用微信登录。')">
                <img src="https://api.iconify.design/mdi:link-off.svg?color=white" width="18" height="18" alt="">
                解绑微信
            </a>
        </div>
    <?php else: ?>
        <!-- 未绑定状态 -->
        <div class="bind-card">
            <div class="bind-icon">
                <img src="https://api.iconify.design/mdi:wechat.svg?color=%23ffffff" width="48" height="48" alt="">
            </div>
            <div class="bind-info">
                <h3>未绑定微信</h3>
                <p>绑定后可使用微信验证码登录</p>
            </div>
            <button class="btn btn-primary" onclick="showBindWechat()">
                <img src="https://api.iconify.design/mdi:link.svg?color=white" width="18" height="18" alt="">
                立即绑定
            </button>
        </div>
    <?php endif; ?>

    <div class="bind-tip">
        <h4>绑定说明</h4>
        <ul>
            <li>绑定微信后，您可以使用微信验证码快速登录</li>
            <li>一个微信账号只能绑定一个平台账号</li>
            <li>您可以随时解绑微信</li>
        </ul>
    </div>
</div>

<!-- 绑定弹窗 -->
<div id="bindWechatModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; align-items: center; justify-content: center;" onclick="if(event.target===this)this.remove()">
    <div style="background: white; border-radius: 20px; padding: 30px; width: 90%; max-width: 360px; text-align: center;" onclick="event.stopPropagation()">
        <h3 style="margin-bottom: 20px;">
            <img src="https://api.iconify.design/mdi:wechat.svg?color=%2307C160" width="24" height="24" style="vertical-align: middle; margin-right: 8px;">
            绑定微信
        </h3>
        
        <p style="color: #666; font-size: 14px; margin-bottom: 16px;">
            1. 扫描下方二维码关注公众号<br>
            2. 向公众号发送下方验证码<br>
            3. 发送后自动完成绑定
        </p>
        
        <img src="/assets/uploads/wechat.jpg" style="width: 200px; height: 200px; margin-bottom: 16px; border-radius: 10px;" alt="公众号二维码">
        
        <div id="bindCodeDisplay" style="background: #f5f5f5; padding: 20px; border-radius: 16px; margin-bottom: 16px;">
            <p style="color: #999; font-size: 13px; margin-bottom: 8px;">验证码</p>
            <div id="bindCode" style="font-size: 48px; font-weight: 700; letter-spacing: 8px; color: #07C160; font-family: monospace;">------</div>
            <p style="color: #999; font-size: 12px; margin-top: 8px;">有效期 5 分钟</p>
        </div>
        
        <p id="bindStatus" style="color: #666; font-size: 14px; margin-bottom: 16px;">
            等待发送验证码...
        </p>
        
        <button onclick="document.getElementById('bindWechatModal').remove(); if(bindPollingTimer) clearInterval(bindPollingTimer);" style="width: 100%; padding: 14px; background: #f5f5f5; border: none; border-radius: 10px; font-size: 16px; cursor: pointer;">取消</button>
    </div>
</div>

<style>
.bind-wechat-container {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
}

.page-header {
    margin-bottom: 30px;
}

.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
}

.alert {
    padding: 14px 20px;
    border-radius: 12px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.alert-success {
    background: #d1fae5;
    color: #065f46;
}

.bind-card {
    background: white;
    border-radius: 20px;
    padding: 30px;
    text-align: center;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    border: 1px solid #f0f0f0;
    margin-bottom: 24px;
}

.bind-card.binded {
    background: linear-gradient(135deg, #07C16015, #07C16005);
    border-color: #07C160;
}

.bind-icon {
    width: 80px;
    height: 80px;
    background: #07C160;
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
    box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
}

.bind-info h3 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 8px;
}

.bind-info p {
    color: #666;
    margin-bottom: 24px;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 30px;
    border-radius: 30px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    transition: all 0.2s;
    text-decoration: none;
}

.btn-primary {
    background: #07C160;
    color: white;
}

.btn-danger {
    background: #ef4444;
    color: white;
}

.bind-tip {
    background: #f8fafc;
    border-radius: 16px;
    padding: 24px;
}

.bind-tip h4 {
    font-size: 16px;
    margin-bottom: 16px;
}

.bind-tip ul {
    color: #666;
    font-size: 14px;
    padding-left: 20px;
}

.bind-tip li {
    margin-bottom: 8px;
}
</style>

<script>
let bindPollingTimer = null;
let bindCurrentToken = null;

async function showBindWechat() {
    try {
        const res = await fetch('/api/wechat-bind-generate.php');
        const data = await res.json();
        
        if (data.code === 0) {
            bindCurrentToken = data.token;
            document.getElementById('bindCode').textContent = data.verify_code;
            document.getElementById('bindWechatModal').style.display = 'flex';
            startBindPolling();
        } else {
            alert('生成验证码失败');
        }
    } catch (e) {
        alert('网络错误');
    }
}

function startBindPolling() {
    let count = 0;
    const maxCount = 150;
    
    bindPollingTimer = setInterval(async () => {
        count++;
        
        if (!bindCurrentToken) return;
        
        try {
            const res = await fetch('/api/wechat-bind-check.php?token=' + bindCurrentToken);
            const data = await res.json();
            
            const statusEl = document.getElementById('bindStatus');
            
            if (data.status === 'success') {
                statusEl.innerHTML = '✅ 绑定成功！';
                statusEl.style.color = '#10b981';
                clearInterval(bindPollingTimer);
                setTimeout(() => location.reload(), 1500);
            } else if (data.status === 'waiting') {
                statusEl.innerHTML = '⏳ 等待发送验证码...';
            }
            
            if (count >= maxCount) {
                clearInterval(bindPollingTimer);
                statusEl.innerHTML = '⏰ 验证码已过期，请重新获取';
                statusEl.style.color = '#ef4444';
            }
        } catch (e) {}
    }, 2000);
}
</script>