<?php
/**
 * 授权API集成文件
 * 用于调用官方授权验证、实时更新、续费等API
 */

// 防止直接访问
if (!defined('ROOT')) {
    die('Access denied');
}

/**
 * 授权站基础地址
 */
define('AUTH_BASE_URL', 'https://sqz.dadxb.cn/api');

/**
 * 验证授权API
 * 调用授权站验证授权状态
 * 
 * @return array API返回结果
 */
function verify_auth_status() {
    // 获取授权配置
    $auth_config = include(ROOT . 'includes/Auth.php');
    $authcode = $auth_config['authcode'] ?? '';
    $domain = $_SERVER['HTTP_HOST'] ?? '';
    
    if (empty($authcode)) {
        return [
            'code' => -1,
            'msg' => '未配置授权码，请在Auth.php中设置authcode'
        ];
    }
    
    // 构建请求参数
    $params = [
        'card_key' => $authcode,
        'domain' => $domain
    ];
    
    // 发起POST请求
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => AUTH_BASE_URL . '/verify.php',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($params),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return [
            'code' => -1,
            'msg' => '授权服务器连接失败: ' . $error
        ];
    }
    
    if ($httpCode != 200) {
        return [
            'code' => -1,
            'msg' => '授权服务器返回错误: HTTP ' . $httpCode
        ];
    }
    
    $data = json_decode($response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'code' => -1,
            'msg' => '授权服务器返回数据解析失败'
        ];
    }
    
    // 解析授权结果
    if (isset($data['success']) && $data['success'] && isset($data['data']['is_valid']) && $data['data']['is_valid']) {
        $result = [
            'code' => 1,
            'msg' => $data['message'] ?? '授权有效',
            'data' => [
                'card_key' => $data['data']['card_key'] ?? '',
                'domain' => $data['data']['domain'] ?? '',
                'expire_time' => $data['data']['expire_time'] ?? '',
                'days_left' => $data['data']['days_left'] ?? 0,
                'bind_time' => $data['data']['bind_time'] ?? ''
            ]
        ];
    } else {
        $result = [
            'code' => -1,
            'msg' => $data['message'] ?? '授权无效或已过期',
            'data' => $data['data'] ?? []
        ];
    }
    
    return $result;
}

/**
 * 实时更新API
 * 调用授权站API检测是否有新版本
 * 
 * @param string $current_version 当前版本号
 * @return array API返回结果
 */
function check_update_api($current_version = '') {
    // 获取当前版本
    if (empty($current_version)) {
        $auth_config = include(ROOT . 'includes/Auth.php');
        $current_version = $auth_config['app_version'] ?? '1.0';
    }
    
    // 构建请求URL
    $url = AUTH_BASE_URL . '/check-update.php?current_version=' . urlencode($current_version);
    
    // 发起请求
    $response = auth_curl_request($url);
    
    if ($response === false) {
        return [
            'code' => -1,
            'msg' => 'API请求失败，请检查网络连接'
        ];
    }
    
    $data = json_decode($response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'code' => -1,
            'msg' => 'API返回数据解析失败'
        ];
    }
    
    // 转换API返回格式为系统统一格式
    if (isset($data['success']) && $data['success']) {
        $latest_version = $data['data']['latest_version'] ?? '1.0';
        $has_update = $data['data']['has_update'] ?? false;
        $changelog = $data['data']['changelog'] ?? '';
        $download_url = $data['data']['download_url'] ?? '';
        $name = $data['data']['name'] ?? '小荠菜网页登录系统';
        
        // 构建版本列表
        $version_list = [];
        
        // 如果有更新，先添加最新版本
        if ($has_update) {
            $version_list[] = [
                'version' => $latest_version,
                'add_time' => date('Y-m-d'),
                'content' => $changelog
            ];
        }
        
        // 添加当前版本信息
        $version_list[] = [
            'version' => $current_version,
            'add_time' => date('Y-m-d'),
            'content' => '当前版本'
        ];
        
        // 检查是否有更新
        if (!$has_update) {
            return [
                'code' => 1,
                'msg' => '当前版本已经是最新版，无需更新',
                'data' => [
                    'has_update' => false,
                    'version' => $current_version,
                    'appname' => $name,
                    'content' => $changelog,
                    'download_url' => '',
                    'date' => date('Y-m-d'),
                    'version_list' => $version_list
                ]
            ];
        }
        
        return [
            'code' => 1,
            'msg' => $data['message'] ?? '检测到新版本',
            'data' => [
                'has_update' => true,
                'version' => $latest_version,
                'appname' => $name,
                'content' => $changelog,
                'download_url' => $download_url,
                'date' => date('Y-m-d'),
                'version_list' => $version_list
            ]
        ];
    } else {
        return [
            'code' => -1,
            'msg' => $data['message'] ?? '实时更新失败'
        ];
    }
}

/**
 * 获取版本列表API
 * 从授权站获取各版本的更新日志
 * 
 * @return array API返回结果
 */
function get_version_list_api() {
    // 获取当前版本
    $auth_config = include(ROOT . 'includes/Auth.php');
    $current_version = $auth_config['app_version'] ?? '1.0';
    
    // 调用实时更新API获取版本信息
    $url = AUTH_BASE_URL . '/check-update.php?current_version=' . urlencode($current_version);
    
    $response = auth_curl_request($url);
    
    if ($response !== false) {
        $data = json_decode($response, true);
        if (isset($data['success']) && $data['success'] && isset($data['data'])) {
            $changelog = $data['data']['changelog'] ?? '';
            $latest_version = $data['data']['latest_version'] ?? $current_version;
            $has_update = $data['data']['has_update'] ?? false;
            
            // 构建版本列表
            $version_list = [];
            
            // 如果有更新，先添加最新版本
            if ($has_update) {
                $version_list[] = [
                    'version' => $latest_version,
                    'add_time' => date('Y-m-d'),
                    'content' => $changelog
                ];
            }
            
            // 添加当前版本
            $version_list[] = [
                'version' => $current_version,
                'add_time' => date('Y-m-d'),
                'content' => $changelog ?: '当前版本'
            ];
            
            return [
                'code' => 1,
                'msg' => '获取成功',
                'data' => $version_list
            ];
        }
    }
    
    // 如果API不可用，返回模拟数据
    return [
        'code' => 1,
        'msg' => '获取成功',
        'data' => [
            [
                'version' => $current_version,
                'add_time' => date('Y-m-d'),
                'content' => "当前版本 V{$current_version}"
            ]
        ]
    ];
}

/**
 * CURL请求函数
 * 
 * @param string $url 请求URL
 * @param int $timeout 超时时间
 * @return string|false 响应内容
 */
function auth_curl_request($url, $timeout = 30) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 3,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($httpCode != 200 || $error) {
        return false;
    }
    
    return $response;
}

/**
 * 执行在线更新
 * 从授权站下载更新包并应用
 * 
 * @return array 更新结果
 */
function do_update_api() {
    // 获取当前版本
    $auth_config = include(ROOT . 'includes/Auth.php');
    $current_version = $auth_config['app_version'] ?? '1.0';
    
    // 调用授权站实时更新API，获取下载地址
    $url = AUTH_BASE_URL . '/check-update.php?current_version=' . urlencode($current_version);
    $response = auth_curl_request($url);
    
    if ($response === false) {
        return [
            'code' => -1,
            'msg' => '连接授权服务器失败，请检查网络'
        ];
    }
    
    $data = json_decode($response, true);
    
    if (!isset($data['success']) || !$data['success']) {
        return [
            'code' => -1,
            'msg' => $data['message'] ?? '获取版本信息失败'
        ];
    }
    
    $download_url = $data['data']['download_url'] ?? '';
    $latest_version = $data['data']['latest_version'] ?? '';
    
    // 检查是否有更新
    if (empty($download_url)) {
        return [
            'code' => -1,
            'msg' => '暂无可用的更新包，请联系作者获取最新版本'
        ];
    }
    
    // 检查版本，如果当前版本 >= 最新版本，提示无需更新
    if (version_compare($current_version, $latest_version, '>=')) {
        return [
            'code' => -1,
            'msg' => '当前已是最新版本，无需更新'
        ];
    }
    
    // 下载更新包
    $temp_file = ROOT . 'cache/update_' . time() . '.zip';
    $cache_dir = dirname($temp_file);
    if (!is_dir($cache_dir)) {
        mkdir($cache_dir, 0755, true);
    }
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $download_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 300,
        CURLOPT_CONNECTTIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]);
    
    $zip_content = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($httpCode != 200 || empty($zip_content) || $error) {
        return [
            'code' => -1,
            'msg' => '下载更新包失败: ' . ($error ?: 'HTTP ' . $httpCode)
        ];
    }
    
    // 保存更新包
    if (file_put_contents($temp_file, $zip_content) === false) {
        return [
            'code' => -1,
            'msg' => '保存更新包失败'
        ];
    }
    
    // 解压更新包
    $zip = new ZipArchive();
    if ($zip->open($temp_file) !== true) {
        unlink($temp_file);
        return [
            'code' => -1,
            'msg' => '打开更新包失败，可能是损坏的压缩包'
        ];
    }
    
    // 解压到临时目录
    $extract_dir = ROOT . 'cache/update_extract_' . time() . '/';
    if (!is_dir($extract_dir)) {
        mkdir($extract_dir, 0755, true);
    }
    
    $zip->extractTo($extract_dir);
    $zip->close();
    
    // 查找解压后的实际目录（可能有一层根目录）
    $source_dir = $extract_dir;
    $items = scandir($extract_dir);
    foreach ($items as $item) {
        if ($item != '.' && $item != '..' && is_dir($extract_dir . $item)) {
            // 检查是否包含 includes 或 admin 目录
            if (is_dir($extract_dir . $item . '/includes') || is_dir($extract_dir . $item . '/admin')) {
                $source_dir = $extract_dir . $item . '/';
                break;
            }
        }
    }
    
    // 应用更新 - 复制文件
    $updated_files = [];
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($source_dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $item) {
        if ($item->isDir()) {
            continue;
        }
        
        $relative_path = str_replace($source_dir, '', $item->getPathname());
        $relative_path = ltrim($relative_path, '/\\');
        $dest_path = ROOT . $relative_path;
        
        // 创建目标目录
        $dest_dir = dirname($dest_path);
        if (!is_dir($dest_dir)) {
            mkdir($dest_dir, 0755, true);
        }
        
        // 复制文件
        if (copy($item->getPathname(), $dest_path)) {
            $updated_files[] = $relative_path;
        }
    }
    
    // 清理临时文件
    unlink($temp_file);
    
    // 递归删除临时目录
    $delete_dir = function($dir) use (&$delete_dir) {
        if (is_dir($dir)) {
            $items = scandir($dir);
            foreach ($items as $item) {
                if ($item != '.' && $item != '..') {
                    $path = $dir . '/' . $item;
                    is_dir($path) ? $delete_dir($path) : unlink($path);
                }
            }
            rmdir($dir);
        }
    };
    $delete_dir($extract_dir);
    
    if (empty($updated_files)) {
        return [
            'code' => -1,
            'msg' => '更新包中没有找到可更新的文件'
        ];
    }
    
    return [
        'code' => 1,
        'msg' => '更新成功！共更新 ' . count($updated_files) . ' 个文件，版本已更新至 V' . $latest_version,
        'updated_files' => $updated_files,
        'new_version' => $latest_version
    ];
}
