<?php
/**
 * BarjuCMS 公共函数库 - 授权相关
 * 包含：域名清理、API签名生成、授权校验、版本检测
 */

// 清理域名：去除 http/https、www、端口、斜杠，统一小写
function cleanDomain($domain) {
    $domain = strtolower(trim($domain));
    $domain = preg_replace('/^https?:\/\//', '', $domain);
    $domain = preg_replace('/^www\./', '', $domain);
    $domain = preg_replace('/:\d+$/', '', $domain);
    $domain = rtrim($domain, '/');
    return $domain;
}

// 生成 API 签名
function generateApiSignature($domain, $timestamp, $action = 'check') {
    $secretKey = 'BarjuCMS_Api_Secret_Key_2026';
    return md5($domain . $timestamp . $secretKey . $action);
}

// 校验 API 请求（时间戳+签名）
function validateApiRequest($domain, $timestamp, $signature, $action = 'check') {
    $currentTime = time();
    
    // 时间戳验证（±5分钟）
    if (!$timestamp || abs($currentTime - $timestamp) > 300) {
        return ['success' => false, 'message' => '请求已过期'];
    }
    
    // 签名验证
    $expectedSignature = generateApiSignature($domain, $timestamp, $action);
    if (!$signature || $signature !== $expectedSignature) {
        return ['success' => false, 'message' => '签名验证失败'];
    }
    
    return ['success' => true];
}

// 调用主站 API 校验授权
function checkLicenseFromServer($domain) {
    $apiUrl = 'https://www.barju.cn/api/license_check.php';
    $timestamp = time();
    $signature = generateApiSignature($domain, $timestamp);
    
    $url = $apiUrl . '?domain=' . urlencode($domain) . '&timestamp=' . $timestamp . '&signature=' . $signature;
    
    $response = @file_get_contents($url);
    if ($response === false) {
        return ['success' => false, 'message' => '无法连接授权服务器'];
    }
    
    $data = json_decode($response, true);
    return $data ?: ['success' => false, 'message' => '授权服务器返回数据格式错误'];
}

// 调用主站 API 申请授权
function applyLicense($domain) {
    $apiUrl = 'https://www.barju.cn/api/license_apply.php';
    $timestamp = time();
    $signature = generateApiSignature($domain, $timestamp, 'apply');
    
    $postData = json_encode([
        'domain' => $domain,
        'timestamp' => $timestamp,
        'signature' => $signature
    ]);
    
    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/json',
            'content' => $postData,
            'timeout' => 30
        ]
    ]);
    
    $response = @file_get_contents($apiUrl, false, $context);
    if ($response === false) {
        return ['success' => false, 'message' => '无法连接授权服务器'];
    }
    
    $data = json_decode($response, true);
    return $data ?: ['success' => false, 'message' => '授权服务器返回数据格式错误'];
}

// 调用主站 API 检测版本
function checkVersionFromServer($domain, $currentVersion) {
    $apiUrl = 'https://www.barju.cn/api/version_check.php';
    $timestamp = time();
    $signature = generateApiSignature($domain, $timestamp, 'check');
    
    $url = $apiUrl . '?domain=' . urlencode($domain) . '&timestamp=' . $timestamp . '&signature=' . $signature . '&action=check&current_version=' . urlencode($currentVersion);
    
    $response = @file_get_contents($url);
    if ($response === false) {
        return ['success' => false, 'message' => '无法连接更新服务器'];
    }
    
    $data = json_decode($response, true);
    return $data ?: ['success' => false, 'message' => '更新服务器返回数据格式错误'];
}
