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

$user_id = intval($_POST['user_id'] ?? 0);
$device_name = $_POST['device_name'] ?? 'Windows 电脑';

if ($user_id <= 0) {
    echo json_encode(['code' => 1, 'msg' => '用户不存在']);
    exit;
}

// 验证用户存在
$user = $db->fetchOne("SELECT id FROM users WHERE id = $user_id AND status = 1");
if (!$user) {
    echo json_encode(['code' => 1, 'msg' => '用户不存在']);
    exit;
}

$token = bin2hex(random_bytes(32));
$expire = date('Y-m-d H:i:s', strtotime('+5 minutes'));

$db->query("INSERT INTO pc_login_requests (token, user_id, device_name, expire_at) VALUES ('$token', $user_id, '$device_name', '$expire')");

echo json_encode([
    'code' => 0,
    'token' => $token
]);
exit;