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

$user = currentUser();  // 手机端当前用户（可能是未登录）
$token = $_POST['token'] ?? '';
$action = $_POST['action'] ?? '';

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, 'msg' => '二维码无效']);
    exit;
}

if (strtotime($qrcode['expire_at']) < time()) {
    echo json_encode(['code' => 1, 'msg' => '二维码已过期']);
    exit;
}

// 获取扫码者的用户ID（可能为0，表示未登录）
$scan_user_id = $user ? $user['id'] : 0;

if ($action === 'scan') {
    $db->query("UPDATE login_qrcodes SET status = 1, scan_user_id = $scan_user_id WHERE id = " . $qrcode['id']);
    echo json_encode(['code' => 0, 'msg' => '已扫描']);
    exit;
}

if ($action === 'confirm') {
    $generate_user_id = $qrcode['generate_user_id'] ?? 0;
    $scan_user_id = $user ? $user['id'] : 0;
    
    // 确定最终要登录的账号
    if ($scan_user_id > 0) {
        // 手机端已登录 → 手机端的账号将授权给 PC 端
        $target_user_id = $scan_user_id;
    } elseif ($generate_user_id > 0) {
        // 手机端未登录，PC 端已登录 → 手机端登录 PC 端的账号
        $target_user_id = $generate_user_id;
        
        // 让手机端登录
        $target_user = $db->fetchOne("SELECT * FROM users WHERE id = $generate_user_id");
        if ($target_user) {
            $_SESSION['user_id'] = $target_user['id'];
            $_SESSION['username'] = $target_user['username'];
            $_SESSION['role'] = $target_user['role'];
        }
    } else {
        $target_user_id = 0;
    }
    
    $db->query("UPDATE login_qrcodes SET status = 2, confirm_user_id = $target_user_id WHERE token = '$token'");
    
    echo json_encode(['code' => 0, 'msg' => '确认成功', 'redirect' => SITE_URL . 'm/']);
    exit;
}

echo json_encode(['code' => 1, 'msg' => '无效操作']);
exit;