<?php
/**
 * 客户站 API - 执行更新
 * 访问地址: /api/do_update.php
 * 请求方式: POST
 * 参数: version, download_url
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/LicenseClient.php';

// 权限检查：仅管理员可执行
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;
}

header('Content-Type: application/json');
set_time_limit(300);

$input = json_decode(file_get_contents('php://input'), true);
if (!$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. 解压
    $zip = new ZipArchive();
    if ($zip->open($temp_file) !== true) {
        throw new Exception('无法打开更新包');
    }
    
    $root_path = realpath(__DIR__ . '/../');
    if (!$zip->extractTo($root_path)) {
        $zip->close();
        throw new Exception('解压失败，请检查目录权限');
    }
    $zip->close();
    unlink($temp_file);
    
    // 3. 执行数据库迁移
    $sql_file = $root_path . '/update.sql';
    if (file_exists($sql_file)) {
        $sql = file_get_contents($sql_file);
        $db->query($sql);
        unlink($sql_file);
    }
    
    // 4. 更新版本号
    $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);
    
    // 5. 上报主站
    $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;