<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/functions.php';

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

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

// 检查权限
$user = currentUser();
if ($user['role'] !== 'admin' && $user['role'] !== 'employee') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

// 获取参数
$license_id = intval($_POST['license_id'] ?? 0);
$domain = trim($_POST['domain'] ?? '');

if ($license_id <= 0) {
    echo json_encode(['success' => false, 'message' => '授权ID无效']);
    exit;
}

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 used FROM licenses WHERE id = $license_id");
if ($license && $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, 'message' => '域名绑定成功']);
exit;