<?php
require_once dirname(__DIR__) . '/config.php';

header('Content-Type: application/json');

$code = trim($_POST['code'] ?? '');

if (empty($code)) {
    echo json_encode(['success' => false, 'message' => '请输入验证码']);
    exit;
}

// 查询验证码（type=wechat）
$record = $db->fetchOne("SELECT * FROM email_verify_codes 
                         WHERE code = '$code' 
                         AND type = 'wechat' 
                         AND used = 0 
                         AND expired_at > NOW()");

if (!$record) {
    echo json_encode(['success' => false, 'message' => '验证码错误或已过期']);
    exit;
}

// 标记为已使用
$db->query("UPDATE email_verify_codes SET used = 1 WHERE id = {$record['id']}");

$wechat_openid = $record['email'];

// 查询或创建用户
$user = $db->fetchOne("SELECT * FROM users WHERE wechat_openid = '$wechat_openid'");

if (!$user) {
    // 创建新用户
    $username = 'wx_' . substr($wechat_openid, -8);
    $hashed_password = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);
    
    // 确保用户名唯一
    $counter = 1;
    $original_username = $username;
    while ($db->fetchOne("SELECT id FROM users WHERE username = '$username'")) {
        $username = $original_username . $counter;
        $counter++;
    }
    
    $db->query("INSERT INTO users (username, password, wechat_openid, email_verified, role) 
                VALUES ('$username', '$hashed_password', '$wechat_openid', 1, 'user')");
    $user_id = $db->insertId();
    $username = $username;
} else {
    $user_id = $user['id'];
    $username = $user['username'];
}

// 登录
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['role'] = $user['role'] ?? 'user';

echo json_encode(['success' => true, 'message' => '登录成功']);