<?php
ob_start();
header('Content-Type: application/json');
require_once '../config.php';

$token = $_GET['token'] ?? '';
if (!$token) {
    echo json_encode(['code' => 1, 'msg' => '缺少token']);
    exit;
}

$token = $db->escape($token);
$qrcode = $db->fetchOne("SELECT * FROM login_qrcodes WHERE token = '$token'");

if (!$qrcode) {
    echo json_encode(['code' => 1, 'status' => 'invalid']);
    exit;
}

// 检查是否过期
if (strtotime($qrcode['expire_at']) < time()) {
    echo json_encode(['code' => 0, 'status' => 'expired']);
    exit;
}

// 状态 1 = 已扫描待确认
if ($qrcode['status'] == 1) {
    $scan_user = null;
    if ($qrcode['scan_user_id'] > 0) {
        $scan_user = $db->fetchOne("SELECT id, username, avatar FROM users WHERE id = " . $qrcode['scan_user_id']);
    }
    
    echo json_encode([
        'code' => 0,
        'status' => 'scanned',
        'user' => [
            'username' => $scan_user['username'] ?? '手机用户',
            'avatar' => $scan_user['avatar'] ?? null
        ]
    ]);
    exit;
}

// 状态 2 = 已确认
if ($qrcode['status'] == 2) {
    $db->query("UPDATE login_qrcodes SET status = 3 WHERE id = " . $qrcode['id']);
    
    // ========== 情况一：本分站用户确认 ==========
    if ($qrcode['confirm_user_id'] > 0) {
        $_SESSION['user_id'] = $qrcode['confirm_user_id'];
        
        $user = $db->fetchOne("SELECT username, role FROM users WHERE id = " . $qrcode['confirm_user_id']);
        if ($user) {
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
        }
        
        echo json_encode([
            'code' => 0, 
            'status' => 'confirmed',
            'msg' => 'PC端已登录手机账号',
            'redirect' => SITE_URL . 'admin.php'
        ]);
        exit;
    }
    
    // ========== 情况二：跨站 App 用户确认 ==========
    if (!empty($qrcode['site_id']) && $qrcode['app_user_id'] > 0) {
        // 向总站请求用户信息
        $ch = curl_init();
        $master_url = 'https://auth.lhwks.cn';
        curl_setopt($ch, CURLOPT_URL, $master_url . '/api/get_confirm_user.php?token=' . $token . '&site_id=' . SITE_ID);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $userData = json_decode($response, true);
        
        if ($userData['code'] === 0 && !empty($userData['user'])) {
            $remoteUser = $userData['user'];
            
            // 在分站查找或创建本地用户
            $localUser = $db->fetchOne("SELECT * FROM users WHERE union_id = '{$remoteUser['id']}' AND union_type = 'app'");
            
            if (!$localUser) {
                $username = 'app_' . $remoteUser['id'];
                $password = password_hash(uniqid(), PASSWORD_DEFAULT);
                $email = $remoteUser['id'] . '@app.local';
                $db->query("INSERT INTO users (username, email, password, union_id, union_type, role, status) VALUES ('$username', '$email', '$password', '{$remoteUser['id']}', 'app', 'user', 1)");
                $user_id = $db->insertId();
            } else {
                $user_id = $localUser['id'];
            }
            
            $db->query("UPDATE login_qrcodes SET confirm_user_id = $user_id WHERE id = " . $qrcode['id']);
            
            $_SESSION['user_id'] = $user_id;
            
            echo json_encode([
                'code' => 0,
                'status' => 'confirmed',
                'redirect' => SITE_URL . 'admin.php'
            ]);
            exit;
        }
    }
    
    // ========== 情况三：手机端未登录，PC 端已登录用户生成二维码 ==========
    echo json_encode([
        'code' => 0, 
        'status' => 'confirmed',
        'msg' => '手机端已成功登录'
    ]);
    exit;
}

// 状态 0 = 待扫描
echo json_encode(['code' => 0, 'status' => 'pending']);
exit;