<?php
/**
 * 客户站 API - 执行更新
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/LicenseClient.php';

// ========== 强制关闭所有错误输出 ==========
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// ========== 权限检查 ==========
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$db = Database::getInstance();
$user = $db->fetchOne("SELECT role FROM users WHERE id = " . intval($_SESSION['user_id']));
if (!$user || $user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

// ========== 获取参数 ==========
$raw_input = file_get_contents('php://input');
$input = json_decode($raw_input, true);
if (json_last_error() !== JSON_ERROR_NONE || empty($input)) {
    $input = $_POST;
}

$to_version = trim($input['version'] ?? '');
$download_url = trim($input['download_url'] ?? '');

if (empty($to_version) || empty($download_url)) {
    echo json_encode(['success' => false, 'message' => '参数不完整']);
    exit;
}

// ========== 执行更新 ==========
try {
    $client = new LicenseClient();
    $from_version = $client->getCurrentVersion();
    
    // 1. 下载更新包
    $temp_file = sys_get_temp_dir() . '/update_' . uniqid() . '.zip';
    if (!$client->downloadUpdate($download_url, $temp_file)) {
        throw new Exception('下载更新包失败，请检查下载地址');
    }
    
    // 2. 检查 ZipArchive
    if (!class_exists('ZipArchive')) {
        throw new Exception('服务器未安装 ZipArchive 扩展');
    }
    
    $zip = new ZipArchive();
    if ($zip->open($temp_file) !== true) {
        throw new Exception('无法打开更新包');
    }
    
    $root_path = realpath(__DIR__ . '/../');
    
    // 3. 逐个解压，跳过受保护文件
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $target = $root_path . '/' . $filename;
        // 跳过敏感文件（仅根目录）
$basename = basename($filename);
$is_root = (dirname($filename) === '.');  // 判断是否为根目录

// 仅跳过根目录下的敏感文件
if ($is_root && in_array($basename, ['.user.ini', 'config.php', 'install.lock', 'version.php', '.htaccess'])) {
    continue;
}
        
        // 创建目录
        if (substr($filename, -1) === '/') {
            if (!is_dir($target)) {
                mkdir($target, 0755, true);
            }
            continue;
        }
        
        // 确保父目录存在
        $parent = dirname($target);
        if (!is_dir($parent)) {
            mkdir($parent, 0755, true);
        }
        
        // 写入文件
        $content = $zip->getFromIndex($i);
        if ($content !== false) {
            file_put_contents($target, $content);
        }
    }
    $zip->close();
    unlink($temp_file);
    
    // 4. 执行数据库迁移
    $sql_file = $root_path . '/update.sql';
    if (file_exists($sql_file)) {
        $sql = file_get_contents($sql_file);
        $db->query($sql);
        unlink($sql_file);
    }
    
    // 5. 更新版本号
    $version_file = $root_path . '/version.php';
    $version_content = "<?php\nreturn ['version' => '{$to_version}', 'updated_at' => '" . date('Y-m-d H:i:s') . "'];\n";
    file_put_contents($version_file, $version_content);
    
    // 6. 上报主站
    $client->reportUpdate($from_version, $to_version, 'success');
    
    echo json_encode(['success' => true, 'message' => '更新成功！']);
    
} catch (Exception $e) {
    if (isset($client) && isset($from_version)) {
        try {
            $client->reportUpdate($from_version, $to_version, 'failed');
        } catch (Exception $ignored) {}
    }
    
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
exit;