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

if (!isLoggedIn()) {
    echo json_encode(['code' => 1, 'msg' => '请先登录']);
    exit;
}

$code = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
$token = md5(uniqid(rand(), true));
$expire_at = date('Y-m-d H:i:s', time() + 300);

// 使用全局 $db 对象
global $db;
$db->query("INSERT INTO wechat_bind_tokens (token, code, expire_at) VALUES ('$token', '$code', '$expire_at')");

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