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

$token = $_GET['token'] ?? '';
$request = $db->fetchOne("SELECT * FROM pc_login_requests WHERE token = '$token'");

if (!$request) {
    echo json_encode(['status' => 'invalid']);
    exit;
}

if (strtotime($request['expire_at']) < time()) {
    echo json_encode(['status' => 'expired']);
    exit;
}

if ($request['status'] == 1) {
    // 确认成功，自动登录
    $_SESSION['user_id'] = $request['user_id'];
    
    // 记住登录状态
    $session_token = bin2hex(random_bytes(32));
    setcookie('pc_login_token', $session_token, time() + 2592000, '/');
    
    // 保存设备记录
    $db->query("INSERT INTO pc_login_sessions (user_id, session_token, device_name) VALUES ({$request['user_id']}, '$session_token', '{$request['device_name']}')");
    
    $db->query("UPDATE pc_login_requests SET status = 3 WHERE id = {$request['id']}");
    
    echo json_encode(['status' => 'confirmed', 'redirect' => '/admin.php']);
    exit;
}

if ($request['status'] == 2) {
    echo json_encode(['status' => 'rejected']);
    exit;
}

echo json_encode(['status' => 'waiting']);
exit;