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

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

$gn = isset($_GET['gn']) ? $_GET['gn'] : '';

// 获取程序分类列表
$categories = array();
$res = $DB->query("SELECT * FROM `program_categories` ORDER BY `sort_order` ASC, `id` ASC");
while ($row = $DB->fetch($res)) {
    $categories[] = $row;
}
// 如果没有分类，使用默认分类
if (empty($categories)) {
    $categories = array(
        array('name' => 'WordPress', 'icon' => 'fa-wordpress'),
        array('name' => 'Discuz', 'icon' => 'fa-comments'),
        array('name' => 'DedeCMS', 'icon' => 'fa-file-alt'),
        array('name' => 'ThinkPHP', 'icon' => 'fa-code'),
        array('name' => 'Laravel', 'icon' => 'fa-laravel'),
        array('name' => '其他', 'icon' => 'fa-folder')
    );
}
?>
<!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">
        <?php if ($gn == 'bt'): ?>
        <div class="card">
            <h3><i class="fas fa-network-wired"></i> 添加宝塔</h3>
            <form id="btForm">
                <div class="form-group">
                    <label for="btmc">宝塔名字 <span style="color: red;">*</span></label>
                    <input type="text" name="btmc" id="btmc" class="form-control" placeholder="请输入宝塔名字" required>
                    <small>请输入宝塔服务器的名字（必填）</small>
                </div>
                <div class="form-group">
                    <label for="ip">宝塔IP <span style="color: red;">*</span></label>
                    <input type="text" name="ip" id="ip" class="form-control" placeholder="192.168.1.1" required oninput="updateFtpAddress()">
                    <small>请输入宝塔服务器的IP地址（必填）</small>
                </div>
                <div class="form-group">
                    <label for="dk">宝塔端口 <span style="color: red;">*</span></label>
                    <input type="text" name="dk" id="dk" class="form-control" placeholder="8888" required>
                    <small>请输入宝塔面板的端口（必填）</small>
                </div>
                <div class="form-group">
                    <label for="key">宝塔密钥 <span style="color: red;">*</span></label>
                    <input type="text" name="key" id="key" class="form-control" placeholder="API密钥" required>
                    <small>请输入宝塔API密钥（必填）</small>
                </div>
                <div class="form-group">
                    <label for="ftp">FTP 地址</label>
                    <input type="text" name="ftp" id="ftp" class="form-control" placeholder="ftp://192.168.1.1">
                    <small>FTP 地址将根据 IP 自动填充</small>
                </div>
                <div class="form-group">
                    <label for="bzbh">宝塔编号 <span style="color: red;">*</span></label>
                    <div style="display: flex; gap: 10px;">
                        <input type="text" name="bzbh" id="bzbh" class="form-control" placeholder="BT001" required style="flex: 1;">
                        <button type="button" class="btn btn-secondary" onclick="generateBzbh()" style="white-space: nowrap;">
                            <i class="fas fa-random"></i> 随机生成
                        </button>
                    </div>
                    <small>请输入宝塔编号（必填，可点击按钮随机生成）</small>
                </div>
                <div class="form-group">
                    <label for="czzt">操作系统</label>
                    <select name="czzt" id="czzt" class="form-control">
                        <option value="Linux">Linux</option>
                        <option value="Windows">Windows</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>安全访问</label>
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <input type="checkbox" id="aqfw" name="aqfw" style="width: auto;">
                        <label for="aqfw" style="margin: 0; font-weight: 400;">开启安全访问</label>
                    </div>
                </div>
                <div class="form-group">
                    <label>接口开关</label>
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <input type="checkbox" id="jkkg" name="jkkg" checked style="width: auto;">
                        <label for="jkkg" style="margin: 0; font-weight: 400;">开启接口</label>
                    </div>
                </div>
                <button type="button" class="btn btn-primary" onclick="addbt(this)">
                    <i class="fas fa-plus"></i> 添加
                </button>
            </form>
        </div>
        
        <script>
        // 自动更新FTP地址
        function updateFtpAddress() {
            var ip = $('#ip').val().trim();
            if (ip) {
                $('#ftp').val('ftp://' + ip);
            } else {
                $('#ftp').val('');
            }
        }
        
        // 随机生成宝塔编号
        function generateBzbh() {
            var timestamp = Date.now().toString().slice(-4);
            var random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
            var bzbh = 'BT' + timestamp + random;
            $('#bzbh').val(bzbh);
        }
        
        function addbt(btn) {
            var $btn = $(btn);
            var originalText = $btn.html();
            $btn.addClass('btn-loading').prop('disabled', true);
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: $('#btForm').serialize() + '&egn=addbt',
                dataType: 'json',
                success: function(data) {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert(data.code);
                    if(data.code == '添加成功') {
                        location.href = 'list.php?gn=bt';
                    }
                },
                error: function(xhr, status, error) {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert('操作失败: ' + (xhr.responseText || '请检查网络连接'));
                }
            });
        }
        </script>
        
        <?php elseif ($gn == 'ym'): ?>
        <div class="card">
            <h3><i class="fas fa-globe"></i> 添加域名</h3>
            <form id="ymForm">
                <div class="form-group">
                    <label for="ym">域名</label>
                    <input type="text" name="ym" id="ym" class="form-control" placeholder="example.com" required>
                    <small>请输入域名</small>
                </div>
                <div class="form-group">
                    <label for="jg">价格</label>
                    <input type="text" name="jg" id="jg" class="form-control" placeholder="10" required>
                    <small>请输入价格</small>
                </div>
                <div class="form-group">
                    <label for="js">简介</label>
                    <textarea name="js" id="js" class="form-control" placeholder="域名简介"></textarea>
                    <small>请输入域名简介（可选）</small>
                </div>
                <div class="form-group">
                    <label for="btid">所属宝塔</label>
                    <select name="btid" id="btid" class="form-control" required>
                        <?php
                        $bts = $DB->query("SELECT * FROM `bt`");
                        while ($bt = $DB->fetch($bts)) {
                            echo '<option value="'.$bt['id'].'">'.$bt['ip'].'</option>';
                        }
                        ?>
                    </select>
                </div>
                <button type="button" class="btn btn-primary" onclick="addym(this)">
                    <i class="fas fa-plus"></i> 添加
                </button>
            </form>
        </div>
        
        <script>
        function addym(btn) {
            var $btn = $(btn);
            var originalText = $btn.html();
            $btn.addClass('btn-loading').prop('disabled', true);
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: $('#ymForm').serialize() + '&egn=addym',
                dataType: 'json',
                success: function(data) {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert(data.code);
                    if(data.code == '添加成功') {
                        location.href = 'list.php?gn=ym';
                    }
                },
                error: function() {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert('操作失败，请重试');
                }
            });
        }
        </script>
        
        <?php elseif ($gn == 'zj'): ?>
        <div class="card">
            <h3><i class="fas fa-laptop"></i> 添加主机</h3>
            <form id="zjForm">
                <div class="form-group">
                    <label for="btid">选择宝塔</label>
                    <select name="btid" id="btid" class="form-control" required>
                        <?php
                        $bts = $DB->query("SELECT * FROM `bt`");
                        while ($bt = $DB->fetch($bts)) {
                            echo '<option value="'.$bt['id'].'">'.$bt['ip'].' ('.$bt['czzt'].')</option>';
                        }
                        ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="cplx">产品类型</label>
                    <select name="cplx" id="cplx" class="form-control" required>
                        <option value="主机">主机</option>
                        <option value="CDN">CDN</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="user">账号</label>
                    <input type="text" name="user" id="user" class="form-control" placeholder="用户名" required oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
                    <small style="color: #dc3545;"><i class="fas fa-exclamation-triangle"></i> 不支持中文，仅限字母、数字、下划线和横线</small>
                </div>
                <div class="form-group">
                    <label for="pass">密码</label>
                    <input type="text" name="pass" id="pass" class="form-control" placeholder="密码" required>
                    <small>请输入密码</small>
                </div>
                <div class="form-group">
                    <label for="wypj">网页空间大小 (MB)</label>
                    <input type="number" name="wypj" id="wypj" class="form-control" placeholder="1024" required>
                    <input type="hidden" name="wypj_unit" id="wypj_unit" value="MB">
                    <small>请输入网页空间大小（单位：MB）</small>
                </div>
                <div class="form-group">
                    <label for="sypj">数据库空间大小 (MB)</label>
                    <input type="number" name="sypj" id="sypj" class="form-control" placeholder="1024" required>
                    <input type="hidden" name="sypj_unit" id="sypj_unit" value="MB">
                    <small>请输入数据库空间大小（单位：MB）</small>
                </div>
                <div class="form-group">
                    <label for="llxz">流量限制 (GB)</label>
                    <input type="number" name="llxz" id="llxz" class="form-control" placeholder="10" required>
                    <input type="hidden" name="llxz_unit" id="llxz_unit" value="GB">
                    <small>请输入流量限制（单位：GB）</small>
                </div>
                <div class="form-group">
                    <label for="dqsj">到期时间</label>
                    <input type="date" name="dqsj" id="dqsj" class="form-control" required>
                    <small>请选择到期时间</small>
                </div>
                <div class="form-group">
                    <label for="yms">域名绑定数</label>
                    <input type="number" name="yms" id="yms" class="form-control" placeholder="1" min="0" required>
                    <small>请输入域名绑定数（0表示不限制）</small>
                </div>
                <button type="button" class="btn btn-primary" onclick="addzj(this)">
                    <i class="fas fa-plus"></i> 添加
                </button>
            </form>
        </div>
        
        <script>
        function addzj(btn) {
            var $btn = $(btn);
            var originalText = $btn.html();
            $btn.addClass('btn-loading').prop('disabled', true);
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: $('#zjForm').serialize() + '&egn=addzj',
                dataType: 'json',
                success: function(data) {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert(data.code);
                    if(data.code == '添加成功') {
                        location.href = 'list.php?gn=zj';
                    }
                },
                error: function() {
                    $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                    alert('操作失败，请重试');
                }
            });
        }
        </script>
        
        <?php elseif ($gn == 'cx'): ?>
        <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);
            }
            .form-control::placeholder {
                color: #9aa0a6;
            }
            .dynamic-form-item {
                background: #f8f9fa;
                border: 1px solid #e8eaed;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 12px;
                position: relative;
                transition: all 0.2s;
            }
            .dynamic-form-item:hover {
                border-color: #1a73e8;
                box-shadow: 0 2px 8px rgba(26,115,232,0.08);
            }
            .dynamic-form-item .remove-btn {
                position: absolute;
                top: 15px;
                right: 15px;
                color: #ea4335;
                cursor: pointer;
                font-size: 18px;
                width: 28px;
                height: 28px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                transition: all 0.2s;
            }
            .dynamic-form-item .remove-btn:hover {
                background: #fce8e8;
                color: #c5221f;
            }
            .add-btn-group {
                margin-top: 15px;
            }
            .install-operation-item {
                background: #f8f9fa;
                border: 1px solid #e8eaed;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 12px;
                position: relative;
                transition: all 0.2s;
            }
            .install-operation-item:hover {
                border-color: #1a73e8;
                box-shadow: 0 2px 8px rgba(26,115,232,0.08);
            }
            .install-operation-item .op-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
                padding-bottom: 12px;
                border-bottom: 1px solid #e8eaed;
            }
            .install-operation-item .op-type {
                font-weight: 600;
                color: #1a73e8;
                font-size: 14px;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .install-operation-item .op-type i {
                font-size: 16px;
            }
            .install-operation-item .remove-btn {
                color: #ea4335;
                cursor: pointer;
                font-size: 18px;
                width: 28px;
                height: 28px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                transition: all 0.2s;
            }
            .install-operation-item .remove-btn:hover {
                background: #fce8e8;
                color: #c5221f;
            }
            .help-text {
                background: linear-gradient(135deg, #e8f0fe 0%, #f1f8e9 100%);
                border-left: 4px solid #1a73e8;
                padding: 20px;
                margin-top: 25px;
                border-radius: 0 8px 8px 0;
                font-size: 13px;
                color: #5f6368;
                line-height: 1.8;
            }
            .help-text strong {
                color: #202124;
                font-weight: 600;
            }
            .help-text code {
                background: #fff;
                padding: 3px 8px;
                border-radius: 4px;
                color: #1a73e8;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 12px;
                border: 1px solid #e8eaed;
            }
            .btn-block {
                padding: 12px 24px;
                font-size: 14px;
                font-weight: 500;
            }
            small {
                color: #5f6368;
                font-size: 12px;
                margin-top: 6px;
                display: block;
            }
            .dropdown-menu {
                border: 1px solid #e8eaed;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                padding: 8px 0;
            }
            .dropdown-item {
                padding: 10px 20px;
                font-size: 13px;
                color: #5f6368;
                transition: all 0.2s;
            }
            .dropdown-item:hover {
                background: #e8f0fe;
                color: #1a73e8;
            }
            .dropdown-item i {
                margin-right: 8px;
                width: 16px;
            }
        </style>
        <div class="card">
            <h3><i class="fas fa-box"></i> 添加程序</h3>
            <form id="cxForm">
                <!-- 基本信息 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-info-circle"></i> 基本信息</div>
                    <div class="form-group">
                        <label for="name">程序名称 <span style="color: red;">*</span></label>
                        <input type="text" name="name" id="name" class="form-control" placeholder="WordPress" required>
                        <small>程序显示给客户时的名称</small>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="jg">价格 <span style="color: red;">*</span></label>
                            <input type="number" name="jg" id="jg" class="form-control" placeholder="10" min="0" step="0.01" required>
                            <small>部署本程序需要支付的费用（元），免费请填0</small>
                        </div>
                        <div class="form-group">
                            <label for="version">版本 <span style="color: red;">*</span></label>
                            <input type="text" name="version" id="version" class="form-control" placeholder="6.0" required>
                            <small>程序版本号</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="type">程序类型</label>
                        <select name="type" id="type" class="form-control">
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat['name']); ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small>可在"程序分类"管理中自定义分类</small>
                    </div>
                    <div class="form-group">
                        <label for="js">程序介绍</label>
                        <textarea name="js" id="js" class="form-control" rows="4" placeholder="程序简介"></textarea>
                        <small>程序显示给客户的介绍说明</small>
                    </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 for="webkj">所需网页空间 (MB)</label>
                            <input type="number" name="webkj" id="webkj" class="form-control" placeholder="100" min="0">
                            <small>安装本程序最低所需的网页空间（单位：MB）</small>
                        </div>
                        <div class="form-group">
                            <label for="sqlkj">所需数据库空间 (MB)</label>
                            <input type="number" name="sqlkj" id="sqlkj" class="form-control" placeholder="50" min="0">
                            <small>安装本程序最低所需的数据库空间（单位：MB）</small>
                        </div>
                    </div>
                </div>

                <!-- PHP版本要求 -->
                <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 for="php_version">所需PHP版本</label>
                            <select name="php_version" id="php_version" class="form-control">
                                <option value="">不限制</option>
                                <option value="5.6">PHP 5.6</option>
                                <option value="7.0">PHP 7.0</option>
                                <option value="7.1">PHP 7.1</option>
                                <option value="7.2">PHP 7.2</option>
                                <option value="7.3">PHP 7.3</option>
                                <option value="7.4">PHP 7.4</option>
                                <option value="8.0">PHP 8.0</option>
                                <option value="8.1">PHP 8.1</option>
                                <option value="8.2">PHP 8.2</option>
                                <option value="8.3">PHP 8.3</option>
                            </select>
                            <small>安装本程序所需的最低PHP版本（不限制则表示支持所有版本）</small>
                        </div>
                        <div class="form-group">
                            <label for="php_ext">所需PHP扩展</label>
                            <input type="text" name="php_ext" id="php_ext" class="form-control" placeholder="如：mysqli,pdo_mysql,gd,curl">
                            <small>多个扩展用逗号分隔，可选</small>
                        </div>
                    </div>
                </div>

                <!-- 部署提示 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-bell"></i> 部署完成提示</div>
                    <div class="form-group">
                        <label for="alerts">部署完成后的弹窗提示</label>
                        <textarea name="alerts" id="alerts" class="form-control" rows="4" placeholder="部署成功！"></textarea>
                        <small>部署成功后给用户的弹窗提示（支持使用替换符）</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 for="source_file">程序源码文件 <span style="color: red;">*</span></label>
                        <input type="file" name="source_file" id="source_file" class="form-control" accept=".zip,.tar.gz,.tar" required>
                        <small>请上传程序源码压缩包（支持 .zip, .tar.gz, .tar 格式）</small>
                    </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="imageUploadArea" 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;"></i>
                            <p style="color: #5f6368; margin: 0;">点击上传或拖拽图片到此处</p>
                            <p style="color: #9aa0a6; font-size: 12px; margin: 10px 0 0 0;">支持 .png, .jpg, .jpeg, .gif 格式，最多上传9张图片</p>
                            <input type="file" name="images[]" id="images" multiple accept=".png,.jpg,.jpeg,.gif" style="display: none;">
                        </div>
                        <div id="imagePreviewArea" style="margin-top: 15px;">
                            <!-- 图片预览将显示在这里 -->
                        </div>
                        <small>第一张图片将作为程序封面，所有图片将在程序详情页轮播展示</small>
                    </div>
                </div>

                <!-- 用户表单配置 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-list-alt"></i> 用户表单配置</div>
                    <div id="formFields">
                        <!-- 动态添加的表单字段将显示在这里 -->
                    </div>
                    <div class="add-btn-group">
                        <div class="btn-group">
                            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">
                                <i class="fas fa-plus"></i> 添加表单字段
                            </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addFormField('input')">文本输入框</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addFormField('password')">密码输入框</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addFormField('select')">下拉选择框</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addFormField('radio')">单选框</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addFormField('checkbox')">多选框</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addFormField('textarea')">多行文本框</a>
                            </div>
                        </div>
                    </div>
                    <small class="text-muted">配置用户在部署程序时需要填写的表单字段，系统会将 [sf_变量名] 替换为用户填写的内容</small>
                </div>

                <!-- 安装操作配置 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-cogs"></i> 安装操作配置</div>
                    <div id="installOperations">
                        <!-- 动态添加的安装操作将显示在这里 -->
                    </div>
                    <div class="add-btn-group">
                        <div class="btn-group">
                            <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">
                                <i class="fas fa-plus"></i> 添加安装操作
                            </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('newfile')">新建文件</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('newdir')">新建文件夹</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('delfile')">删除文件</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('deldir')">删除文件夹</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('editfile')">修改文件内容</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('importsql')">导入数据库文件</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('rename')">重命名文件/文件夹</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('setrewrite')">设置伪静态</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('setrundir')">设置运行目录</a>
                                <a class="dropdown-item" href="javascript:void(0)" onclick="addInstallOp('httpget')">GET请求</a>
                            </div>
                        </div>
                    </div>
                    <small class="text-muted">配置程序安装时需要执行的操作，系统将按照顺序依次执行</small>
                </div>

                <!-- 上架开关 -->
                <div class="form-section">
                    <div class="form-section-title"><i class="fas fa-toggle-on"></i> 上架设置</div>
                    <div class="form-group">
                        <label class="btn-block">是否上架</label>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <input type="checkbox" id="status" name="status" checked style="width: auto;">
                            <label for="status" style="margin: 0; font-weight: 400;">立即上架</label>
                        </div>
                        <small>关闭后程序将不会显示在程序列表中</small>
                    </div>
                </div>

                <button type="button" class="btn btn-primary btn-block" onclick="addcx(this)">
                    <i class="fas fa-plus"></i> 确认添加
                </button>

                <!-- 帮助说明 -->
                <div class="help-text">
                    <strong>替换符说明：</strong><br>
                    <code>[db_host]</code> - 数据库连接地址<br>
                    <code>[db_port]</code> - 数据库端口<br>
                    <code>[db_user]</code> - 数据库账号<br>
                    <code>[db_pass]</code> - 数据库密码<br>
                    <code>[db_name]</code> - 数据库名<br>
                    <code>[date]</code> - 安装时的时间<br>
                    <code>[sf_变量名]</code> - 用户填写的表单内容（如变量名为 admin，则使用 [sf_admin]）<br><br>
                    <strong>注意事项：</strong><br>
                    1. 根目录请填写 <code>/</code><br>
                    2. 文件名和目录不得出现特殊字符（如空格、{}、:"|<>? 等）<br>
                    3. 安装操作将按照添加顺序依次执行
                </div>
            </form>
        </div>
        
        <script>
        // 表单字段计数器
        var formFieldCount = 0;
        // 安装操作计数器
        var installOpCount = 0;

        // 添加表单字段
        function addFormField(type) {
            formFieldCount++;
            var html = '';
            var typeName = '';
            switch(type) {
                case 'input': typeName = '文本输入框'; break;
                case 'password': typeName = '密码输入框'; break;
                case 'select': typeName = '下拉选择框'; break;
                case 'radio': typeName = '单选框'; break;
                case 'checkbox': typeName = '多选框'; break;
                case 'textarea': typeName = '多行文本框'; break;
            }
            
            html += '<div class="dynamic-form-item" data-index="' + formFieldCount + '">';
            html += '<span class="remove-btn" onclick="removeFormField(' + formFieldCount + ')"><i class="fas fa-times-circle"></i></span>';
            html += '<div class="form-row">';
            html += '<div class="form-group">';
            html += '<label>字段类型</label>';
            html += '<input type="text" class="form-control" value="' + typeName + '" readonly>';
            html += '<input type="hidden" name="form_fields[' + formFieldCount + '][type]" value="' + type + '">';
            html += '</div>';
            html += '<div class="form-group">';
            html += '<label>变量名 <span style="color: red;">*</span></label>';
            html += '<input type="text" name="form_fields[' + formFieldCount + '][name]" class="form-control" placeholder="如：admin_user" required>';
            html += '</div>';
            html += '</div>';
            html += '<div class="form-group">';
            html += '<label>显示名称 <span style="color: red;">*</span></label>';
            html += '<input type="text" name="form_fields[' + formFieldCount + '][label]" class="form-control" placeholder="如：管理员账号" required>';
            html += '</div>';
            
            if (type === 'select' || type === 'radio' || type === 'checkbox') {
                html += '<div class="form-group">';
                html += '<label>选项（每行一个，格式：值|显示文本）</label>';
                html += '<textarea name="form_fields[' + formFieldCount + '][options]" class="form-control" rows="3" placeholder="如：&#10;admin|管理员&#10;user|普通用户"></textarea>';
                html += '</div>';
            }
            
            html += '<div class="form-group">';
            html += '<label>默认值</label>';
            html += '<input type="text" name="form_fields[' + formFieldCount + '][default]" class="form-control" placeholder="可选">';
            html += '</div>';
            html += '<div class="form-group">';
            html += '<label>提示文字</label>';
            html += '<input type="text" name="form_fields[' + formFieldCount + '][placeholder]" class="form-control" placeholder="可选">';
            html += '</div>';
            html += '<div style="margin-top: 10px;">';
            html += '<label style="display: flex; align-items: center; gap: 5px; font-weight: 400;">';
            html += '<input type="checkbox" name="form_fields[' + formFieldCount + '][required]" value="1" checked> 必填';
            html += '</label>';
            html += '</div>';
            html += '</div>';
            
            $('#formFields').append(html);
        }

        // 移除表单字段
        function removeFormField(index) {
            $('.dynamic-form-item[data-index="' + index + '"]').remove();
        }

        // 添加安装操作
        function addInstallOp(type) {
            installOpCount++;
            var html = '';
            var typeName = '';
            var fields = '';
            
            switch(type) {
                case 'newfile':
                    typeName = '新建文件';
                    fields = '<div class="form-group"><label>文件路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][path]" class="form-control" placeholder="如：/config.php" required></div>';
                    fields += '<div class="form-group"><label>文件内容</label><textarea name="install_ops[' + installOpCount + '][content]" class="form-control" rows="4" placeholder="文件内容（支持替换符）"></textarea></div>';
                    break;
                case 'newdir':
                    typeName = '新建文件夹';
                    fields = '<div class="form-group"><label>文件夹路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][path]" class="form-control" placeholder="如：/uploads" required></div>';
                    break;
                case 'delfile':
                    typeName = '删除文件';
                    fields = '<div class="form-group"><label>文件路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][path]" class="form-control" placeholder="如：/install.php" required></div>';
                    break;
                case 'deldir':
                    typeName = '删除文件夹';
                    fields = '<div class="form-group"><label>文件夹路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][path]" class="form-control" placeholder="如：/install" required></div>';
                    break;
                case 'editfile':
                    typeName = '修改文件内容';
                    fields = '<div class="form-group"><label>文件路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][path]" class="form-control" placeholder="如：/config.php" required></div>';
                    fields += '<div class="form-group"><label>查找内容 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][search]" class="form-control" placeholder="要查找的文本" required></div>';
                    fields += '<div class="form-group"><label>替换为 <span style="color: red;">*</span></label><textarea name="install_ops[' + installOpCount + '][replace]" class="form-control" rows="3" placeholder="替换后的内容（支持替换符）" required></textarea></div>';
                    break;
                case 'importsql':
                    typeName = '导入数据库文件';
                    fields = '<div class="form-group"><label>SQL文件路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][path]" class="form-control" placeholder="如：/database.sql" required></div>';
                    break;
                case 'rename':
                    typeName = '重命名文件/文件夹';
                    fields = '<div class="form-group"><label>原路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][old_path]" class="form-control" placeholder="如：/old_name" required></div>';
                    fields += '<div class="form-group"><label>新路径 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][new_path]" class="form-control" placeholder="如：/new_name" required></div>';
                    break;
                case 'setrewrite':
                    typeName = '设置伪静态';
                    fields = '<div class="form-group"><label>伪静态规则 <span style="color: red;">*</span></label><textarea name="install_ops[' + installOpCount + '][content]" class="form-control" rows="6" placeholder="伪静态规则内容" required></textarea></div>';
                    break;
                case 'setrundir':
                    typeName = '设置运行目录';
                    fields = '<div class="form-group"><label>运行目录 <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][path]" class="form-control" placeholder="如：/public" required></div>';
                    break;
                case 'httpget':
                    typeName = 'GET请求';
                    fields = '<div class="form-group"><label>请求URL <span style="color: red;">*</span></label><input type="text" name="install_ops[' + installOpCount + '][url]" class="form-control" placeholder="如：http://example.com/install.php?step=2" required></div>';
                    break;
            }
            
            html += '<div class="install-operation-item" data-index="' + installOpCount + '" data-type="' + type + '">';
            html += '<div class="op-header">';
            html += '<span class="op-type"><i class="fas fa-cog"></i> ' + typeName + '</span>';
            html += '<span class="remove-btn" onclick="removeInstallOp(' + installOpCount + ')"><i class="fas fa-times-circle"></i></span>';
            html += '</div>';
            html += '<input type="hidden" name="install_ops[' + installOpCount + '][op_type]" value="' + type + '">';
            html += fields;
            html += '</div>';
            
            $('#installOperations').append(html);
        }

        // 移除安装操作
        function removeInstallOp(index) {
            $('.install-operation-item[data-index="' + index + '"]').remove();
        }

        // 提交表单
        function addcx(btn) {
            var $btn = $(btn);
            var originalText = $btn.html();
            $btn.addClass('btn-loading').prop('disabled', true);
            
            try {
                var formData = new FormData($('#cxForm')[0]);
                formData.append('egn', 'addcx');
                
                // 收集表单字段配置
                var formFields = [];
                $('#formFields .dynamic-form-item').each(function() {
                    var field = {};
                    field.type = $(this).find('input[name*="[type]"]').val() || '';
                    field.name = $(this).find('input[name*="[name]"]').val() || '';
                    field.label = $(this).find('input[name*="[label]"]').val() || '';
                    field.placeholder = $(this).find('input[name*="[placeholder]"]').val() || '';
                    field.required = $(this).find('input[name*="[required]"]').is(':checked') ? 1 : 0;
                    field.options = $(this).find('textarea[name*="[options]"]').val() || '';
                    formFields.push(field);
                });
                formData.append('form_fields', JSON.stringify(formFields));
                
                // 收集安装操作配置
                var installOps = [];
                $('#installOperations .install-operation-item').each(function() {
                    var op = {};
                    op.type = $(this).data('type') || '';
                    op.path = $(this).find('input[name*="[path]"]').val() || '';
                    op.content = $(this).find('textarea[name*="[content]"]').val() || '';
                    op.search = $(this).find('input[name*="[search]"]').val() || '';
                    op.replace = $(this).find('textarea[name*="[replace]"]').val() || '';
                    op.old_path = $(this).find('input[name*="[old_path]"]').val() || '';
                    op.new_path = $(this).find('input[name*="[new_path]"]').val() || '';
                    op.url = $(this).find('input[name*="[url]"]').val() || '';
                    installOps.push(op);
                });
                formData.append('install_ops', JSON.stringify(installOps));
                
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: formData,
                    processData: false,
                    contentType: false,
                    dataType: 'json',
                    success: function(data) {
                        $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                        alert(data.code);
                        if(data.code == '添加成功') {
                            location.href = 'list.php?gn=cx';
                        }
                    },
                    error: function(xhr, status, error) {
                        $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                        alert('操作失败: ' + error + '\n请按F12查看控制台获取详细信息');
                    }
                });
            } catch (e) {
                console.error('JavaScript错误:', e);
                $btn.removeClass('btn-loading').prop('disabled', false).html(originalText);
                alert('页面脚本错误: ' + e.message);
            }
        }

        </script>
        
        <?php elseif ($gn == 'dr'):
        // 使用新的导入页面
        include 'add_dr_new.php';
        exit;
        endif; ?>
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
    <script src="js/admin.js"></script>
    
    <?php if ($gn == 'cx'): ?>
    <script>
    // 图片上传预览功能 - 在jQuery加载后执行
    $(function() {
        var selectedImages = [];
        
        // 点击上传区域
        $('#imageUploadArea').on('click', function(e) {
            // 如果点击的是input元素本身，不处理
            if (e.target.id === 'images') return;
            e.preventDefault();
            e.stopPropagation();
            document.getElementById('images').click();
        });
        
        // 拖拽事件
        $('#imageUploadArea').on('dragover', function(e) {
            e.preventDefault();
            $(this).css('border-color', '#1a73e8');
            $(this).css('background', '#e8f0fe');
        });
        
        $('#imageUploadArea').on('dragleave', function(e) {
            e.preventDefault();
            $(this).css('border-color', '#dadce0');
            $(this).css('background', '#f8f9fa');
        });
        
        $('#imageUploadArea').on('drop', function(e) {
            e.preventDefault();
            $(this).css('border-color', '#dadce0');
            $(this).css('background', '#f8f9fa');
            
            var files = e.originalEvent.dataTransfer.files;
            handleImageFiles(files);
        });
        
        // 文件选择变化
        $('#images').on('change', function() {
            handleImageFiles(this.files);
        });
        
        // 处理图片文件
        function handleImageFiles(files) {
            var currentCount = selectedImages.length;
            var remainingSlots = 9 - currentCount;
            
            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;
                }
                
                selectedImages.push(file);
                
                var reader = new FileReader();
                reader.onload = (function(theFile, index) {
                    return function(e) {
                        var html = '<div class="image-preview-item" data-index="' + (currentCount + 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-image" onclick="window.removeSelectedImage(' + (currentCount + 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 ((currentCount + 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>';
                        
                        $('#imagePreviewArea').append(html);
                    };
                })(file, i);
                
                reader.readAsDataURL(file);
            }
            
            updateImageInput();
        }
        
        // 删除图片
        window.removeSelectedImage = function(index) {
            selectedImages.splice(index, 1);
            $('.image-preview-item[data-index="' + index + '"]').remove();
            
            // 重新排序索引
            $('.image-preview-item').each(function(i) {
                $(this).attr('data-index', i);
                $(this).find('.remove-image').attr('onclick', 'window.removeSelectedImage(' + i + ')');
                if (i === 0) {
                    if ($(this).find('span:last-child').text() !== '封面') {
                        $(this).append('<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>');
                    }
                } else {
                    $(this).find('span:last-child').remove();
                }
            });
            
            updateImageInput();
        };
        
        // 更新文件输入
        function updateImageInput() {
            var dataTransfer = new DataTransfer();
            selectedImages.forEach(function(file) {
                dataTransfer.items.add(file);
            });
            $('#images')[0].files = dataTransfer.files;
        }
    });
    </script>
    <?php endif; ?>
</body>
</html>