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

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

$record = $db->fetchOne("SELECT * FROM wechat_login_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) {
    $openid = $record['openid'];
    
    if (!$openid) {
        echo json_encode(['status' => 'waiting']);
        exit;
    }
    
    $user = $db->fetchOne("SELECT * FROM users WHERE union_id = '$openid' AND union_type = 'wechat'");
    
    if (!$user) {
        $username = 'wx_' . substr($openid, -8);
        $password = password_hash(uniqid(), PASSWORD_DEFAULT);
        $email = $openid . '@wechat.local';
        $db->query("INSERT INTO users (username, email, password, union_id, union_type, role, status) VALUES ('$username', '$email', '$password', '$openid', 'wechat', 'user', 1)");
        $user_id = $db->insertId();
    } else {
        $user_id = $user['id'];
    }
    
    $_SESSION['user_id'] = $user_id;
    $db->query("UPDATE wechat_login_tokens SET status = 2 WHERE id = {$record['id']}");
    
    echo json_encode(['status' => 'success', 'redirect' => '/admin.php']);
    exit;
}

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