<?php
ob_start();
require_once '../../config.php';

$token = $_GET['token'] ?? '';

if (empty($token)) {
    die('无效的二维码');
}

// 检查二维码是否有效
$qrcode = $db->fetchOne("SELECT * FROM login_qrcodes WHERE token = '$token'");

if (!$qrcode) {
    die('二维码不存在');
}

if (strtotime($qrcode['expire_at']) < time()) {
    die('二维码已过期');
}

// 获取生成二维码的用户（PC端已登录用户）
$generate_user_id = $qrcode['generate_user_id'] ?? 0;
$pc_user = null;
if ($generate_user_id > 0) {
    $pc_user = $db->fetchOne("SELECT id, username, avatar FROM users WHERE id = $generate_user_id");
}

// 判断当前手机端是否已登录
$current_user = currentUser();
$scan_user_id = $current_user ? $current_user['id'] : 0;

// 更新为已扫描状态
$db->query("UPDATE login_qrcodes SET status = 1, scan_user_id = $scan_user_id WHERE token = '$token'");
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>确认登录</title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .card {
            background: white;
            border-radius: 28px;
            padding: 40px 30px;
            max-width: 400px;
            width: 100%;
            text-align: center;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }
        .avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 20px;
            border: 3px solid #667eea;
        }
        .icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 24px;
        }
        h2 {
            font-size: 24px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 8px;
        }
        .desc {
            color: #64748b;
            font-size: 14px;
            margin-bottom: 32px;
        }
        .btn {
            display: block;
            width: 100%;
            padding: 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            margin-bottom: 12px;
        }
        .btn-secondary {
            background: #f1f5f9;
            color: #64748b;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 0.6s linear infinite;
            margin-right: 8px;
            vertical-align: middle;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="card">
        <?php if ($pc_user): ?>
            <img src="<?php echo htmlspecialchars($pc_user['avatar'] ?? '/assets/uploads/default_avatar.png'); ?>" class="avatar" alt="">
        <?php else: ?>
            <div class="icon">
                <img src="https://api.iconify.design/mdi:qrcode-scan.svg?color=white" width="40" height="40" alt="">
            </div>
        <?php endif; ?>
        
        <?php if ($current_user): ?>
            <!-- 手机已登录 -->
            <h2>确认登录</h2>
            <p class="desc">
                您将使用账号 <strong><?php echo htmlspecialchars($current_user['username']); ?></strong> 登录到 PC 端
            </p>
        <?php elseif ($pc_user): ?>
            <!-- 手机未登录，但 PC 端已登录 -->
            <h2>确认登录</h2>
            <p class="desc">
                确认后，您将使用账号 <strong><?php echo htmlspecialchars($pc_user['username']); ?></strong> 登录手机端
            </p>
        <?php else: ?>
            <!-- 两端都未登录 -->
            <h2>无法登录</h2>
            <p class="desc">
                请登录任何pc端或者移动端在扫描二维码登录
            </p>
        <?php endif; ?>
        
        <?php if ($pc_user || $current_user): ?>
            <button class="btn" id="confirmBtn" onclick="confirmLogin()">
                <span id="btnText">确认登录</span>
            </button>
            <button class="btn btn-secondary" onclick="window.location.href='/m/'">取消</button>
        <?php else: ?>
            <a href="/m/login.php" class="btn">去登录</a>
        <?php endif; ?>
    </div>
    
    <script>
        const token = '<?php echo htmlspecialchars($token); ?>';
        const isLoggedIn = <?php echo $current_user ? 'true' : 'false'; ?>;
        const pcUserId = <?php echo $pc_user ? $pc_user['id'] : '0'; ?>;
        
        // 自动确认（1.5秒后自动点击）
        // <?php if ($pc_user || $current_user): ?>
        // setTimeout(() => confirmLogin(), 1500);
        // <?php endif; ?>
        
        async function confirmLogin() {
            const btn = document.getElementById('confirmBtn');
            const btnText = document.getElementById('btnText');
            
            if (!btn) return;
            
            btn.disabled = true;
            btnText.innerHTML = '<span class="loading"></span> 确认中...';
            
            try {
                const res = await fetch('/api/qrcode_confirm.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `token=${token}&action=confirm`
                });
                const data = await res.json();
                
                if (data.code === 0) {
                    btnText.innerHTML = ' 登录成功！';
                    setTimeout(() => {
                        window.location.href = data.redirect || '/m/';
                    }, 1000);
                } else {
                    alert(data.msg || '确认失败');
                    btn.disabled = false;
                    btnText.innerHTML = '确认登录';
                }
            } catch (e) {
                alert('网络错误');
                btn.disabled = false;
                btnText.innerHTML = '确认登录';
            }
        }
    </script>
</body>
</html>