<?php
/**
 * cms.barju.cn - 打包发布页面
 * 功能：自动校验、生成增量补丁包、生成更新日志、推送至主站
 */
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
admin_check_login();
check_permission('admin');

$msg = '';
$msgType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['publish'])) {
	// CSRF 保护
	if (!csrf_validate($_POST["csrf_token"] ?? "")) {
	    die("CSRF 验证失败");
	}

    $version = trim($_POST['version'] ?? '');
    $changelog = trim($_POST['changelog'] ?? '');
    
    if (!$version || !$changelog) {
        $msg = '版本号和更新日志不能为空';
        $msgType = 'error';
    } else {
        // 1. 自动校验功能（检查语法错误、数据库连接等）
        $errors = [];
        
        // 检查 PHP 语法
        $phpFiles = glob(__DIR__ . '/../**/*.php');
        foreach ($phpFiles as $file) {
            $output = [];
            $returnVar = 0;
            exec('php -l "' . $file . '" 2>&1', $output, $returnVar);
            if ($returnVar !== 0) {
                $errors[] = '语法错误：' . $file . ' - ' . implode('\n', $output);
            }
        }
        
        // 检查数据库连接
        try {
            $pdo->query('SELECT 1');
        } catch (Exception $e) {
            $errors[] = '数据库连接失败：' . $e->getMessage();
        }
        
        if (!empty($errors)) {
            $msg = '校验失败：<br>' . implode('<br>', $errors);
            $msgType = 'error';
        } else {
            // 2. 生成增量补丁包
            $packageFile = __DIR__ . '/../packages/barjucms_v' . $version . '.zip';
            
            // 创建 packages 目录
            if (!is_dir(__DIR__ . '/../packages')) {
                mkdir(__DIR__ . '/../packages', 0755, true);
            }
            
            // 生成补丁包（排除上传目录、自定义模板、数据库配置文件）
            $excludeDirs = ['uploads', 'packages', 'config'];
            $excludeFiles = ['config.php', 'database.php'];
            
            $zip = new ZipArchive();
            if ($zip->open($packageFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                $rootPath = realpath(__DIR__ . '/../');
                
                /** @var SplFileInfo[] $files */
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($rootPath),
                    RecursiveIteratorIterator::LEAVES_ONLY
                );
                
                foreach ($files as $name => $file) {
                    if (!$file->isFile()) continue;
                    
                    $filePath = $file->getRealPath();
                    $relativePath = substr($filePath, strlen($rootPath) + 1);
                    
                    // 排除目录和文件
                    $skip = false;
                    foreach ($excludeDirs as $dir) {
                        if (strpos($relativePath, $dir . '/') === 0) {
                            $skip = true;
                            break;
                        }
                    }
                    if (in_array($relativePath, $excludeFiles)) {
                        $skip = true;
                    }
                    
                    if (!$skip) {
                        $zip->addFile($filePath, $relativePath);
                    }
                }
                
                $zip->close();
                
                // 3. 自动生成更新日志（已通过表单输入）
                // 4. 自动推送至主站待发布列表
                $apiUrl = 'https://www.barju.cn/api/version_submit.php';
                $postData = [
                    'version' => $version,
                    'release_date' => date('Y-m-d'),
                    'changelog' => $changelog,
                    'download_url' => '/packages/barjucms_v' . $version . '.zip',
                    'file_size' => filesize($packageFile),
                    'md5_hash' => md5_file($packageFile),
                    'status' => 'beta',
                    'is_published' => 0,
                    'timestamp' => time(),
                ];
                
                // 生成签名
                $secretKey = 'BarjuCMS_Api_Secret_Key_2026';
                $postData['signature'] = md5($version . $postData['timestamp'] . $secretKey);
                
                $ch = curl_init($apiUrl);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
                curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                
                $response = curl_exec($ch);
                $error = curl_error($ch);
                curl_close($ch);
                
                if ($error) {
                    $msg = '推送失败：' . $error;
                    $msgType = 'error';
                } else {
                    $result = json_decode($response, true);
                    if ($result && $result['success']) {
                        $msg = '版本 v' . $version . ' 已成功打包并推送至主站待发布列表！';
                        $msgType = 'success';
                    } else {
                        $msg = '推送失败：' . ($result['message'] ?? '未知错误');
                        $msgType = 'error';
                    }
                }
            } else {
                $msg = '无法创建补丁包文件';
                $msgType = 'error';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>打包发布 - BarjuCMS 调试站</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; }
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; }
        .header h1 { font-size: 1.5em; }
        .container { max-width: 800px; margin: 40px auto; padding: 0 20px; }
        .card { background: white; border-radius: 8px; padding: 40px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .card h2 { font-size: 1.8em; margin-bottom: 20px; color: #333; }
        .form-group { margin-bottom: 25px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 500; color: #555; }
        .form-group input, .form-group textarea { width: 100%; padding: 12px 15px; border: 1px solid #ddd; border-radius: 6px; font-size: 1em; }
        .form-group textarea { min-height: 200px; resize: vertical; }
        .btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 30px; border-radius: 6px; font-size: 1em; font-weight: 500; cursor: pointer; }
        .alert { padding: 15px 20px; border-radius: 6px; margin-bottom: 25px; }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #e7f3ff; padding: 20px; border-radius: 6px; margin-bottom: 30px; line-height: 1.8; }
    </style>
</head>
<body>
    <div class="header">
        <h1>打包发布</h1>
    </div>
    
    <div class="container">
        <div class="card">
            <h2>生成版本补丁包</h2>
            
            <div class="info">
                <p><strong>功能说明：</strong></p>
                <p>1. 自动校验系统功能（PHP语法、数据库连接等）</p>
                <p>2. 生成增量补丁包（排除上传目录、自定义模板、数据库配置）</p>
                <p>3. 自动生成更新日志</p>
                <p>4. 自动推送至主站（www.barju.cn）待发布列表</p>
                <p style="color: #dc3545; margin-top: 10px;"><strong>注意：不会直接对外上线，需主站手动确认发布！</strong></p>
            </div>
            
            <?php if ($msg): ?>
                <div class="alert alert-<?php echo htmlspecialchars($msgType, ENT_QUOTES, "UTF-8"); ?>">
                    <?php echo $msg; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
        <?php echo csrf_input(); ?>
                <div class="form-group">
                    <label for="version">版本号</label>
                    <input type="text" id="version" name="version" placeholder="如：1.0.1" required>
                </div>
                
                <div class="form-group">
                    <label for="changelog">更新日志（JSON格式）</label>
                    <textarea id="changelog" name="changelog" placeholder='{"新增功能": ["功能1", "功能2"], "修复问题": ["问题1", "问题2"]}' required></textarea>
                    <small style="color: #999; margin-top: 5px; display: block;">请输入JSON格式，包含新增功能和修复问题</small>
                </div>
                
                <button type="submit" name="publish" class="btn">生成补丁包并推送</button>
            </form>
        </div>
    </div>
</body>
</html>
