<?php
require_once __DIR__ . '/../MPHX/common.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$gn = isset($_GET['gn']) ? $_GET['gn'] : '';
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$program = null;
$categories = array();

if ($gn == 'cx' && $id > 0) {
    // 获取程序信息
    $program = $DB->get_row("SELECT * FROM `bs` WHERE `id`='{$id}'");
    if (!$program) {
        // 调试信息
        header('Location: /admin/list.php?gn=cx');
        exit;
    }
    
    // 获取分类列表
    $categories = $DB->query("SELECT * FROM `program_categories` ORDER BY `sort_order` ASC, `id` ASC");
    
    // 初始化表单字段和安装操作变量（供页面各处使用）
    // 使用 parse_json_safe 函数安全解析JSON，处理包含换行符和未转义反斜杠的情况
    $form_fields_raw = isset($program['form_fields']) ? $program['form_fields'] : '[]';
    $form_fields = parse_json_safe($form_fields_raw, true);
    if (!is_array($form_fields)) {
        $form_fields = array();
    }
    
    $install_ops_raw = isset($program['install_ops']) ? $program['install_ops'] : '[]';
    $install_ops = parse_json_safe($install_ops_raw, true);
    if (!is_array($install_ops)) {
        $install_ops = array();
    }
    
    // 调试信息
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>编辑程序 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=2026040501">
</head>
<body>
    <div class="content-area" style="margin-left: 0; padding: 20px;">
        <?php if ($gn == 'cx' && $program): ?>
        <style>
            .form-section {
                background: #fff;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 20px;
                border: 1px solid #e8eaed;
                box-shadow: 0 1px 2px rgba(0,0,0,0.04);
            }
            .form-section-title {
                font-size: 14px;
                font-weight: 600;
                color: #202124;
                margin-bottom: 20px;
                padding-bottom: 12px;
                border-bottom: 2px solid #e8eaed;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .form-section-title i {
                color: #1a73e8;
                font-size: 16px;
            }
            .form-row {
                display: flex;
                gap: 20px;
                margin-bottom: 20px;
            }
            .form-row .form-group {
                flex: 1;
                margin-bottom: 0;
            }
            .form-group {
                margin-bottom: 20px;
            }
            .form-group label {
                font-size: 13px;
                font-weight: 500;
                color: #202124;
                margin-bottom: 8px;
                display: block;
            }
            .form-control {
                border: 1px solid #dadce0;
                border-radius: 6px;
                padding: 10px 12px;
                font-size: 13px;
                transition: all 0.2s;
            }
            .form-control:focus {
                border-color: #1a73e8;
                box-shadow: 0 0 0 2px rgba(26,115,232,0.1);
            }
            .btn-block {
                padding: 12px 24px;
                font-size: 14px;
                font-weight: 500;
            }
            .program-preview {
                background: #f8f9fa;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 20px;
            }
            .program-preview img {
                max-width: 100%;
                max-height: 200px;
                border-radius: 6px;
            }
        </style>
        <div class="card">
            <h3><i class="fas fa-edit"></i> 编辑程序</h3>
            
            <div class="program-preview">
                <div class="d-flex align-items-center">
                    <?php 
                // 获取封面图片：优先使用 cover/tb 字段，否则使用 images 的第一张
                $cover_img = !empty($program['cover']) ? $program['cover'] : (!empty($program['tb']) ? $program['tb'] : '');
                if (empty($cover_img) && !empty($program['images'])) {
                    $images = json_decode($program['images'], true);
                    if (is_array($images) && !empty($images[0])) {
                        $cover_img = $images[0];
                    }
                }
                if (!empty($cover_img)): 
                ?>
                    <img src="/uploads/<?php echo htmlspecialchars($cover_img); ?>" alt="封面" style="width: 100px; height: 100px; object-fit: cover; margin-right: 20px;">
                    <?php else: ?>
                    <div style="width: 100px; height: 100px; background: #e8eaed; border-radius: 6px; display: flex; align-items: center; justify-content: center; margin-right: 20px;">
                        <i class="fas fa-image" style="font-size: 32px; color: #9aa0a6;"></i>
                    </div>
                    <?php endif; ?>
                    <div>
                        <h4 style="margin: 0 0 10px 0;"><?php echo htmlspecialchars($program['name']); ?></h4>
                        <p style="margin: 0; color: #5f6368;">
                            <span class="badge badge-primary"><?php echo htmlspecialchars($program['type'] ?: '未分类'); ?></span>
                            <span class="badge badge-secondary">版本: <?php echo htmlspecialchars($program['version'] ?: '1.0'); ?></span>
                            <span class="badge badge-<?php echo $program['status'] == 1 ? 'success' : 'secondary'; ?>">
                                <?php echo $program['status'] == 1 ? '上架' : '下架'; ?>
                            </span>
                        </p>
                    </div>
                </div>
            </div>
            
            <form id="editForm" method="post" enctype="multipart/form-data" onsubmit="return false;">
                <input type="hidden" name="id" value="<?php echo $id; ?>">
                
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-info-circle"></i> 基本信息</div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>程序名称</label>
                            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($program['name']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>程序价格</label>
                            <input type="number" class="form-control" name="jg" step="0.01" value="<?php echo htmlspecialchars($program['jg']); ?>" required>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>程序版本</label>
                            <input type="text" class="form-control" name="version" value="<?php echo htmlspecialchars($program['version']); ?>">
                        </div>
                        <div class="form-group">
                            <label>程序分类</label>
                            <select class="form-control" name="type">
                                <option value="">请选择分类</option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo htmlspecialchars($cat['name']); ?>" <?php echo $program['type'] == $cat['name'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>程序介绍</label>
                        <textarea class="form-control" name="js" rows="4"><?php echo htmlspecialchars($program['js']); ?></textarea>
                    </div>
                </div>
                
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-hdd"></i> 空间需求</div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>所需网页空间 (MB)</label>
                            <input type="number" class="form-control" name="webkj" value="<?php echo intval($program['webkj']); ?>">
                        </div>
                        <div class="form-group">
                            <label>所需数据库空间 (MB)</label>
                            <input type="number" class="form-control" name="sqlkj" value="<?php echo intval($program['sqlkj']); ?>">
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <div class="form-section-title"><i class="fab fa-php"></i> PHP版本要求</div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>所需PHP版本</label>
                            <select name="php_version" class="form-control">
                                <option value="" <?php echo empty($program['php_version']) ? 'selected' : ''; ?>>不限制</option>
                                <option value="5.6" <?php echo $program['php_version'] == '5.6' ? 'selected' : ''; ?>>PHP 5.6</option>
                                <option value="7.0" <?php echo $program['php_version'] == '7.0' ? 'selected' : ''; ?>>PHP 7.0</option>
                                <option value="7.1" <?php echo $program['php_version'] == '7.1' ? 'selected' : ''; ?>>PHP 7.1</option>
                                <option value="7.2" <?php echo $program['php_version'] == '7.2' ? 'selected' : ''; ?>>PHP 7.2</option>
                                <option value="7.3" <?php echo $program['php_version'] == '7.3' ? 'selected' : ''; ?>>PHP 7.3</option>
                                <option value="7.4" <?php echo $program['php_version'] == '7.4' ? 'selected' : ''; ?>>PHP 7.4</option>
                                <option value="8.0" <?php echo $program['php_version'] == '8.0' ? 'selected' : ''; ?>>PHP 8.0</option>
                                <option value="8.1" <?php echo $program['php_version'] == '8.1' ? 'selected' : ''; ?>>PHP 8.1</option>
                                <option value="8.2" <?php echo $program['php_version'] == '8.2' ? 'selected' : ''; ?>>PHP 8.2</option>
                                <option value="8.3" <?php echo $program['php_version'] == '8.3' ? 'selected' : ''; ?>>PHP 8.3</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>所需PHP扩展</label>
                            <input type="text" name="php_ext" class="form-control" value="<?php echo htmlspecialchars($program['php_ext']); ?>" placeholder="如：mysqli,pdo_mysql,gd,curl">
                        </div>
                    </div>
                </div>
                
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-bell"></i> 部署提示</div>
                    <div class="form-group">
                        <label>部署完成后的提示信息</label>
                        <textarea class="form-control" name="alerts" rows="4"><?php echo htmlspecialchars($program['alerts']); ?></textarea>
                        <small>支持替换符：{webname}网站名称, {weburl}网站URL, {user}用户名, {pass}密码等</small>
                    </div>
                </div>
                
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-toggle-on"></i> 状态设置</div>
                    <div class="form-group">
                        <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" id="status" name="status" value="1" <?php echo $program['status'] == 1 ? 'checked' : ''; ?>>
                            <label class="custom-control-label" for="status">程序上架状态</label>
                        </div>
                    </div>
                </div>
                
                <!-- 表单字段管理 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-list-alt"></i> 表单字段配置</div>
                    <div class="form-group">
                        <label>部署时需要用户填写的字段</label>
                        <!-- 调试信息: form_fields=<?php echo htmlspecialchars(json_encode($form_fields)); ?>, count=<?php echo count($form_fields); ?> -->
                        <div id="formFieldsContainer" style="margin-bottom: 15px;">
                            <?php if (!empty($form_fields) && count($form_fields) > 0): ?>
                            <?php foreach ($form_fields as $index => $field): ?>
                            <div class="form-field-item" data-index="<?php echo $index; ?>" style="background: #f8f9fa; border-radius: 8px; padding: 15px; margin-bottom: 10px; border: 1px solid #e8eaed;">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <strong>字段 #<?php echo $index + 1; ?></strong>
                                    <button type="button" class="btn btn-sm btn-danger" onclick="removeFormField(<?php echo $index; ?>)"><i class="fas fa-trash"></i></button>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label>字段名称</label>
                                        <input type="text" class="form-control" name="form_fields[<?php echo $index; ?>][name]" value="<?php echo htmlspecialchars($field['name']); ?>" placeholder="如：admin_user" required>
                                    </div>
                                    <div class="form-group">
                                        <label>显示标签</label>
                                        <input type="text" class="form-control" name="form_fields[<?php echo $index; ?>][label]" value="<?php echo htmlspecialchars($field['label']); ?>" placeholder="如：管理员账号" required>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label>字段类型</label>
                                        <select class="form-control" name="form_fields[<?php echo $index; ?>][type]">
                                            <option value="text" <?php echo $field['type'] == 'text' ? 'selected' : ''; ?>>文本</option>
                                            <option value="password" <?php echo $field['type'] == 'password' ? 'selected' : ''; ?>>密码</option>
                                            <option value="email" <?php echo $field['type'] == 'email' ? 'selected' : ''; ?>>邮箱</option>
                                            <option value="number" <?php echo $field['type'] == 'number' ? 'selected' : ''; ?>>数字</option>
                                            <option value="textarea" <?php echo $field['type'] == 'textarea' ? 'selected' : ''; ?>>多行文本</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>默认值</label>
                                        <input type="text" class="form-control" name="form_fields[<?php echo $index; ?>][default]" value="<?php echo htmlspecialchars($field['default'] ?? ''); ?>" placeholder="可选">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>占位提示</label>
                                    <input type="text" class="form-control" name="form_fields[<?php echo $index; ?>][placeholder]" value="<?php echo htmlspecialchars($field['placeholder'] ?? ''); ?>" placeholder="如：请输入管理员账号">
                                </div>
                                <div class="form-group mb-0">
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="field_required_<?php echo $index; ?>" name="form_fields[<?php echo $index; ?>][required]" value="1" <?php echo !empty($field['required']) ? 'checked' : ''; ?>>
                                        <label class="custom-control-label" for="field_required_<?php echo $index; ?>">必填字段</label>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <button type="button" class="btn btn-outline-primary" onclick="addFormField()">
                            <i class="fas fa-plus"></i> 添加字段
                        </button>
                        <small class="d-block mt-2 text-muted">这些字段将在用户部署程序时显示，供用户填写</small>
                    </div>
                </div>
                
                <!-- 安装操作管理 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-tasks"></i> 安装操作配置</div>
                    <div class="form-group">
                        <label>程序安装步骤</label>
                        <!-- 调试信息: install_ops=<?php echo htmlspecialchars(json_encode($install_ops)); ?>, count=<?php echo count($install_ops); ?> -->
                        <div id="installOpsContainer" style="margin-bottom: 15px;">
                            <?php if (is_array($install_ops) && count($install_ops) > 0): ?>
                            <?php foreach ($install_ops as $index => $op): ?>
                            <div class="install-op-item" data-index="<?php echo $index; ?>" style="background: #f8f9fa; border-radius: 8px; padding: 15px; margin-bottom: 10px; border: 1px solid #e8eaed;">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <strong>步骤 #<?php echo $index + 1; ?></strong>
                                    <button type="button" class="btn btn-sm btn-danger" onclick="removeInstallOp(<?php echo $index; ?>)"><i class="fas fa-trash"></i></button>
                                </div>
                                <div class="form-group">
                                    <label>操作类型</label>
                                    <select class="form-control install-op-type" name="install_ops[<?php echo $index; ?>][type]" onchange="updateInstallOpFields(<?php echo $index; ?>)">
                                        <option value="extract" <?php echo $op['type'] == 'extract' ? 'selected' : ''; ?>>解压文件</option>
                                        <option value="rewrite" <?php echo $op['type'] == 'rewrite' ? 'selected' : ''; ?>>设置伪静态</option>
                                        <option value="sql" <?php echo $op['type'] == 'sql' ? 'selected' : ''; ?>>导入SQL</option>
                                        <option value="rename" <?php echo $op['type'] == 'rename' ? 'selected' : ''; ?>>重命名文件/目录</option>
                                        <option value="config" <?php echo $op['type'] == 'config' ? 'selected' : ''; ?>>修改配置文件</option>
                                        <option value="command" <?php echo $op['type'] == 'command' ? 'selected' : ''; ?>>执行命令</option>
                                        <option value="setrundir" <?php echo $op['type'] == 'setrundir' ? 'selected' : ''; ?>>设置运行目录</option>
                                    </select>
                                </div>
                                <div class="install-op-fields" data-type="<?php echo $op['type']; ?>">
                                    <?php if ($op['type'] == 'extract'): ?>
                                    <div class="form-group">
                                        <label>压缩包路径</label>
                                        <input type="text" class="form-control" name="install_ops[<?php echo $index; ?>][source]" value="<?php echo htmlspecialchars($op['source'] ?? ''); ?>" placeholder="如：/www/wwwroot/source.zip 或 {source_file}">
                                        <small class="text-muted">可使用 {source_file} 变量表示上传的源码文件</small>
                                    </div>
                                    <div class="form-group">
                                        <label>解压目标目录</label>
                                        <input type="text" class="form-control" name="install_ops[<?php echo $index; ?>][target]" value="<?php echo htmlspecialchars($op['target'] ?? ''); ?>" placeholder="如：/www/wwwroot/{webname}">
                                    </div>
                                    <?php elseif ($op['type'] == 'rewrite'): ?>
                                    <div class="form-group">
                                        <label>伪静态规则</label>
                                        <textarea class="form-control" name="install_ops[<?php echo $index; ?>][content]" rows="6" placeholder="输入Nginx伪静态规则"><?php echo htmlspecialchars($op['content'] ?? ''); ?></textarea>
                                    </div>
                                    <?php elseif ($op['type'] == 'sql'): ?>
                                    <div class="form-group">
                                        <label>SQL文件路径</label>
                                        <input type="text" class="form-control" name="install_ops[<?php echo $index; ?>][sql_file]" value="<?php echo htmlspecialchars($op['sql_file'] ?? ''); ?>" placeholder="如：/www/wwwroot/{webname}/install.sql">
                                    </div>
                                    <?php elseif ($op['type'] == 'rename'): ?>
                                    <div class="form-group">
                                        <label>原路径</label>
                                        <input type="text" class="form-control" name="install_ops[<?php echo $index; ?>][old_path]" value="<?php echo htmlspecialchars($op['old_path'] ?? ''); ?>" placeholder="如：/www/wwwroot/{webname}/config.sample.php">
                                    </div>
                                    <div class="form-group">
                                        <label>新路径</label>
                                        <input type="text" class="form-control" name="install_ops[<?php echo $index; ?>][new_path]" value="<?php echo htmlspecialchars($op['new_path'] ?? ''); ?>" placeholder="如：/www/wwwroot/{webname}/config.php">
                                    </div>
                                    <?php elseif ($op['type'] == 'config'): ?>
                                    <div class="form-group">
                                        <label>配置文件路径</label>
                                        <input type="text" class="form-control" name="install_ops[<?php echo $index; ?>][config_file]" value="<?php echo htmlspecialchars($op['config_file'] ?? ''); ?>" placeholder="如：/www/wwwroot/{webname}/config.php">
                                    </div>
                                    <div class="form-group">
                                        <label>配置内容</label>
                                        <textarea class="form-control" name="install_ops[<?php echo $index; ?>][content]" rows="6" placeholder="输入配置文件内容，可使用变量如 {db_host}, {db_name}, {db_user}, {db_pass}, {form_fields}"><?php echo htmlspecialchars($op['content'] ?? ''); ?></textarea>
                                        <small class="text-muted">可用变量: {db_host}, {db_name}, {db_user}, {db_pass}, {webname}, {weburl}, {form_fields}</small>
                                    </div>
                                    <?php elseif ($op['type'] == 'command'): ?>
                                    <div class="form-group">
                                        <label>执行命令</label>
                                        <textarea class="form-control" name="install_ops[<?php echo $index; ?>][command]" rows="3" placeholder="输入要执行的Shell命令"><?php echo htmlspecialchars($op['command'] ?? ''); ?></textarea>
                                        <small class="text-muted">谨慎使用，命令将在服务器上执行</small>
                                    </div>
                                    <?php elseif ($op['type'] == 'setrundir'): ?>
                                    <div class="form-group">
                                        <label>运行目录</label>
                                        <input type="text" class="form-control" name="install_ops[<?php echo $index; ?>][path]" value="<?php echo htmlspecialchars($op['path'] ?? ''); ?>" placeholder="如：/public 或 /www/wwwroot/{webname}/public">
                                        <small class="text-muted">设置网站的运行目录，可使用相对路径（如 /public）或绝对路径</small>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <button type="button" class="btn btn-outline-primary" onclick="addInstallOp()">
                            <i class="fas fa-plus"></i> 添加安装步骤
                        </button>
                        <small class="d-block mt-2 text-muted">按顺序执行这些操作来完成程序安装</small>
                    </div>
                </div>
                
                <!-- 源码文件管理 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-file-archive"></i> 源码文件管理</div>
                    <div class="form-group">
                        <label>当前源码文件</label>
                        <?php if (!empty($program['wj'])): ?>
                        <div class="alert alert-info">
                            <i class="fas fa-file"></i> <?php echo htmlspecialchars($program['wj']); ?>
                            <span class="float-right">
                                <?php
                                // 处理程序包路径：如果wj已经包含programs/前缀，直接使用，否则添加
                                $wj_path = $program['wj'];
                                if (strpos($wj_path, 'programs/') === 0) {
                                    $download_path = '/uploads/' . $wj_path;
                                } else {
                                    $download_path = '/uploads/programs/' . $wj_path;
                                }
                                ?>
                                <a href="<?php echo htmlspecialchars($download_path); ?>" target="_blank" class="btn btn-sm btn-outline-primary" download>
                                    <i class="fas fa-download"></i> 下载
                                </a>
                                <button type="button" class="btn btn-sm btn-outline-danger" onclick="deleteSourceFile()">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </span>
                        </div>
                        <input type="hidden" name="existing_source_file" value="<?php echo htmlspecialchars($program['wj']); ?>">
                        <?php else: ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i> 暂无源码文件
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="form-group">
                        <label>上传新源码文件</label>
                        <div id="sourceFileUploadArea" style="border: 2px dashed #dadce0; border-radius: 8px; padding: 30px; text-align: center; background: #f8f9fa; cursor: pointer; transition: all 0.2s;">
                            <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #9aa0a6; margin-bottom: 15px; display: block;"></i>
                            <p style="color: #5f6368; margin: 0; font-size: 14px; font-weight: 500;">点击上传或拖拽文件到此处</p>
                            <p style="color: #9aa0a6; font-size: 12px; margin: 8px 0 0 0;">支持 .zip, .tar.gz, .tar 格式</p>
                        </div>
                        <input type="file" name="source_file" id="sourceFile" accept=".zip,.tar.gz,.tar" style="display: none;">
                        <div id="sourceFilePreview" style="margin-top: 15px;"></div>
                    </div>
                </div>
                
                <!-- 展示图片管理 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-images"></i> 展示图片</div>
                    <div class="form-group">
                        <label>当前图片</label>
                        <div id="currentImages" style="margin-bottom: 15px;">
                            <?php
                            $images = isset($program['images']) ? json_decode($program['images'], true) : array();
                            if (!is_array($images)) $images = array();
                            ?>
                            <?php if (!empty($images)): ?>
                            <?php foreach ($images as $index => $img): ?>
                            <div class="image-preview-item" data-index="<?php echo $index; ?>" style="display: inline-block; position: relative; margin: 5px; width: 120px; height: 120px; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                <img src="/uploads/<?php echo htmlspecialchars($img); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                <span class="remove-image" onclick="removeExistingImage(<?php echo $index; ?>)" style="position: absolute; top: 5px; right: 5px; background: rgba(234,67,53,0.9); color: white; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 14px;"><i class="fas fa-times"></i></span>
                                <?php if ($index === 0): ?>
                                <span style="position: absolute; bottom: 0; left: 0; right: 0; background: rgba(26,115,232,0.9); color: white; font-size: 12px; padding: 4px; text-align: center;">封面</span>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <input type="hidden" name="existing_images" id="existingImages" value='<?php echo htmlspecialchars($program['images'] ?? '[]'); ?>'>
                        
                        <label>添加新图片</label>
                        <div id="imageUploadArea" style="border: 2px dashed #dadce0; border-radius: 8px; padding: 20px; text-align: center; background: #f8f9fa; cursor: pointer; transition: all 0.2s;">
                            <i class="fas fa-cloud-upload-alt" style="font-size: 36px; color: #9aa0a6; margin-bottom: 10px;"></i>
                            <p style="color: #5f6368; margin: 0; font-size: 14px;">点击上传或拖拽图片到此处</p>
                            <p style="color: #9aa0a6; font-size: 11px; margin: 5px 0 0 0;">支持 .png, .jpg, .jpeg, .gif 格式</p>
                            <input type="file" name="new_images[]" id="newImages" multiple accept=".png,.jpg,.jpeg,.gif" style="display: none;">
                        </div>
                        <div id="newImagePreviewArea" style="margin-top: 15px;"></div>
                        <small>第一张图片将作为程序封面</small>
                    </div>
                </div>
                
                <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fas fa-save"></i> 保存修改
                    </button>
                    <a href="list.php?gn=cx" class="btn btn-secondary btn-block mt-2">
                        <i class="fas fa-arrow-left"></i> 返回列表
                    </a>
                </div>
            </form>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i> 程序不存在或参数错误 (gn=<?php echo htmlspecialchars($gn); ?>, id=<?php echo $id; ?>)
            </div>
            <a href="list.php?gn=cx" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> 返回列表
            </a>
        </div>
        <?php endif; ?>
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
    
    <?php if ($gn == 'cx' && $program): ?>
    <script>
    $(document).ready(function() {
        // 管理现有图片
        var existingImages = JSON.parse($('#existingImages').val() || '[]');
        var newImages = [];
        
        window.removeExistingImage = function(index) {
            existingImages.splice(index, 1);
            $('#existingImages').val(JSON.stringify(existingImages));
            renderExistingImages();
        };
        
        function renderExistingImages() {
            var html = '';
            existingImages.forEach(function(img, index) {
                html += '<div class="image-preview-item" data-index="' + index + '" style="display: inline-block; position: relative; margin: 5px; width: 120px; height: 120px; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">';
                html += '<img src="/uploads/' + escapeHtml(img) + '" style="width: 100%; height: 100%; object-fit: cover;">';
                html += '<span class="remove-image" onclick="removeExistingImage(' + index + ')" style="position: absolute; top: 5px; right: 5px; background: rgba(234,67,53,0.9); color: white; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 14px;"><i class="fas fa-times"></i></span>';
                if (index === 0) {
                    html += '<span style="position: absolute; bottom: 0; left: 0; right: 0; background: rgba(26,115,232,0.9); color: white; font-size: 12px; padding: 4px; text-align: center;">封面</span>';
                }
                html += '</div>';
            });
            $('#currentImages').html(html);
        }
        
        function escapeHtml(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // 新图片上传 - 使用原生JavaScript
        document.getElementById('imageUploadArea').addEventListener('click', function() {
            document.getElementById('newImages').click();
        });
        
        document.getElementById('imageUploadArea').addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#1a73e8';
            this.style.background = '#e8f0fe';
        });
        
        document.getElementById('imageUploadArea').addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.borderColor = '#dadce0';
            this.style.background = '#f8f9fa';
        });
        
        document.getElementById('imageUploadArea').addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '#dadce0';
            this.style.background = '#f8f9fa';
            handleNewImages(e.dataTransfer.files);
        });
        
        document.getElementById('newImages').addEventListener('change', function() {
            handleNewImages(this.files);
        });
        
        function handleNewImages(files) {
            var totalImages = existingImages.length + newImages.length;
            var remainingSlots = 9 - totalImages;
            
            if (remainingSlots <= 0) {
                alert('最多只能上传9张图片');
                return;
            }
            
            var filesToProcess = Math.min(files.length, remainingSlots);
            
            for (var i = 0; i < filesToProcess; i++) {
                var file = files[i];
                if (!file.type.match('image.*')) continue;
                
                newImages.push(file);
                
                var reader = new FileReader();
                reader.onload = (function(theFile, index) {
                    return function(e) {
                        var html = '<div class="new-image-preview-item" data-index="' + index + '" style="display: inline-block; position: relative; margin: 5px; width: 120px; height: 120px; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">';
                        html += '<img src="' + e.target.result + '" style="width: 100%; height: 100%; object-fit: cover;">';
                        html += '<span class="remove-new-image" onclick="removeNewImage(' + index + ')" style="position: absolute; top: 5px; right: 5px; background: rgba(234,67,53,0.9); color: white; width: 24px; height: 24px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 14px;"><i class="fas fa-times"></i></span>';
                        html += '<span style="position: absolute; bottom: 0; left: 0; right: 0; background: rgba(251,188,5,0.9); color: white; font-size: 12px; padding: 4px; text-align: center;">新图片</span>';
                        html += '</div>';
                        
                        $('#newImagePreviewArea').append(html);
                    };
                })(file, newImages.length - 1);
                
                reader.readAsDataURL(file);
            }
            
            updateNewImagesInput();
        }
        
        window.removeNewImage = function(index) {
            newImages.splice(index, 1);
            $('.new-image-preview-item[data-index="' + index + '"]').remove();
            
            $('.new-image-preview-item').each(function(i) {
                $(this).attr('data-index', i);
                $(this).find('.remove-new-image').attr('onclick', 'removeNewImage(' + i + ')');
            });
            
            updateNewImagesInput();
        };
        
        function updateNewImagesInput() {
            var dataTransfer = new DataTransfer();
            newImages.forEach(function(file) {
                dataTransfer.items.add(file);
            });
            $('#newImages')[0].files = dataTransfer.files;
        }
        
        // ========== 表单字段管理 ==========
        var formFieldIndex = <?php echo !empty($form_fields) ? count($form_fields) : 0; ?>;
        
        window.addFormField = function() {
            var html = '<div class="form-field-item" data-index="' + formFieldIndex + '" style="background: #f8f9fa; border-radius: 8px; padding: 15px; margin-bottom: 10px; border: 1px solid #e8eaed;">';
            html += '<div class="d-flex justify-content-between align-items-center mb-2">';
            html += '<strong>字段 #' + (formFieldIndex + 1) + '</strong>';
            html += '<button type="button" class="btn btn-sm btn-danger" onclick="removeFormField(' + formFieldIndex + ')"><i class="fas fa-trash"></i></button>';
            html += '</div>';
            html += '<div class="form-row">';
            html += '<div class="form-group">';
            html += '<label>字段名称</label>';
            html += '<input type="text" class="form-control" name="form_fields[' + formFieldIndex + '][name]" placeholder="如：admin_user" required>';
            html += '</div>';
            html += '<div class="form-group">';
            html += '<label>显示标签</label>';
            html += '<input type="text" class="form-control" name="form_fields[' + formFieldIndex + '][label]" placeholder="如：管理员账号" required>';
            html += '</div>';
            html += '</div>';
            html += '<div class="form-row">';
            html += '<div class="form-group">';
            html += '<label>字段类型</label>';
            html += '<select class="form-control" name="form_fields[' + formFieldIndex + '][type]">';
            html += '<option value="text">文本</option>';
            html += '<option value="password">密码</option>';
            html += '<option value="email">邮箱</option>';
            html += '<option value="number">数字</option>';
            html += '<option value="textarea">多行文本</option>';
            html += '</select>';
            html += '</div>';
            html += '<div class="form-group">';
            html += '<label>默认值</label>';
            html += '<input type="text" class="form-control" name="form_fields[' + formFieldIndex + '][default]" placeholder="可选">';
            html += '</div>';
            html += '</div>';
            html += '<div class="form-group">';
            html += '<label>占位提示</label>';
            html += '<input type="text" class="form-control" name="form_fields[' + formFieldIndex + '][placeholder]" placeholder="如：请输入管理员账号">';
            html += '</div>';
            html += '<div class="form-group mb-0">';
            html += '<div class="custom-control custom-checkbox">';
            html += '<input type="checkbox" class="custom-control-input" id="field_required_' + formFieldIndex + '" name="form_fields[' + formFieldIndex + '][required]" value="1">';
            html += '<label class="custom-control-label" for="field_required_' + formFieldIndex + '">必填字段</label>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
            
            $('#formFieldsContainer').append(html);
            formFieldIndex++;
        };
        
        window.removeFormField = function(index) {
            $('.form-field-item[data-index="' + index + '"]').remove();
            // 重新索引
            $('.form-field-item').each(function(i) {
                $(this).attr('data-index', i);
                $(this).find('strong').text('字段 #' + (i + 1));
                $(this).find('button').attr('onclick', 'removeFormField(' + i + ')');
                // 更新所有input的name属性
                $(this).find('input, select').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        var newName = name.replace(/form_fields\[\d+\]/, 'form_fields[' + i + ']');
                        $(this).attr('name', newName);
                    }
                });
                // 更新checkbox的id
                var checkbox = $(this).find('.custom-control-input');
                if (checkbox.length) {
                    checkbox.attr('id', 'field_required_' + i);
                    $(this).find('.custom-control-label').attr('for', 'field_required_' + i);
                }
            });
            formFieldIndex = $('.form-field-item').length;
        };
        
        // ========== 安装操作管理 ==========
        var installOpIndex = <?php echo !empty($install_ops) ? count($install_ops) : 0; ?>;
        
        var installOpTemplates = {
            extract: '<div class="form-group">' +
                '<label>压缩包路径</label>' +
                '<input type="text" class="form-control" name="install_ops[{index}][source]" placeholder="如：/www/wwwroot/source.zip 或 {source_file}">' +
                '<small class="text-muted">可使用 {source_file} 变量表示上传的源码文件</small>' +
                '</div>' +
                '<div class="form-group">' +
                '<label>解压目标目录</label>' +
                '<input type="text" class="form-control" name="install_ops[{index}][target]" placeholder="如：/www/wwwroot/{webname}">' +
                '</div>',
            rewrite: '<div class="form-group">' +
                '<label>伪静态规则</label>' +
                '<textarea class="form-control" name="install_ops[{index}][content]" rows="6" placeholder="输入Nginx伪静态规则"></textarea>' +
                '</div>',
            sql: '<div class="form-group">' +
                '<label>SQL文件路径</label>' +
                '<input type="text" class="form-control" name="install_ops[{index}][sql_file]" placeholder="如：/www/wwwroot/{webname}/install.sql">' +
                '</div>',
            rename: '<div class="form-group">' +
                '<label>原路径</label>' +
                '<input type="text" class="form-control" name="install_ops[{index}][old_path]" placeholder="如：/www/wwwroot/{webname}/config.sample.php">' +
                '</div>' +
                '<div class="form-group">' +
                '<label>新路径</label>' +
                '<input type="text" class="form-control" name="install_ops[{index}][new_path]" placeholder="如：/www/wwwroot/{webname}/config.php">' +
                '</div>',
            config: '<div class="form-group">' +
                '<label>配置文件路径</label>' +
                '<input type="text" class="form-control" name="install_ops[{index}][config_file]" placeholder="如：/www/wwwroot/{webname}/config.php">' +
                '</div>' +
                '<div class="form-group">' +
                '<label>配置内容</label>' +
                '<textarea class="form-control" name="install_ops[{index}][content]" rows="6" placeholder="输入配置文件内容，可使用变量如 {db_host}, {db_name}, {db_user}, {db_pass}, {form_fields}"></textarea>' +
                '<small class="text-muted">可用变量: {db_host}, {db_name}, {db_user}, {db_pass}, {webname}, {weburl}, {form_fields}</small>' +
                '</div>',
            command: '<div class="form-group">' +
                '<label>执行命令</label>' +
                '<textarea class="form-control" name="install_ops[{index}][command]" rows="3" placeholder="输入要执行的Shell命令"></textarea>' +
                '<small class="text-muted">谨慎使用，命令将在服务器上执行</small>' +
                '</div>',
            setrundir: '<div class="form-group">' +
                '<label>运行目录</label>' +
                '<input type="text" class="form-control" name="install_ops[{index}][path]" placeholder="如：/public 或 /www/wwwroot/{webname}/public">' +
                '<small class="text-muted">设置网站的运行目录，可使用相对路径（如 /public）或绝对路径</small>' +
                '</div>'
        };
        
        window.addInstallOp = function() {
            var html = '<div class="install-op-item" data-index="' + installOpIndex + '" style="background: #f8f9fa; border-radius: 8px; padding: 15px; margin-bottom: 10px; border: 1px solid #e8eaed;">';
            html += '<div class="d-flex justify-content-between align-items-center mb-2">';
            html += '<strong>步骤 #' + (installOpIndex + 1) + '</strong>';
            html += '<button type="button" class="btn btn-sm btn-danger" onclick="removeInstallOp(' + installOpIndex + ')"><i class="fas fa-trash"></i></button>';
            html += '</div>';
            html += '<div class="form-group">';
            html += '<label>操作类型</label>';
            html += '<select class="form-control install-op-type" name="install_ops[' + installOpIndex + '][type]" onchange="updateInstallOpFields(' + installOpIndex + ')">';
            html += '<option value="extract">解压文件</option>';
            html += '<option value="rewrite">设置伪静态</option>';
            html += '<option value="sql">导入SQL</option>';
            html += '<option value="rename">重命名文件/目录</option>';
            html += '<option value="config">修改配置文件</option>';
            html += '<option value="command">执行命令</option>';
            html += '<option value="setrundir">设置运行目录</option>';
            html += '</select>';
            html += '</div>';
            html += '<div class="install-op-fields" data-type="extract">';
            html += installOpTemplates.extract.replace(/{index}/g, installOpIndex);
            html += '</div>';
            html += '</div>';
            
            $('#installOpsContainer').append(html);
            installOpIndex++;
        };
        
        window.removeInstallOp = function(index) {
            $('.install-op-item[data-index="' + index + '"]').remove();
            // 重新索引
            $('.install-op-item').each(function(i) {
                $(this).attr('data-index', i);
                $(this).find('strong').text('步骤 #' + (i + 1));
                $(this).find('button').attr('onclick', 'removeInstallOp(' + i + ')');
                $(this).find('.install-op-type').attr('onchange', 'updateInstallOpFields(' + i + ')');
                // 更新所有input/textarea/select的name属性
                $(this).find('input, textarea, select').each(function() {
                    var name = $(this).attr('name');
                    if (name) {
                        var newName = name.replace(/install_ops\[\d+\]/, 'install_ops[' + i + ']');
                        $(this).attr('name', newName);
                    }
                });
            });
            installOpIndex = $('.install-op-item').length;
        };
        
        window.updateInstallOpFields = function(index) {
            var type = $('.install-op-item[data-index="' + index + '"] .install-op-type').val();
            var template = installOpTemplates[type] || '';
            $('.install-op-item[data-index="' + index + '"] .install-op-fields').html(template.replace(/{index}/g, index));
        };
        
        // ========== 源码文件管理 ==========
        window.deleteSourceFile = function() {
            if (confirm('确定要删除当前源码文件吗？')) {
                $('input[name="existing_source_file"]').val('');
                $('.alert-info:has(.fa-file)').html('<div class="alert alert-warning"><i class="fas fa-exclamation-triangle"></i> 文件已标记删除，保存后生效</div>');
            }
        };
        
        // 源码文件上传事件绑定
        document.getElementById('sourceFileUploadArea').addEventListener('click', function() {
            document.getElementById('sourceFile').click();
        });
        
        document.getElementById('sourceFileUploadArea').addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#1a73e8';
            this.style.background = '#e8f0fe';
        });
        
        document.getElementById('sourceFileUploadArea').addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.borderColor = '#dadce0';
            this.style.background = '#f8f9fa';
        });
        
        document.getElementById('sourceFileUploadArea').addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '#dadce0';
            this.style.background = '#f8f9fa';
            var files = e.dataTransfer.files;
            if (files.length > 0) {
                handleSourceFile(files[0]);
            }
        });
        
        document.getElementById('sourceFile').addEventListener('change', function() {
            if (this.files.length > 0) {
                handleSourceFile(this.files[0]);
            }
        });
        
        function handleSourceFile(file) {
            var allowedTypes = ['.zip', '.tar.gz', '.tar'];
            var fileName = file.name.toLowerCase();
            var isValid = allowedTypes.some(function(ext) {
                return fileName.endsWith(ext);
            });
            
            if (!isValid) {
                alert('不支持的文件格式，请上传 .zip, .tar.gz 或 .tar 文件');
                return;
            }
            
            var html = '<div class="alert alert-success">';
            html += '<i class="fas fa-check-circle"></i> 已选择文件: ' + escapeHtml(file.name);
            html += ' (' + formatFileSize(file.size) + ')';
            html += '</div>';
            $('#sourceFilePreview').html(html);
        }
        
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            var k = 1024;
            var sizes = ['Bytes', 'KB', 'MB', 'GB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        $('#editForm').on('submit', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            var $btn = $(this).find('button[type="submit"]');
            var originalText = $btn.html();
            $btn.addClass('btn-loading').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 保存中...');
            
            var formData = new FormData(this);
            formData.append('egn', 'edit_cx');
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function(data) {
                    alert(data.code || '操作完成');
                    if (data.code == '更新成功') {
                        var timestamp = new Date().getTime();
                        var listUrl = 'list.php?gn=cx&t=' + timestamp;
                        if (window.parent && window.parent.loadPage) {
                            window.parent.loadPage(listUrl);
                        } else {
                            console.log('Using window.location.href');
                            window.location.href = listUrl;
                        }
                    } else {
                        alert('保存失败: ' + (data.code || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    alert('操作失败，请重试');
                },
                complete: function() {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                }
            });
            
            return false;
        });
    });
    </script>
    <?php endif; ?>
</body>
</html>
