<?php
/**
 * 在线升级处理程序
 * 使用UpgradeManager进行分步骤升级
 */

// 开启错误显示用于调试
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    require_once __DIR__ . '/../MPHX/common.php';
    require_once __DIR__ . '/../MPHX/UpgradeManager.php';
} catch (Exception $e) {
    header('Content-Type: application/json; charset=UTF-8');
    exit(json_encode(['code' => 500, 'message' => '加载失败: ' . $e->getMessage()]));
}

header('Content-Type: application/json; charset=UTF-8');

$action = isset($_POST['action']) ? $_POST['action'] : '';
$download_url = isset($_POST['download_url']) ? $_POST['download_url'] : '';
$is_repair = isset($_POST['repair']) && $_POST['repair'] == 1;

// 检查登录状态
$admin_user = is_admin_login();
if (!$admin_user) {
    exit(json_encode(array('code' => 401, 'message' => '请先登录')));
}

// 初始化UpgradeManager
try {
    $upgradeManager = new UpgradeManager(ROOT, $DB);
} catch(Exception $e) {
    exit(json_encode(array('code' => 500, 'message' => '初始化升级管理器失败: ' . $e->getMessage())));
}

switch($action) {
    case 'backup':
        // 步骤1: 创建备份
        logjl($admin_user, $is_repair ? '系统修复' : '系统更新', '开始' . ($is_repair ? '系统修复' : '系统更新') . ' - 创建备份', true);
        
        try {
            $backupDir = $upgradeManager->createBackup();
            
            // 保存备份目录到session
            $_SESSION['upgrade_backup_dir'] = $backupDir;
            
            $log = $upgradeManager->getLog();
            exit(json_encode(array(
                'code' => 200, 
                'message' => '备份创建成功',
                'next_step' => 'download',
                'backup_dir' => basename($backupDir),
                'log' => $log
            )));
        } catch(Exception $e) {
            exit(json_encode(array('code' => 500, 'message' => '备份失败: ' . $e->getMessage())));
        }
        break;
        
    case 'download':
        // 步骤2: 下载更新包
        if(empty($download_url)) {
            exit(json_encode(array('code' => 400, 'message' => '下载地址不能为空')));
        }
        
        logjl($admin_user, $is_repair ? '系统修复' : '系统更新', '下载更新包', true);
        
        try {
            $extractDir = $upgradeManager->downloadUpdate($download_url);
            
            // 保存解压目录到session
            $_SESSION['upgrade_extract_dir'] = $extractDir;
            
            $log = $upgradeManager->getLog();
            exit(json_encode(array(
                'code' => 200, 
                'message' => '下载成功',
                'next_step' => 'database',
                'log' => $log
            )));
        } catch(Exception $e) {
            exit(json_encode(array('code' => 500, 'message' => '下载失败: ' . $e->getMessage())));
        }
        break;
        
    case 'database':
        // 步骤3: 更新数据库
        $extractDir = isset($_SESSION['upgrade_extract_dir']) ? $_SESSION['upgrade_extract_dir'] : '';
        if(empty($extractDir) || !is_dir($extractDir)) {
            exit(json_encode(array('code' => 500, 'message' => '更新包目录不存在，请重新开始')));
        }
        
        logjl($admin_user, $is_repair ? '系统修复' : '系统更新', '更新数据库', true);
        
        try {
            $upgradeManager->updateDatabase($extractDir);
            
            $log = $upgradeManager->getLog();
            exit(json_encode(array(
                'code' => 200, 
                'message' => '数据库更新成功',
                'next_step' => 'files',
                'log' => $log
            )));
        } catch(Exception $e) {
            exit(json_encode(array('code' => 500, 'message' => '数据库更新失败: ' . $e->getMessage())));
        }
        break;
        
    case 'files':
        // 步骤4: 更新文件
        $extractDir = isset($_SESSION['upgrade_extract_dir']) ? $_SESSION['upgrade_extract_dir'] : '';
        if(empty($extractDir) || !is_dir($extractDir)) {
            exit(json_encode(array('code' => 500, 'message' => '更新包目录不存在，请重新开始')));
        }
        
        logjl($admin_user, $is_repair ? '系统修复' : '系统更新', '更新文件', true);
        
        try {
            // 获取后台目录配置
            $admin_dir = isset($conf['admin_dir']) ? $conf['admin_dir'] : 'admin';
            
            // 调试信息
            $debugInfo = "extractDir: " . $extractDir . "\n";
            $debugInfo .= "extractDir exists: " . (is_dir($extractDir) ? 'yes' : 'no') . "\n";
            $debugInfo .= "extractDir contents: " . implode(', ', array_slice(scandir($extractDir), 0, 10)) . "\n";
            $debugInfo .= "admin exists: " . (is_dir($extractDir . '/admin') ? 'yes' : 'no') . "\n";
            $debugInfo .= "MPHX exists: " . (is_dir($extractDir . '/MPHX') ? 'yes' : 'no') . "\n";
            
            // 查找files目录
            $filesDir = $extractDir . '/files';
            $debugInfo .= "filesDir: " . $filesDir . "\n";
            $debugInfo .= "filesDir exists: " . (is_dir($filesDir) ? 'yes' : 'no') . "\n";
            
            if(!is_dir($filesDir)) {
                // 检查是否在子目录中（如upgrade_v1.0.2/files）
                $subDirs = glob($extractDir . '/*', GLOB_ONLYDIR);
                $debugInfo .= "subDirs found: " . count($subDirs) . "\n";
                foreach($subDirs as $subDir) {
                    $debugInfo .= "  checking: " . $subDir . "/files\n";
                    if(is_dir($subDir . '/files')) {
                        $filesDir = $subDir . '/files';
                        $debugInfo .= "  found filesDir in subdir\n";
                        break;
                    }
                }
            }
            
            // 如果找不到files目录，直接使用解压目录（适配直接打包根目录的情况）
            if(!is_dir($filesDir)) {
                // 检查解压目录中是否包含项目文件（如admin、MPHX等）
                $adminExists = is_dir($extractDir . '/admin');
                $mphxExists = is_dir($extractDir . '/MPHX');
                $debugInfo .= "Final check - admin: " . ($adminExists ? 'yes' : 'no') . ", MPHX: " . ($mphxExists ? 'yes' : 'no') . "\n";
                
                if($adminExists || $mphxExists) {
                    $filesDir = $extractDir;
                } else {
                    exit(json_encode(array('code' => 500, 'message' => '未找到files目录 - 调试: ' . $debugInfo)));
                }
            }
            
            $upgradeManager->copyFiles($filesDir, ROOT, $admin_dir);
            
            $log = $upgradeManager->getLog();
            exit(json_encode(array(
                'code' => 200,
                'message' => '文件更新成功',
                'next_step' => 'complete',
                'log' => $log
            )));
        } catch(Exception $e) {
            exit(json_encode(array('code' => 500, 'message' => '文件更新失败: ' . $e->getMessage())));
        }
        break;

    case 'complete':
        // 步骤6: 完成升级
        // 清理临时文件
        $upgradeManager->cleanup();
        
        // 删除backup备份文件夹
        $backupDir = ROOT . '/backup';
        if(is_dir($backupDir)) {
            // 递归删除目录
            function deleteBackupDir($dir) {
                $files = array_diff(scandir($dir), array('.','..'));
                foreach ($files as $file) {
                    (is_dir("$dir/$file")) ? deleteBackupDir("$dir/$file") : unlink("$dir/$file");
                }
                return rmdir($dir);
            }
            deleteBackupDir($backupDir);
        }
        
        // 清除session
        unset($_SESSION['upgrade_backup_dir']);
        unset($_SESSION['upgrade_extract_dir']);
        
        logjl($admin_user, $is_repair ? '系统修复' : '系统更新', $is_repair ? '系统修复完成' : '系统更新完成', true);
        exit(json_encode(array(
            'code' => 200, 
            'message' => $is_repair ? '修复成功' : '更新成功',
            'completed' => true
        )));
        break;
        
    case 'rollback':
        // 回滚功能
        $backup_dir = isset($_POST['backup_dir']) ? $_POST['backup_dir'] : '';
        
        if(empty($backup_dir)) {
            // 尝试从session获取
            $backup_dir = isset($_SESSION['upgrade_backup_dir']) ? $_SESSION['upgrade_backup_dir'] : '';
        }
        
        if(empty($backup_dir)) {
            exit(json_encode(array('code' => 400, 'message' => '未找到备份目录')));
        }
        
        logjl($admin_user, '系统回滚', '开始系统回滚', true);
        
        try {
            $upgradeManager->rollback($backup_dir);
            
            // 清除session
            unset($_SESSION['upgrade_backup_dir']);
            unset($_SESSION['upgrade_extract_dir']);
            
            $log = $upgradeManager->getLog();
            exit(json_encode(array(
                'code' => 200, 
                'message' => '回滚成功',
                'log' => $log
            )));
        } catch(Exception $e) {
            exit(json_encode(array('code' => 500, 'message' => '回滚失败: ' . $e->getMessage())));
        }
        break;
        
    default:
        exit(json_encode(array('code' => 400, 'message' => '无效的操作')));
}
