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

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

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$license_id = intval($_POST['license_id'] ?? 0);
$domain = trim($_POST['domain'] ?? '');

// 验证域名格式
if (!preg_match('/^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/', $domain)) {
    echo json_encode(['success' => false, 'message' => '域名格式不正确']);
    exit;
}

// 验证授权码属于当前用户，并检查是否已被使用
$license = $db->fetchOne("SELECT id, used FROM licenses WHERE id = $license_id AND user_id = $user_id");
if (!$license) {
    echo json_encode(['success' => false, 'message' => '授权码不存在']);
    exit;
}

// 检查授权码是否已被使用
if ($license['used'] == 1) {
    echo json_encode(['success' => false, 'message' => '授权码已被使用，无法绑定']);
    exit;
}

$domain = $db->escape($domain);
// 绑定域名并标记为已使用
$db->query("UPDATE licenses SET domain = '$domain', used = 1, used_at = NOW(), used_domain = '$domain' WHERE id = $license_id");

echo json_encode(['success' => true]);
exit;
?>