<?php
// bd.php - 查询QQ绑定账号
session_start();
require_once '../config.php';

$message = '';
$accounts = [];

// 1. 优先获取URL参数 (用于从 home.php 跳转过来自动填写)
$search_qq = $_GET['qq'] ?? '';

// 2. 如果有POST提交，则使用POST数据
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_qq'])) {
    $search_qq = trim($_POST['search_qq']);
}

// 3. 如果有QQ号，执行查询
if (!empty($search_qq)) {
    if (!preg_match('/^[1-9][0-9]{4,10}$/', $search_qq)) {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $message = '请输入正确的QQ号码';
        }
    } else {
        $stmt = mysqli_prepare($conn, "SELECT id, username, qq, created_at FROM users WHERE qq = ? ORDER BY id ASC");
        mysqli_stmt_bind_param($stmt, "s", $search_qq);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        
        $accounts = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $accounts[] = $row;
        }
        
        if (empty($accounts)) {
            $message = '该QQ号未绑定任何账号';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>查询绑定账号</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            background: linear-gradient(145deg, #1e2b4a, #152238);
            min-height: 100vh;
            font-family: 'Segoe UI', Roboto, system-ui, sans-serif;
            padding: 20px;
            color: white;
            display: flex; justify-content: center; align-items: center;
        }
        .container {
            width: 100%; max-width: 500px;
            background: rgba(255,255,255,0.07);
            border-radius: 24px;
            padding: 30px 20px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        h2 { text-align: center; color: #FFD966; margin-bottom: 25px; }
        
        .search-box { display: flex; gap: 10px; margin-bottom: 20px; }
        .input-field {
            flex: 1; padding: 12px 16px; border-radius: 40px; border: 1px solid rgba(255,255,255,0.2);
            background: rgba(255,255,255,0.1); color: white; font-size: 15px; outline: none;
        }
        .btn {
            padding: 12px 24px; border-radius: 40px; border: none; font-weight: bold; cursor: pointer;
            transition: 0.2s;
        }
        .btn-primary { background: linear-gradient(145deg, #3b82f6, #2563eb); color: white; }
        
        .message { text-align: center; padding: 15px; background: rgba(255,255,255,0.1); border-radius: 12px; margin-bottom: 20px; color: #ff6b6b; }
        
        .account-card {
            background: rgba(0,0,0,0.3); border-radius: 16px; padding: 16px; margin-bottom: 15px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .account-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
        .account-name { font-size: 18px; font-weight: bold; color: #4ECDC4; }
        .account-id { font-size: 12px; color: #aaa; margin-top: 2px; }
        .account-time { font-size: 12px; color: #aaa; }
        
        .action-btns { display: flex; gap: 8px; flex-wrap: wrap; }
        .btn-sm {
            flex: 1; padding: 10px; border-radius: 20px; border: none; cursor: pointer; font-size: 13px;
            font-weight: 600; transition: 0.2s; min-width: 70px;
        }
        .btn-login { background: #FFD966; color: #1e2b4a; }
        .btn-change { background: #17a2b8; color: white; }
        .btn-unbind { background: rgba(255,255,255,0.1); color: #ff6b6b; border: 1px solid rgba(255,107,107,0.3); }
        
        /* 弹窗样式 */
        .modal {
            display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.8); justify-content: center; align-items: center; z-index: 999;
        }
        .modal-box {
            background: #1e2b4a; padding: 25px 20px; border-radius: 20px; width: 90%; max-width: 320px;
            text-align: center; border: 1px solid rgba(255,255,255,0.1);
        }
        .modal-title { font-size: 18px; margin-bottom: 20px; color: #FFD966; font-weight: bold; }
        .qr-area { 
            min-height: 150px; 
            display: flex; 
            flex-direction: column; 
            justify-content: center; 
            align-items: center; 
        }
        
        /* 【彻底修复二维码歪了】强制重置所有可能导致变形的CSS */
        #modalQrImg {
            width: 180px !important; 
            height: 180px !important; 
            border-radius: 8px; 
            display: block !important; /* block防止底部留白 */
            transform: none !important; /* 强制不旋转 */
            max-width: none !important; /* 解除宽度限制 */
            opacity: 1 !important;
            object-fit: contain !important;
            margin: 0 auto; /* 居中 */
        }

        .status-text { margin: 15px 0 10px; font-size: 13px; color: #aaa; min-height: 20px;}
        
        /* 新增：红色不换行提示 */
        .qr-warning {
            color: #ff4d4f;
            font-size: 12px;
            white-space: nowrap; /* 强制不换行 */
            margin-top: 5px;
            margin-bottom: 10px;
        }

        .modal-actions { display: flex; flex-direction: column; gap: 10px; margin-top: 20px; }
        .modal-btn {
            width: 100%; padding: 12px; border-radius: 25px; border: none; font-weight: bold; cursor: pointer;
            transition: 0.2s; font-size: 14px;
        }
        .btn-confirm { background: #4CAF50; color: white; }
        .btn-refresh { background: rgba(255,255,255,0.1); color: white; border: 1px solid rgba(255,255,255,0.2); }
        .btn-close { background: transparent; color: #aaa; margin-top: 5px; font-size: 12px; }

        /* 输入框样式 */
        .input-new-qq {
            width: 100%; padding: 12px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.2);
            background: rgba(0,0,0,0.3); color: white; font-size: 16px; text-align: center;
            margin: 10px 0; outline: none;
        }
        .input-new-qq::placeholder { color: #888; }
    </style>
</head>
<body>
<div class="container">
    <h2>🔍 查询绑定账号</h2>
    
    <form method="post" class="search-box">
        <input type="text" name="search_qq" class="input-field" placeholder="输入要查询的QQ号" value="<?php echo htmlspecialchars($search_qq); ?>">
        <button type="submit" class="btn btn-primary">查询</button>
    </form>
    
    <?php if($message): ?>
        <div class="message"><?php echo $message; ?></div>
    <?php endif; ?>
    
    <?php if(!empty($accounts)): ?>
        <div class="result-list">
            <?php foreach($accounts as $index => $acc): ?>
                <div class="account-card">
                    <div class="account-header">
                        <div>
                            <div class="account-name"><?php echo htmlspecialchars($acc['username']); ?></div>
                            <div class="account-id">ID: <?php echo $acc['id']; ?></div>
                        </div>
                        <div class="account-time">
                            注册于 <?php echo date('Y-m-d', strtotime($acc['created_at'])); ?>
                        </div>
                    </div>
                    <div class="action-btns">
                        <button class="btn-sm btn-login" onclick="openScanner('login', <?php echo $acc['id']; ?>, '<?php echo htmlspecialchars($acc['username']); ?>', '<?php echo htmlspecialchars($acc['qq']); ?>')">
                            登录
                        </button>
                        <button class="btn-sm btn-change" onclick="openScanner('change_qq', <?php echo $acc['id']; ?>, '<?php echo htmlspecialchars($acc['username']); ?>', '<?php echo htmlspecialchars($acc['qq']); ?>')">
                            换绑
                        </button>
                        <button class="btn-sm btn-unbind" onclick="openScanner('unbind', <?php echo $acc['id']; ?>, '<?php echo htmlspecialchars($acc['username']); ?>', '<?php echo htmlspecialchars($acc['qq']); ?>')">
                            解绑
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 扫码弹窗 -->
<div class="modal" id="scanModal">
    <div class="modal-box">
        <div class="modal-title" id="modalTitle">扫码操作</div>
        
        <!-- 扫码区域 -->
        <div id="qrSection" class="qr-area">
            <div id="loadingText">二维码加载中...</div>
            <img id="modalQrImg">
            <!-- 新增：红色不换行提示 -->
            <div class="qr-warning" id="qrWarning">（通常在10秒∽20秒内过期）</div>
        </div>
        
        <!-- 输入新QQ区域 (初始隐藏) -->
        <div id="inputSection" style="display:none;">
            <p style="font-size:13px; color:#aaa; margin-bottom:10px;">身份验证成功！<br>请输入你要绑定的新QQ号：</p>
            <input type="text" id="newQQInput" class="input-new-qq" placeholder="输入新QQ号">
        </div>

        <div class="status-text" id="modalStatus"></div>
        
        <div class="modal-actions">
            <button class="modal-btn btn-confirm" id="btnConfirm" onclick="checkResult()">我已完成</button>
            <button class="modal-btn btn-refresh" id="btnRefresh" onclick="refreshQr()">刷新二维码</button>
            <button class="modal-btn btn-close" onclick="closeModal()">取消</button>
        </div>
    </div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
let currentAction = '';
let currentUserId = 0;
let currentOldQQ = '';
let currentQrsig = '';
let checkTimer = null;

function openScanner(action, userId, username, oldQQ) {
    currentAction = action;
    currentUserId = userId;
    currentOldQQ = oldQQ;
    currentQrsig = '';
    
    // 重置界面
    document.getElementById('qrSection').style.display = 'block';
    document.getElementById('inputSection').style.display = 'none';
    document.getElementById('btnRefresh').style.display = 'block';
    document.getElementById('btnConfirm').innerText = '我已完成';
    document.getElementById('modalStatus').textContent = '';
    document.getElementById('newQQInput').value = '';
    
    // 显示过期提示
    document.getElementById('qrWarning').style.display = 'block';

    const title = document.getElementById('modalTitle');
    const statusBox = document.getElementById('modalStatus');
    
    if(action === 'login') {
        title.textContent = '扫码登录: ' + username;
        statusBox.textContent = '请使用绑定的QQ号扫码';
    } else if(action === 'change_qq') {
        title.textContent = '换绑QQ: ' + username;
        statusBox.innerHTML = '第一步：请使用<strong>当前绑定的QQ</strong>扫码验证身份';
    } else {
        title.textContent = '解除绑定: ' + username;
        statusBox.textContent = '请使用当前绑定的QQ号扫码确认解绑';
    }
    
    document.getElementById('scanModal').style.display = 'flex';
    getQrPic();
}

function closeModal() {
    document.getElementById('scanModal').style.display = 'none';
    if(checkTimer) clearInterval(checkTimer);
}

function refreshQr() {
    getQrPic();
    document.getElementById('modalStatus').textContent = '二维码已刷新';
}

function getQrPic() {
    if(checkTimer) clearInterval(checkTimer);
    
    $("#loadingText").text('二维码加载中...').show();
    $("#modalQrImg").hide();
    $("#qrWarning").hide(); // 加载中隐藏提示
    
    $.get('qrlogin.php?do=getqrpic', function(data) {
        if(data.saveOK == 0) {
            currentQrsig = data.qrsig;
            $("#modalQrImg").attr('src', 'data:image/png;base64,' + data.data).show();
            $("#loadingText").hide();
            $("#qrWarning").show(); // 显示提示
            startCheckLoop();
        } else {
            $("#loadingText").text('获取二维码失败: ' + data.msg);
        }
    }, 'json');
}

function startCheckLoop() {
    if(checkTimer) clearInterval(checkTimer);
    
    checkTimer = setInterval(function() {
        if(!currentQrsig) return;
        
        $.get('qrlogin.php', { do: 'qrlogin', qrsig: currentQrsig }, function(data) {
            if(data.saveOK == 0) {
                clearInterval(checkTimer);
                const scannedQQ = data.uin;
                
                if(currentAction === 'change_qq' || currentAction === 'unbind' || currentAction === 'login') {
                    verifyAction(scannedQQ);
                }
            } else if(data.saveOK == 1) {
                clearInterval(checkTimer);
                $("#modalStatus").html('<span style="color:#ff6b6b">二维码已过期，请点击刷新</span>');
                currentQrsig = '';
            } else if(data.saveOK == 3) {
                $("#modalStatus").html('<span style="color:#FFD966">扫描成功，请在手机上点击确认...</span>');
            }
        }, 'json');
    }, 2000);
}

function checkResult() {
    // 如果当前是输入新QQ的步骤
    if(document.getElementById('inputSection').style.display === 'block') {
        submitNewQQ();
    } else {
        // 否则是扫码验证步骤
        if(!currentQrsig) { alert('请先刷新二维码'); return; }
        document.getElementById('modalStatus').textContent = '正在验证...';
        
        $.get('qrlogin.php', { do: 'qrlogin', qrsig: currentQrsig }, function(data) {
            if(data.saveOK == 0) {
                verifyAction(data.uin);
            } else if(data.saveOK == 1) {
                $("#modalStatus").html('<span style="color:#ff6b6b">二维码已过期</span>');
            } else {
                $("#modalStatus").html('<span style="color:#ff6b6b">未检测到成功授权，请重试</span>');
            }
        }, 'json');
    }
}

// 验证扫描的QQ与操作是否匹配
function verifyAction(scannedQQ) {
    $("#modalStatus").html('<span style="color:#4CAF50">扫码成功！正在验证...</span>');
    
    // 对于换绑和解绑，必须用旧QQ扫码
    if((currentAction === 'change_qq' || currentAction === 'unbind' || currentAction === 'login') && scannedQQ !== currentOldQQ) {
        $("#modalStatus").html('<span style="color:#ff6b6b">错误：请使用该账号绑定的QQ扫码！</span>');
        return;
    }

    // 根据操作类型分流
    if(currentAction === 'change_qq') {
        // 验证通过，显示输入框
        showNewQQInput();
    } else {
        // 登录或解绑，直接执行
        processAction(scannedQQ);
    }
}

// 显示输入新QQ的界面
function showNewQQInput() {
    document.getElementById('qrSection').style.display = 'none';
    document.getElementById('inputSection').style.display = 'block';
    document.getElementById('btnRefresh').style.display = 'none';
    document.getElementById('btnConfirm').innerText = '确认更换';
    document.getElementById('modalStatus').textContent = '';
    document.getElementById('newQQInput').focus();
}

// 提交新QQ号
function submitNewQQ() {
    const newQQ = document.getElementById('newQQInput').value.trim();
    
    if(!newQQ) { alert('请输入新QQ号'); return; }
    if(!/^[1-9][0-9]{4,10}$/.test(newQQ)) { alert('请输入正确的QQ号格式'); return; }
    if(newQQ === currentOldQQ) { alert('新QQ号不能与旧QQ号相同'); return; }

    document.getElementById('modalStatus').textContent = '正在处理...';
    
    $.post('bd_action.php', {
        action: 'change_qq',
        user_id: currentUserId,
        qq: newQQ
    }, function(res) {
        if(res.status == 'success') {
            $("#modalStatus").html('<span style="color:#4CAF50">换绑成功！页面即将刷新</span>');
            setTimeout(() => { location.reload(); }, 1500);
        } else {
            $("#modalStatus").html('<span style="color:#ff6b6b">' + res.message + '</span>');
        }
    }, 'json');
}

// 处理登录和解绑
function processAction(scannedQQ) {
    $.post('bd_action.php', {
        action: currentAction,
        user_id: currentUserId,
        qq: scannedQQ
    }, function(res) {
        if(res.status == 'success') {
            if(currentAction === 'login') {
                $("#modalStatus").html('<span style="color:#4CAF50">登录成功！正在跳转...</span>');
                setTimeout(() => { window.location.href = 'home.php'; }, 1000);
            } else if(currentAction === 'unbind') {
                $("#modalStatus").html('<span style="color:#4CAF50">解绑成功！页面即将刷新</span>');
                setTimeout(() => { location.reload(); }, 1500);
            }
        } else {
            $("#modalStatus").html('<span style="color:#ff6b6b">' + res.message + '</span>');
        }
    }, 'json');
}
</script>
</body>
</html>
