<?php
/**
 * 授权客户端类 - 用于与主站授权服务器通信
 */
class LicenseClient {
    private $api_base = 'https://38.76.165.134/api/license/';  // 改为 IP 直连
    private $api_host = 'auth.lhwks.cn';                     // 原始域名用于 Host 头
    private $site_id;
    private $license_key;
    private $app_key;

    public function __construct() {
        // 优先从常量读取（安装时生成的 config.php 中已定义）
        if (defined('SITE_ID') && defined('LICENSE_KEY')) {
            $this->site_id = SITE_ID;
            $this->license_key = LICENSE_KEY;
        } else {
            // 兼容旧版独立授权文件
            $license_file = __DIR__ . '/../config/license.php';
            if (file_exists($license_file)) {
                $config = include $license_file;
                $this->site_id = $config['site_id'] ?? '';
                $this->license_key = $config['license_key'] ?? '';
            }
        }
        
        if (empty($this->site_id) || empty($this->license_key)) {
            throw new Exception('授权信息不存在，请重新安装');
        }
        
        $this->app_key = defined('APP_KEY') ? APP_KEY : '';
    }

    /**
     * 获取当前站点版本号
     */
    public function getCurrentVersion() {
        $version_file = __DIR__ . '/../version.php';
        if (file_exists($version_file)) {
            $version = include $version_file;
            return $version['version'] ?? '1.0.0';
        }
        return defined('SYS_VERSION') ? SYS_VERSION : '1.0.0';
    }

    /**
     * 发送 POST 请求到主站 API
     */
    private function request($endpoint, $data = []) {
        $url = $this->api_base . $endpoint;
        $data['site_id'] = $this->site_id;
        $data['license_key'] = $this->license_key;
        if (!empty($this->app_key)) {
            $data['app_key'] = $this->app_key;
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Host: ' . $this->api_host    // 添加 Host 头
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   // 关闭 SSL 验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);   // 关闭 SSL 主机验证

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error) {
            throw new Exception('网络请求失败: ' . $error);
        }

        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('API 响应格式错误');
        }

        // 兼容主站 API 返回格式 {code, message, data}
        if (isset($result['code']) && $result['code'] !== 200) {
            throw new Exception($result['message'] ?? '未知错误');
        }

        return $result['data'] ?? $result;
    }

    /**
     * 获取系统公告
     */
    public function getAnnouncements($current_version = null) {
        if ($current_version === null) {
            $current_version = $this->getCurrentVersion();
        }
        $data = $this->request('get_announcements.php', [
            'current_version' => $current_version
        ]);
        return $data['announcements'] ?? [];
    }

    /**
     * 检查更新
     */
    public function checkUpdate($current_version = null) {
        // 如果配置了禁用更新，直接返回无更新
        if (defined('DISABLE_UPDATE_CHECK') && DISABLE_UPDATE_CHECK === true) {
            return [
                'has_update' => false,
                'message' => '更新检查已禁用',
                'current_version' => $this->getCurrentVersion()
            ];
        }
        
        if ($current_version === null) {
            $current_version = $this->getCurrentVersion();
        }
        return $this->request('check_update.php', [
            'current_version' => $current_version
        ]);
    }

    /**
     * 上报更新状态
     */
    public function reportUpdate($from_version, $to_version, $status = 'success') {
        return $this->request('report_update.php', [
            'from_version' => $from_version,
            'to_version'   => $to_version,
            'status'       => $status
        ]);
    }

    /**
     * 下载更新包
     */
    public function downloadUpdate($url, $save_path) {
        $ch = curl_init($url);
        $fp = fopen($save_path, 'w+');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   // 关闭 SSL 验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);   // 关闭 SSL 主机验证
        
        // 如果下载地址是主站域名，添加 Host 头
        if (strpos($url, '159.75.95.13') !== false || strpos($url, 'auth.lhwks.top') !== false) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Host: ' . $this->api_host]);
        }
        
        $success = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        fclose($fp);
        
        if (!$success || $httpCode !== 200) {
            return false;
        }
        return filesize($save_path) > 0;
    }

    /**
     * 检查站点状态
     * @return int 1=正常，0=禁用
     * @throws Exception
     */
    public function checkStatus() {
        $data = $this->request('check_status.php');
        return $data['status'] ?? 1;
    }
}