<?php
session_start();
require_once '../config.php';
require_once '../core/functions.php';

if (isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true) {
    $goto = isset($_GET['redirect']) ? $_GET['redirect'] : 'home.php';
    header('Location: ' . $goto);
    exit;
}

$redirect_url = 'home.php';
if(isset($_GET['redirect'])) $redirect_url = $_GET['redirect'];
elseif(isset($_SERVER['HTTP_REFERER'])) {
    if(strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false && strpos($_SERVER['HTTP_REFERER'], 'index.php') === false) {
        $redirect_url = $_SERVER['HTTP_REFERER'];
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户中心</title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css">
    <style>
        /* 原有样式 */
        .user-container { display: flex; justify-content: center; align-items: center; min-height: 80vh; }
        .form-box { width: 100%; max-width: 400px; padding: 30px; background: #fff; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); position: relative;}
        .form-tabs { display: flex; margin-bottom: 20px; border-bottom: 2px solid #f0f0f0; }
        .form-tabs span { flex: 1; text-align: center; padding: 10px; cursor: pointer; color: #999; font-weight: bold; transition: all 0.3s; }
        .form-tabs span.active { color: #007bff; border-bottom: 2px solid #007bff; margin-bottom: -2px; }
        .form-group { margin-bottom: 15px; }
        .form-group input { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; font-size: 14px; }
        .form-group input:focus { border-color: #007bff; outline: none; }
        .captcha-row { display: flex; gap: 10px; align-items: center; }
        .captcha-row input { flex: 1; }
        .captcha-row img { height: 42px; width: 100px; cursor: pointer; border-radius: 5px; border: 1px solid #ddd; }
        .btn-submit { width: 100%; padding: 12px; border: none; border-radius: 5px; color: #fff; font-size: 16px; cursor: pointer; background-color: #007bff; transition: background 0.3s; }
        .btn-submit:hover { background-color: #0056b3; }
        .btn-group { text-align: right; margin-top: 15px; font-size: 13px; }
        .btn-group a { color: #666; text-decoration: none; }
        .error-msg { color: #dc3545; font-size: 13px; margin-bottom: 10px; text-align: center; display: none; }
        #reg-form { display: none; }
        .divider { display: flex; align-items: center; margin: 20px 0; }
        .divider::before, .divider::after { content: ''; flex: 1; border-bottom: 1px solid #eee; }
        .divider span { padding: 0 10px; color: #999; font-size: 12px; }
        .btn-qrlogin { width: 100%; padding: 12px; border: 1px dashed #007bff; border-radius: 5px; background: #f0f7ff; color: #007bff; font-size: 15px; cursor: pointer; transition: all 0.3s; }
        
        /* 弹窗样式 */
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); justify-content: center; align-items: center; z-index: 999; }
        .modal-box { background: #fff; padding: 30px 20px 20px 20px; border-radius: 12px; width: 90%; max-width: 300px; text-align: center; position: relative; animation: popIn 0.3s; }
        @keyframes popIn { from { transform: scale(0.9); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .modal-close { position: absolute; top: 10px; right: 10px; width: 24px; height: 24px; line-height: 24px; border-radius: 50%; border: 1px solid #eee; background: #f5f5f5; font-size: 16px; color: #999; cursor: pointer; display: flex; align-items: center; justify-content: center; }
        
        /* 扫码弹窗特定样式 */
        .qr-area { min-height: 180px; display: flex; justify-content: center; align-items: center; flex-direction: column; }
        #qr-img { width: 180px; height: 180px; border-radius: 8px; }
        .qr-status { margin-top: 15px; font-size: 13px; color: #666; min-height: 20px; }
        .modal-actions { margin-top: 20px; display: flex; flex-direction: column; gap: 10px; }
        .modal-btn { width: 100%; padding: 10px; border-radius: 20px; border: none; cursor: pointer; font-size: 14px; }
        .btn-green { background: #28a745; color: white; }
        .btn-outline { background: white; border: 1px solid #ddd; color: #666; }

        /* 头像上传样式 */
        .avatar-upload-area { text-align: center; margin-bottom: 20px; position: relative; }
        .avatar-preview { width: 80px; height: 80px; border-radius: 50%; border: 2px dashed #ddd; margin: 0 auto; overflow: hidden; cursor: pointer; background: #f8f8f8; display: flex; align-items: center; justify-content: center; }
        .avatar-preview img { width: 100%; height: 100%; object-fit: cover; display: block; }
        .avatar-preview i { color: #ccc; font-size: 30px; font-style: normal; }
        .avatar-tip { font-size: 12px; color: #999; margin-top: 5px; }
        
        /* 二维码样式修复 */
        #qr-img { transform: none !important; opacity: 1 !important; max-width: none !important; }

        /* 【新增】账号选择列表样式 */
        .account-list-container { max-height: 300px; overflow-y: auto; margin: 15px 0; text-align: left; }
        .account-item {
            display: flex; align-items: center; padding: 12px; background: #f8f9fa; 
            border-radius: 8px; margin-bottom: 10px; cursor: pointer; transition: all 0.2s; border: 1px solid #eee;
        }
        .account-item:hover { background: #e9ecef; border-color: #007bff; }
        .account-item img { width: 40px; height: 40px; border-radius: 50%; margin-right: 12px; object-fit: cover; background: #ddd; }
        .account-info h4 { margin: 0 0 4px 0; font-size: 15px; color: #333; }
        .account-info p { margin: 0; font-size: 12px; color: #888; }
    </style>
</head>
<body>
    <div class="user-container">
        <div class="form-box">
            <div class="form-tabs">
                <span class="active" onclick="switchTab('login')">登录</span>
                <span onclick="switchTab('register')">注册</span>
            </div>

            <div id="error-msg" class="error-msg"></div>

            <!-- 登录表单 -->
            <form id="login-form">
                <div class="form-group">
                    <input type="text" name="username" placeholder="用户名" required>
                </div>
                <div class="form-group">
                    <input type="password" name="password" placeholder="密码" required>
                </div>
                <div class="form-group">
                    <div class="captcha-row">
                        <input type="text" name="code" placeholder="验证码" required>
                        <img src="code.php" onclick="this.src='code.php?r='+Math.random();" title="点击刷新">
                    </div>
                </div>
                <button type="submit" class="btn-submit" id="btn-login">立即登录</button>
                
                <div class="divider"><span>其他方式</span></div>
                <button type="button" class="btn-qrlogin" onclick="openQrLogin()">📱 扫码登录</button>
            </form>

            <!-- 注册表单 -->
            <form id="reg-form">
                <div class="avatar-upload-area">
                    <div class="avatar-preview" onclick="document.getElementById('avatarInput').click()">
                        <img id="avatarPreviewImg" style="display:none;">
                        <i id="avatarPlaceholder">+</i>
                    </div>
                    <div class="avatar-tip">点击上传头像 (可选)</div>
                    <input type="file" id="avatarInput" accept="image/*" style="display:none">
                </div>

                <div class="form-group">
                    <input type="text" name="username" placeholder="用户名" required>
                </div>
                <div class="form-group">
                    <input type="password" name="password" placeholder="密码 (至少6位)" required>
                </div>
                <div class="form-group">
                    <input type="text" name="qq" placeholder="QQ号 (必填，用于找回密码)" required>
                </div>
                <div class="form-group">
                    <div class="captcha-row">
                        <input type="text" name="code" placeholder="验证码" required>
                        <img src="code.php" onclick="this.src='code.php?r='+Math.random();" title="点击刷新">
                    </div>
                </div>
                <input type="hidden" name="avatar_data" id="avatarHiddenInput">
                
                <button type="submit" class="btn-submit" id="btn-reg" style="background-color: #28a745;">立即注册</button>
            </form>

            <div id="link-area" class="btn-group">
                <a href="bd.php">忘记密码 / 查询绑定</a>
            </div>
        </div>
    </div>

    <!-- 扫码登录弹窗 -->
    <div class="modal" id="qrModal" onclick="handleModalClick(event)">
        <div class="modal-box" onclick="event.stopPropagation()">
            <button class="modal-close" onclick="closeQrModal()">×</button>
            <div class="modal-title">QQ扫码安全登录</div>
            <div class="qr-area">
                <div id="qr-loading" style="color:#999;">二维码加载中...</div>
                <img id="qr-img" style="display:none;">
            </div>
            <div id="qr-status" class="qr-status">请使用手机QQ扫描二维码</div>
            <div class="modal-actions">
                <button class="modal-btn btn-green" onclick="checkScan()">我已完成</button>
                <button class="modal-btn btn-outline" onclick="refreshQr()">刷新过期二维码</button>
            </div>
        </div>
    </div>

    <!-- 【新增】账号选择弹窗 -->
    <div class="modal" id="selectModal">
        <div class="modal-box" style="max-width: 350px;" onclick="event.stopPropagation()">
            <button class="modal-close" onclick="closeSelectModal()">×</button>
            <div class="modal-title">选择登录账号</div>
            <p style="font-size: 13px; color: #666; margin-bottom: 5px;">该QQ绑定了多个账号，请选择：</p>
            <div id="accountListContainer" class="account-list-container">
                <!-- 账号列表将通过JS动态生成 -->
            </div>
        </div>
    </div>

    <!-- 头像裁剪弹窗 -->
    <div class="modal" id="avatarModal">
        <div class="modal-box" onclick="event.stopPropagation()" style="max-width: 400px; padding: 20px;">
            <button class="modal-close" onclick="closeAvatarModal()">×</button>
            <div class="modal-title">裁剪头像</div>
            <div style="max-height: 300px;">
                <img id="cropImage" style="max-width: 100%;">
            </div>
            <div class="modal-actions" style="margin-top: 15px;">
                <button class="modal-btn btn-green" id="confirmAvatarBtn" onclick="confirmRegistrationAvatar()">确定上传</button>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
    
    <script>
    var referer = '<?php echo $redirect_url; ?>';
    var currentQrsig = '';
    var checkTimer = null;
    var cropper; 

    // --- 头像上传逻辑 ---
    const avatarInput = document.getElementById('avatarInput');
    const avatarPreviewImg = document.getElementById('avatarPreviewImg');
    const avatarPlaceholder = document.getElementById('avatarPlaceholder');
    const avatarHiddenInput = document.getElementById('avatarHiddenInput');

    avatarInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
                $('#avatarModal').fadeIn(200);
                $('#cropImage').attr('src', event.target.result);
                
                if (cropper) cropper.destroy();
                cropper = new Cropper(document.getElementById('cropImage'), {
                    aspectRatio: 1,
                    viewMode: 1
                });
            };
            reader.readAsDataURL(file);
        }
    });

    function closeAvatarModal() { $('#avatarModal').fadeOut(200); }

    function confirmRegistrationAvatar() {
        if (!cropper) { alert('请先选择图片'); return; }
        var canvas = cropper.getCroppedCanvas({ width: 200, height: 200 });
        if (!canvas) { alert('图片处理失败'); return; }
        var dataUrl = canvas.toDataURL('image/jpeg', 0.9);
        
        avatarPreviewImg.src = dataUrl;
        avatarPreviewImg.style.display = 'block';
        avatarPlaceholder.style.display = 'none';
        avatarHiddenInput.value = dataUrl;
        closeAvatarModal();
    }

    // --- 表单逻辑 ---
    function switchTab(type) {
        document.querySelectorAll('.form-tabs span').forEach(e => e.classList.remove('active'));
        var linkArea = document.getElementById('link-area');
        
        if(type === 'login') {
            document.querySelector('.form-tabs span:first-child').classList.add('active');
            document.getElementById('login-form').style.display = 'block';
            document.getElementById('reg-form').style.display = 'none';
            linkArea.style.display = 'block';
        } else {
            document.querySelector('.form-tabs span:last-child').classList.add('active');
            document.getElementById('login-form').style.display = 'none';
            document.getElementById('reg-form').style.display = 'block';
            linkArea.style.display = 'none';
        }
        document.getElementById('error-msg').style.display = 'none';
    }

    function bindForm(formId, action, btnId) {
        document.getElementById(formId).addEventListener('submit', function(e) {
            e.preventDefault();
            const btn = document.getElementById(btnId);
            const originalText = btn.innerText;
            const errorDiv = document.getElementById('error-msg');
            
            btn.disabled = true; btn.innerText = '请稍候...'; errorDiv.style.display = 'none';
            const formData = new FormData(this);
            formData.append('action', action);

            fetch('ajax.php', { method: 'POST', body: formData })
            .then(res => res.json())
            .then(data => {
                btn.disabled = false; btn.innerText = originalText;
                if (data.status === 'success') {
                    if (action === 'register') {
                        alert('注册成功！请登录');
                        switchTab('login');
                        document.querySelector('#login-form input[name="username"]').value = formData.get('username');
                    } else {
                        window.location.href = referer;
                    }
                } else {
                    errorDiv.textContent = data.message; errorDiv.style.display = 'block';
                    document.querySelector('#' + formId + ' .captcha-row img').click();
                }
            })
            .catch(error => { btn.disabled = false; btn.innerText = originalText; errorDiv.textContent = '网络错误'; errorDiv.style.display = 'block'; });
        });
    }

    bindForm('login-form', 'login', 'btn-login');
    bindForm('reg-form', 'register', 'btn-reg');

    // --- 扫码登录逻辑 ---
    function openQrLogin() {
        document.getElementById('qrModal').style.display = 'flex';
        refreshQr();
    }

    function closeQrModal() {
        document.getElementById('qrModal').style.display = 'none';
        if(checkTimer) clearInterval(checkTimer);
        currentQrsig = '';
    }

    function handleModalClick(event) {
        if (event.target.id === 'qrModal') closeQrModal();
    }

    function refreshQr() {
        if(checkTimer) clearInterval(checkTimer);
        $("#qr-loading").text("刷新中...").show();
        $("#qr-img").hide();
        $("#qr-status").text("请使用手机QQ扫描二维码");

        $.get('qrlogin.php?do=getqrpic', function(d) {
            if(d.saveOK == 0) {
                currentQrsig = d.qrsig;
                $("#qr-img").attr('src', 'data:image/png;base64,' + d.data).show();
                $("#qr-loading").hide();
                startLoopCheck();
            } else { $("#qr-loading").text("获取失败: " + d.msg); }
        }, 'json');
    }

    function startLoopCheck() {
        checkTimer = setInterval(function() {
            if(!currentQrsig) return;
            $.get('qrlogin.php', { do: 'qrlogin', qrsig: currentQrsig }, function(d) {
                if(d.saveOK == 0) {
                    clearInterval(checkTimer);
                    $("#qr-status").html('<span style="color:green">扫码成功！跳转中...</span>');
                    qqLogin(d.uin);
                } else if(d.saveOK == 1) {
                    clearInterval(checkTimer);
                    $("#qr-status").html('<span style="color:red">二维码已过期，请刷新</span>');
                    currentQrsig = '';
                } else if(d.saveOK == 3) {
                    $("#qr-status").text('扫描成功，请在手机上确认...');
                }
            }, 'json');
        }, 2000);
    }

    function checkScan() {
        if(!currentQrsig) { alert('请先刷新二维码'); return; }
        $.get('qrlogin.php', { do: 'qrlogin', qrsig: currentQrsig }, function(d) {
            if(d.saveOK == 0) qqLogin(d.uin);
            else if(d.saveOK == 1) $("#qr-status").html('<span style="color:red">二维码已过期</span>');
            else $("#qr-status").html('<span style="color:red; font-weight:bold; font-size:15px;">未检测到扫码，请重试</span>');
        }, 'json');
    }

    // 【核心修改】处理登录逻辑
    function qqLogin(qq) {
        $("#qr-status").text('正在验证账号...');
        $.post('ajax.php', { action: 'qq_login', qq: qq }, function(res) {
            if(res.status == 'success') {
                // 单账号，直接登录
                $("#qr-status").html('<span style="color:green">登录成功！</span>');
                setTimeout(() => { window.location.href = referer; }, 800);
            } else if(res.status == 'multi_accounts') {
                // 【新增】多账号情况，显示选择列表
                closeQrModal(); // 关闭扫码弹窗
                showAccountSelection(res.accounts);
            } else if(res.message.indexOf('未绑定') !== -1) {
                // 未注册，跳转注册
                $("#qr-status").html('<span style="color:#FFD966">检测到新用户，正在跳转注册...</span>');
                setTimeout(() => {
                    closeQrModal();
                    switchTab('register');
                    document.querySelector('#reg-form input[name="qq"]').value = qq;
                    alert('检测到该QQ未绑定账号，请完善注册信息。');
                }, 500);
            } else {
                $("#qr-status").html('<span style="color:red">' + res.message + '</span>');
            }
        }, 'json');
    }

    // 【新增】显示账号选择弹窗
    function showAccountSelection(accounts) {
        var html = '';
        for(var i = 0; i < accounts.length; i++) {
            var acc = accounts[i];
            var avatar = acc.avatar ? '../' + acc.avatar : 'https://q.qlogo.cn/g?b=qq&nk=' + acc.qq + '&s=100';
            var regTime = acc.created_at ? acc.created_at.substring(0, 10) : '未知';
            
            html += '<div class="account-item" onclick="selectAccountLogin(' + acc.id + ')">';
            html += '<img src="' + avatar + '">';
            html += '<div class="account-info">';
            html += '<h4>' + acc.username + ' (ID: ' + acc.id + ')</h4>';
            html += '<p>注册时间: ' + regTime + '</p>';
            html += '</div>';
            html += '</div>';
        }
        $("#accountListContainer").html(html);
        $("#selectModal").fadeIn(200);
    }

    function closeSelectModal() {
        $("#selectModal").fadeOut(200);
    }

    // 【新增】选择账号后执行登录
    function selectAccountLogin(userId) {
        $.post('ajax.php', { action: 'select_account_login', user_id: userId }, function(res) {
            if(res.status == 'success') {
                window.location.href = referer;
            } else {
                alert('登录失败: ' + res.message);
            }
        }, 'json');
    }
    </script>
</body>
</html>
