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

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

$user_id = $_SESSION['user_id'];
$token = $_GET['token'] ?? '';

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

// 使用全局 $db 对象
global $db;

$record = $db->fetchOne("SELECT * FROM wechat_bind_tokens WHERE token = '$token'");

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

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

if ($record['status'] == 1 && $record['openid']) {
    // 检查 openid 是否已被其他账号绑定
    $exist = $db->fetchOne("SELECT id FROM users WHERE union_id = '{$record['openid']}' AND union_type = 'wechat'");
    
    if ($exist && $exist['id'] != $user_id) {
        echo json_encode(['status' => 'error', 'msg' => '该微信已绑定其他账号']);
        exit;
    }
    
    // 绑定到当前用户
    $db->query("UPDATE users SET union_id = '{$record['openid']}', union_type = 'wechat' WHERE id = $user_id");
    $db->query("UPDATE wechat_bind_tokens SET status = 2 WHERE id = {$record['id']}");
    
    echo json_encode(['status' => 'success']);
    exit;
}

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