<?php
// 允许跨域请求
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

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

$license_code = isset($_POST['license_code']) ? trim($_POST['license_code']) : '';
$domain = isset($_POST['domain']) ? trim($_POST['domain']) : '';
$app_key = isset($_POST['app_key']) ? trim($_POST['app_key']) : '';

if (empty($license_code)) {
    echo json_encode(['code' => 400, 'message' => '授权码不能为空', 'data' => null]);
    exit;
}

if (empty($domain)) {
    echo json_encode(['code' => 400, 'message' => '域名不能为空', 'data' => null]);
    exit;
}

if (empty($app_key)) {
    echo json_encode(['code' => 400, 'message' => '应用标识不能为空', 'data' => null]);
    exit;
}

$license = $db->fetchOne("
    SELECT l.*, a.name as app_name, a.app_key as expected_app_key
    FROM licenses l 
    JOIN apps a ON l.app_id = a.id 
    WHERE l.license_code = '$license_code'
");

if (!$license) {
    echo json_encode(['code' => 404, 'message' => '授权码不存在', 'data' => null]);
    exit;
}

// 验证应用标识是否匹配
if ($license['expected_app_key'] !== $app_key) {
    echo json_encode(['code' => 403, 'message' => '应用标识不匹配', 'data' => null]);
    exit;
}

if ($license['status'] != 1) {
    echo json_encode(['code' => 403, 'message' => '授权码已被禁用', 'data' => null]);
    exit;
}

if ($license['expire_date'] !== null && $license['expire_date'] < date('Y-m-d')) {
    echo json_encode(['code' => 403, 'message' => '授权已过期', 'data' => null]);
    exit;
}

// 检查授权码是否已被使用
if ($license['used'] == 1) {
    echo json_encode(['code' => 403, 'message' => '授权码已被使用', 'data' => null]);
    exit;
}

if (empty($license['domain'])) {
    // 首次使用，绑定域名并标记为已使用
    $db->query("UPDATE licenses SET domain = '$domain', used = 1, used_at = NOW(), used_domain = '$domain' WHERE id = {$license['id']}");
} elseif ($license['domain'] != $domain) {
    echo json_encode(['code' => 403, 'message' => '授权域名不匹配', 'data' => null]);
    exit;
}

echo json_encode([
    'code' => 200,
    'message' => '授权有效',
    'data' => [
        'app_name' => $license['app_name'],
        'expire_date' => $license['expire_date'],
        'is_permanent' => $license['expire_date'] === null
    ]
]);
?>