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

$user = check_user();
$bt = $DB->get_row("SELECT * FROM `bt` WHERE `id`='{$user['btid']}'");

// 获取所有分类
$categories = array();
$cat_res = $DB->query("SELECT * FROM `program_categories` ORDER BY `sort_order` ASC, `id` ASC");
while ($cat = $DB->fetch($cat_res)) {
    $categories[] = $cat;
}

// 获取当前选中的分类
$selected_category = isset($_GET['category']) ? trim($_GET['category']) : '';

// 获取所有已上架的程序
$programs = array();
if ($selected_category) {
    $selected_category_sql = daddslashes($selected_category);
    $prog_res = $DB->query("SELECT * FROM `bs` WHERE `status`=1 AND `type`='{$selected_category_sql}' ORDER BY `id` DESC");
} else {
    $prog_res = $DB->query("SELECT * FROM `bs` WHERE `status`=1 ORDER BY `id` DESC");
}
while ($prog = $DB->fetch($prog_res)) {
    $programs[] = $prog;
}

// 获取用户已购买的程序
$purchased_programs = array();
$purchases_res = $DB->query("SELECT bs_id FROM `bs_purchase` WHERE `uid`='{$user['id']}' AND `status`=1");
while ($p = $DB->fetch($purchases_res)) {
    $purchased_programs[$p['bs_id']] = true;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo L('one_click_deploy', 'menu'); ?> - <?php echo $conf['name']; ?></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">
</head>
<body>
    <div class="content-area" style="margin-left: 0; padding: 20px;">
        <div class="card">
            <h3><i class="fas fa-rocket"></i> <?php echo L('one_click_deploy', 'menu'); ?></h3>
            <p class="text-muted"><?php echo L('deploy_desc', 'menu'); ?></p>
            
            <!-- 分类筛选 -->
            <div class="category-filter-wrapper mb-4">
                <!-- 手机版：下拉选择 -->
                <div class="category-filter-mobile d-md-none">
                    <select class="form-control form-control-sm" onchange="location.href=this.value||'deploy.php'">
                        <option value="deploy.php" <?php echo empty($selected_category) ? 'selected' : ''; ?>><?php echo L('all', 'common'); ?></option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="deploy.php?category=<?php echo urlencode($cat['name']); ?>" <?php echo $selected_category == $cat['name'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- 桌面版：按钮组 -->
                <div class="category-filter d-none d-md-block">
                    <div class="btn-group btn-group-sm" role="group">
                        <a href="deploy.php" class="btn <?php echo empty($selected_category) ? 'btn-primary' : 'btn-outline-primary'; ?>">
                            <?php echo L('all', 'common'); ?>
                        </a>
                        <?php foreach ($categories as $cat): ?>
                        <a href="deploy.php?category=<?php echo urlencode($cat['name']); ?>" class="btn <?php echo $selected_category == $cat['name'] ? 'btn-primary' : 'btn-outline-primary'; ?>">
                            <?php echo htmlspecialchars($cat['name']); ?>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            
            <div class="row" id="program-list">
                <?php foreach ($programs as $program): ?>
                <?php
                $images = array();
                if (!empty($program['images'])) {
                    $images = json_decode($program['images'], true);
                    if (!is_array($images)) $images = array();
                }
                $cover = !empty($images) ? $images[0] : (!empty($program['cover']) ? $program['cover'] : '');
                ?>
                <div class="col-md-4 col-lg-3 mb-4">
                    <div class="program-card card h-100" data-id="<?php echo $program['id']; ?>">
                        <div class="program-image" style="height: 150px; overflow: hidden; position: relative; cursor: pointer;" onclick="showProgramImages(<?php echo $program['id']; ?>, '<?php echo htmlspecialchars($program['name']); ?>')">
                            <?php if ($cover): ?>
                            <img src="/uploads/<?php echo htmlspecialchars($cover); ?>" class="card-img-top program-cover-img" style="width: 100%; height: 100%; object-fit: cover;" alt="<?php echo htmlspecialchars($program['name']); ?>" data-images='<?php echo json_encode($images); ?>' data-cover="<?php echo htmlspecialchars($cover); ?>">
                            <?php else: ?>
                            <div class="d-flex align-items-center justify-content-center h-100 bg-light">
                                <i class="fas fa-box fa-3x text-muted"></i>
                            </div>
                            <?php endif; ?>
                            <div class="program-type-badge" style="position: absolute; top: 10px; left: 10px;">
                                <span class="badge badge-info"><?php echo htmlspecialchars($program['type']); ?></span>
                            </div>
                            <?php if ($cover): ?>
                            <div class="image-overlay" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.3); opacity: 0; transition: opacity 0.3s; display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-search-plus" style="color: white; font-size: 24px;"></i>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="card-body">
                            <h5 class="card-title text-truncate" title="<?php echo htmlspecialchars($program['name']); ?>"><?php echo htmlspecialchars($program['name']); ?></h5>
                            <p class="card-text text-muted small" style="height: 40px; overflow: hidden;">
                                <?php echo htmlspecialchars(mb_substr($program['js'], 0, 50)) . '...'; ?>
                            </p>
                            <div class="program-meta mb-2">
                                <small class="text-muted">
                                    <i class="fas fa-globe"></i> <?php echo $program['webkj']; ?>MB
                                    <i class="fas fa-database ml-2"></i> <?php echo $program['sqlkj']; ?>MB
                                </small>
                            </div>
                            <div class="program-version mb-2">
                                <small class="text-muted"><?php echo L('version', 'menu'); ?>: <?php echo htmlspecialchars($program['version']); ?></small>
                            </div>
                            <?php if (!empty($program['php_version'])): ?>
                            <div class="program-php mb-2">
                                <small class="text-muted">PHP: <?php echo htmlspecialchars($program['php_version']); ?></small>
                            </div>
                            <?php endif; ?>
                            <?php
                            $price = floatval($program['jg']);
                            $is_purchased = isset($purchased_programs[$program['id']]) || $price <= 0;
                            ?>
                            <!-- Debug: price=<?php echo $price; ?>, jg=<?php echo htmlspecialchars($program['jg']); ?>, is_purchased=<?php echo $is_purchased ? '1' : '0'; ?> -->
                            <div class="program-price mt-2">
                                <?php if ($is_purchased): ?>
                                    <span class="badge badge-success"><i class="fas fa-check"></i> <?php echo $price > 0 ? L('purchased', 'menu') : L('free', 'menu'); ?></span>
                                <?php else: ?>
                                    <span class="badge badge-warning"><i class="fas fa-coins"></i> <?php echo L('price', 'menu'); ?>: ¥<?php echo number_format($price, 2); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="card-footer bg-transparent p-2">
                            <div class="program-card-actions d-flex" style="gap: 8px;">
                                <button type="button" class="btn btn-outline-info btn-view-detail flex-fill" 
                                    data-id="<?php echo $program['id']; ?>"
                                    data-name="<?php echo htmlspecialchars($program['name']); ?>"
                                    data-js="<?php echo htmlspecialchars($program['js']); ?>"
                                    data-type="<?php echo htmlspecialchars($program['type']); ?>"
                                    data-version="<?php echo htmlspecialchars($program['version']); ?>"
                                    data-webkj="<?php echo $program['webkj']; ?>"
                                    data-sqlkj="<?php echo $program['sqlkj']; ?>"
                                    data-php="<?php echo htmlspecialchars($program['php_version']); ?>"
                                    data-ext="<?php echo htmlspecialchars($program['php_ext']); ?>"
                                    data-images="<?php echo htmlspecialchars($program['images']); ?>"
                                    data-cover="<?php echo htmlspecialchars($cover); ?>"
                                    data-price="<?php echo $price; ?>"
                                    data-form-fields="<?php echo htmlspecialchars($program['form_fields']); ?>"
                                    data-purchased="<?php echo $is_purchased ? '1' : '0'; ?>">
                                    <i class="fas fa-eye"></i> <?php echo L('view_detail', 'menu'); ?>
                                </button>
                                <?php if ($is_purchased): ?>
                                <button type="button" class="btn btn-primary btn-deploy flex-fill" 
                                    data-id="<?php echo $program['id']; ?>" 
                                    data-name="<?php echo htmlspecialchars($program['name']); ?>"
                                    data-form-fields="<?php echo htmlspecialchars($program['form_fields']); ?>">
                                    <i class="fas fa-rocket"></i> <?php echo L('deploy_now', 'menu'); ?>
                                </button>
                                <?php else: ?>
                                <button type="button" class="btn btn-warning btn-buy flex-fill" data-id="<?php echo $program['id']; ?>" data-name="<?php echo htmlspecialchars($program['name']); ?>" data-price="<?php echo $price; ?>">
                                    <i class="fas fa-shopping-cart"></i> <?php echo L('buy_now', 'menu'); ?>
                                </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <?php if (empty($programs)): ?>
            <div class="text-center py-5">
                <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
                <p class="text-muted"><?php echo L('no_programs', 'menu'); ?></p>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- 程序详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document" style="max-width: 800px; margin: 30px auto;">
            <div class="modal-content" style="border-radius: 6px; overflow: hidden; border: none; box-shadow: 0 4px 20px rgba(0,0,0,0.15);">
                <!-- 头部 -->
                <div class="modal-header" style="background: #fff; border-bottom: 1px solid #e8eaed; padding: 16px 20px;">
                    <h5 class="modal-title" id="detailModalLabel" style="color: #202124; font-weight: 500; font-size: 14px;">
                        <i class="fas fa-info-circle" style="color: #188038; margin-right: 8px;"></i><?php echo L('program_detail', 'menu'); ?>
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: #5f6368; opacity: 1;">
                        <span aria-hidden="true" style="font-size: 22px;">&times;</span>
                    </button>
                </div>
                
                <!-- 内容区域 -->
                <div class="modal-body" style="padding: 20px; max-height: 80vh; overflow-y: auto; background: #f8f9fa;">
                    <!-- 信息区域 -->
                    <div style="background: #fff; border-radius: 6px; padding: 20px;">
                        <!-- 标题和类型 -->
                        <div class="text-center mb-4">
                            <h3 id="detail-name" style="margin: 0 0 10px 0; font-weight: 500; color: #202124; font-size: 18px;"></h3>
                            <span class="badge" id="detail-type" style="font-size: 11px; padding: 4px 12px; border-radius: 4px; background: #e8f5e9; color: #188038; font-weight: 500;"></span>
                        </div>
                        
                        <!-- 描述 -->
                        <div class="program-description" style="background: #f8f9fa; padding: 16px; border-radius: 6px; margin-bottom: 20px; border-left: 3px solid #188038;">
                            <p class="mb-0" id="detail-js" style="line-height: 1.7; color: #5f6368; font-size: 13px;"></p>
                        </div>
                        
                        <!-- 技术规格 -->
                        <div class="program-specs" style="background: #fff; border: 1px solid #dadce0; border-radius: 6px; padding: 16px; margin-bottom: 20px;">
                            <h6 style="margin-bottom: 14px; color: #202124; font-weight: 500; font-size: 13px;">
                                <i class="fas fa-cog" style="color: #188038; margin-right: 6px;"></i>技术规格
                            </h6>
                            <div class="row">
                                <div class="col-sm-4 col-6 mb-3">
                                    <div style="color: #5f6368; font-size: 12px; margin-bottom: 3px;"><?php echo L('version', 'menu'); ?></div>
                                    <div id="detail-version" style="font-weight: 500; color: #202124; font-size: 13px;"></div>
                                </div>
                                <div class="col-sm-4 col-6 mb-3">
                                    <div style="color: #5f6368; font-size: 12px; margin-bottom: 3px;"><?php echo L('web_space', 'menu'); ?></div>
                                    <div id="detail-webkj" style="font-weight: 500; color: #202124; font-size: 13px;"></div>
                                </div>
                                <div class="col-sm-4 col-6 mb-3">
                                    <div style="color: #5f6368; font-size: 12px; margin-bottom: 3px;"><?php echo L('db_space', 'menu'); ?></div>
                                    <div id="detail-sqlkj" style="font-weight: 500; color: #202124; font-size: 13px;"></div>
                                </div>
                                <div class="col-sm-4 col-6 mb-3">
                                    <div style="color: #5f6368; font-size: 12px; margin-bottom: 3px;">PHP 版本</div>
                                    <div id="detail-php" style="font-weight: 500; color: #202124; font-size: 13px;"></div>
                                </div>
                                <div class="col-sm-8 col-12">
                                    <div style="color: #5f6368; font-size: 12px; margin-bottom: 3px;"><?php echo L('php_ext', 'menu'); ?></div>
                                    <div id="detail-ext" style="font-weight: 500; color: #202124; font-size: 13px;"></div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 按钮区域 -->
                        <div class="d-flex justify-content-center" style="gap: 10px;">
                            <button type="button" class="btn btn-sm" data-dismiss="modal" style="background: #f1f3f4; color: #5f6368; border: none; padding: 8px 20px; border-radius: 4px; font-weight: 500; font-size: 13px;">
                                <i class="fas fa-times" style="margin-right: 4px;"></i><?php echo L('close', 'menu'); ?>
                            </button>
                            <button type="button" class="btn btn-sm" id="detail-deploy-btn" style="background: #188038; color: white; border: none; padding: 8px 24px; border-radius: 4px; font-weight: 500; font-size: 13px;">
                                <i class="fas fa-rocket" style="margin-right: 4px;"></i><?php echo L('deploy_now', 'menu'); ?>
                            </button>
                            <button type="button" class="btn btn-sm" id="detail-buy-btn" style="display: none; background: #ea4335; color: white; border: none; padding: 8px 24px; border-radius: 4px; font-weight: 500; font-size: 13px;">
                                <i class="fas fa-shopping-cart" style="margin-right: 4px;"></i><?php echo L('buy_now', 'menu'); ?> <span id="detail-price"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 程序图片展示模态框 -->
    <div class="modal fade" id="imageGalleryModal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document" style="max-width: 1000px !important; width: 85vw !important; margin: 40px auto !important;">
            <div class="modal-content" style="max-width: none !important; width: 100% !important; max-height: none !important;">
                <div class="modal-header">
                    <h5 class="modal-title" id="gallery-program-name"></h5>
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body" id="gallery-body" style="padding: 20px; display: flex; justify-content: center;">
                    <!-- 轮播内容将动态插入 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 购买确认模态框 -->
    <div class="modal fade" id="buyModal" tabindex="-1" role="dialog" aria-labelledby="buyModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="buyModalLabel"><?php echo L('confirm_purchase', 'menu'); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p><?php echo L('purchase_confirm_text', 'menu'); ?>: <strong id="buy-program-name"></strong></p>
                    <p class="text-danger font-weight-bold"><?php echo L('price', 'menu'); ?>: ¥<span id="buy-program-price"></span></p>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> <?php echo L('purchase_info', 'menu'); ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                    <button type="button" class="btn btn-warning" id="confirm-buy"><?php echo L('confirm_purchase', 'menu'); ?></button>
                </div>
            </div>
        </div>
    </div>
    


    <!-- 部署确认模态框 -->
    <div class="modal fade" id="deployModal" tabindex="-1" role="dialog" aria-labelledby="deployModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deployModalLabel"><?php echo L('confirm_deploy', 'menu'); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p><?php echo L('deploy_confirm_text', 'menu'); ?>: <strong id="deploy-program-name"></strong></p>
                    
                    <!-- 动态表单字段区域 -->
                    <div id="deploy-form-fields" style="display: none;">
                        <hr>
                        <h6><i class="fas fa-edit"></i> <?php echo L('form_config', 'menu'); ?></h6>
                        <p class="text-muted small"><?php echo L('form_config_desc', 'menu'); ?></p>
                        <div id="form-fields-container">
                            <!-- 表单字段将动态插入这里 -->
                        </div>
                    </div>
                    
                    <div class="alert alert-warning mt-3">
                        <i class="fas fa-exclamation-triangle"></i> <?php echo L('deploy_warning', 'menu'); ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo L('cancel', 'common'); ?></button>
                    <button type="button" class="btn btn-primary" id="confirm-deploy"><?php echo L('confirm', 'common'); ?></button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
    <script>
    $(document).ready(function() {
        var selectedProgramId = null;
        var currentProgramFormFields = null;
        // 显示程序图片轮播 - 与后台保持一致
        window.showProgramImages = function(programId, programName) {
            var $card = $('.program-card[data-id="' + programId + '"]');
            var $img = $card.find('.program-cover-img');
            var images = $img.attr('data-images');
            var cover = $img.data('cover');

            var imageArray = [];
            if (images) {
                try {
                    var imgArray = JSON.parse(images);
                    if (Array.isArray(imgArray) && imgArray.length > 0) {
                        imageArray = imgArray;
                    }
                } catch(e) {}
            }
            if (imageArray.length === 0 && cover) {
                imageArray = [cover];
            }
            if (imageArray.length === 0) return;

            // 构建轮播HTML - 横屏宽屏居中放大，自动轮换
            var carouselHtml = '<div id="imageCarousel" class="carousel slide" data-ride="carousel" data-interval="3000" style="width: 100%;">';

            // 指示器
            carouselHtml += '<ol class="carousel-indicators">';
            for (var i = 0; i < imageArray.length; i++) {
                carouselHtml += '<li data-target="#imageCarousel" data-slide-to="' + i + '"' + (i === 0 ? ' class="active"' : '') + '></li>';
            }
            carouselHtml += '</ol>';

            // 图片项 - 横屏显示居中放大
            carouselHtml += '<div class="carousel-inner">';
            for (var i = 0; i < imageArray.length; i++) {
                carouselHtml += '<div class="carousel-item' + (i === 0 ? ' active' : '') + '" style="text-align: center;">';
                carouselHtml += '<img src="/uploads/' + imageArray[i] + '" style="max-width: 100%; max-height: 800px; width: auto; height: auto; object-fit: contain; background: #f8f9fa;">';
                carouselHtml += '</div>';
            }
            carouselHtml += '</div>';

            // 控制按钮
            if (imageArray.length > 1) {
                carouselHtml += '<a class="carousel-control-prev" href="#imageCarousel" role="button" data-slide="prev">';
                carouselHtml += '<span class="carousel-control-prev-icon"></span>';
                carouselHtml += '</a>';
                carouselHtml += '<a class="carousel-control-next" href="#imageCarousel" role="button" data-slide="next">';
                carouselHtml += '<span class="carousel-control-next-icon"></span>';
                carouselHtml += '</a>';
            }

            carouselHtml += '</div>';

            // 设置标题和内容
            $('#gallery-program-name').text(programName + ' (' + imageArray.length + '张)');
            $('#gallery-body').html(carouselHtml);

            $('#imageGalleryModal').modal('show');

            // 启动轮播自动轮换
            $('#imageCarousel').carousel({
                interval: 3000,
                wrap: true
            });
        };

        // 图片悬停效果
        $('.program-image').hover(
            function() {
                $(this).find('.image-overlay').css('opacity', '1');
            },
            function() {
                $(this).find('.image-overlay').css('opacity', '0');
            }
        );

        // 点击查看详情按钮（支持 touch + click，解决部分手机无法响应的问题）
        var _lastDetailTap = 0;
        $(document).on('click touchend', '.btn-view-detail', function(e) {
            if (e.type === 'touchend') e.preventDefault();
            var now = Date.now();
            if (now - _lastDetailTap < 400) return;
            _lastDetailTap = now;
            var $btn = $(this);
            var $btn = $(this);
            selectedProgramId = $btn.data('id');
            currentProgramFormFields = $btn.data('form-fields');
            
            // 填充详情数据
            $('#detail-name').text($btn.data('name'));
            $('#detail-type').text($btn.data('type'));
            $('#detail-js').text($btn.data('js'));
            $('#detail-version').text($btn.data('version'));
            $('#detail-webkj').text($btn.data('webkj') + ' MB');
            $('#detail-sqlkj').text($btn.data('sqlkj') + ' MB');
            $('#detail-php').text($btn.data('php') || '-');
            $('#detail-ext').text($btn.data('ext') || '-');

            // 根据购买状态显示不同按钮
            var isPurchased = $btn.data('purchased') === '1';
            var price = parseFloat($btn.data('price'));
            
            if (isPurchased) {
                $('#detail-deploy-btn').show();
                $('#detail-buy-btn').hide();
            } else {
                $('#detail-deploy-btn').hide();
                $('#detail-buy-btn').show();
                $('#detail-price').text('¥' + price.toFixed(2));
            }
            
            $('#detailModal').modal('show');
        });

        // 从详情弹窗点击部署
        $('#detail-deploy-btn').on('click', function() {
            $('#detailModal').modal('hide');
            var programName = $('#detail-name').text();
            $('#deploy-program-name').text(programName);
            
            // 处理表单字段
            renderFormFields(currentProgramFormFields);
            
            $('#deployModal').modal('show');
        });
        
        // 从详情弹窗点击购买
        $('#detail-buy-btn').on('click', function() {
            $('#detailModal').modal('hide');
            var programName = $('#detail-name').text();
            var price = $('#detail-price').text();
            $('#buy-program-name').text(programName);
            $('#buy-program-price').text(price.replace('¥', ''));
            $('#buyModal').modal('show');
        });
        
        // 点击查看详情按钮（支持 touch）
        var _lastViewTap = 0;
        $(document).on('click touchend', '.btn-view-detail', function(e) {
            console.log('查看详情按钮被点击', e.type, $(this).data('id'));
            if (e.type === 'touchend') {
                e.preventDefault();
                if (Date.now() - _lastViewTap < 400) return;
                _lastViewTap = Date.now();
            }
            // 原有的点击处理逻辑保持不变
        });
        
        var _lastDeployTap = 0;
        // 点击部署按钮（支持 touch）
        $(document).on('click touchend', '.btn-deploy', function(e) {
            console.log('部署按钮被点击', e.type, $(this).data('id'));
            if (e.type === 'touchend') {
                e.preventDefault();
                if (Date.now() - _lastDeployTap < 400) return;
                _lastDeployTap = Date.now();
            }
            selectedProgramId = $(this).data('id');
            var programName = $(this).data('name');
            var formFields = $(this).data('form-fields');
            
            $('#deploy-program-name').text(programName);
            
            // 处理表单字段
            renderFormFields(formFields);
            
            $('#deployModal').modal('show');
        });

        var _lastBuyTap = 0;
        $(document).on('click touchend', '.btn-buy', function(e) {
            if (e.type === 'touchend') e.preventDefault();
            if (e.type === 'touchend' && Date.now() - _lastBuyTap < 400) return;
            if (e.type === 'touchend') _lastBuyTap = Date.now();
            selectedProgramId = $(this).data('id');
            var programName = $(this).data('name');
            var price = $(this).data('price');
            $('#buy-program-name').text(programName);
            $('#buy-program-price').text(typeof price === 'number' ? price.toFixed(2) : price);
            $('#buyModal').modal('show');
        });
        
        // 渲染表单字段
        function renderFormFields(formFields) {
            var $container = $('#form-fields-container');
            var $wrapper = $('#deploy-form-fields');
            
            $container.empty();
            
            // 检查formFields是否为空或无效
            if (!formFields || formFields === '' || formFields === 'null' || formFields === 'undefined') {
                $wrapper.hide();
                return;
            }
            
            try {
                var fields = JSON.parse(formFields);
                if (!Array.isArray(fields) || fields.length === 0) {
                    $wrapper.hide();
                    return;
                }
                
                var html = '';
                fields.forEach(function(field, index) {
                    var fieldName = field.name || 'field_' + index;
                    var fieldLabel = field.label || fieldName;
                    var fieldType = field.type || 'text';
                    var fieldRequired = field.required ? 'required' : '';
                    var fieldPlaceholder = field.placeholder || '';
                    var fieldDefault = field.default || '';
                    
                    html += '<div class="form-group">';
                    html += '<label for="form_field_' + fieldName + '">' + fieldLabel + (field.required ? ' <span class="text-danger">*</span>' : '') + '</label>';
                    
                    if (fieldType === 'textarea') {
                        html += '<textarea name="form_fields[' + fieldName + ']" id="form_field_' + fieldName + '" class="form-control" rows="3" placeholder="' + fieldPlaceholder + '" ' + fieldRequired + '>' + fieldDefault + '</textarea>';
                    } else if (fieldType === 'select' && field.options) {
                        html += '<select name="form_fields[' + fieldName + ']" id="form_field_' + fieldName + '" class="form-control" ' + fieldRequired + '>';
                        field.options.forEach(function(opt) {
                            var selected = (opt.value === fieldDefault) ? 'selected' : '';
                            html += '<option value="' + opt.value + '" ' + selected + '>' + opt.label + '</option>';
                        });
                        html += '</select>';
                    } else {
                        html += '<input type="' + fieldType + '" name="form_fields[' + fieldName + ']" id="form_field_' + fieldName + '" class="form-control" placeholder="' + fieldPlaceholder + '" value="' + fieldDefault + '" ' + fieldRequired + '>';
                    }
                    
                    if (field.description) {
                        html += '<small class="form-text text-muted">' + field.description + '</small>';
                    }
                    
                    html += '</div>';
                });
                
                $container.html(html);
                $wrapper.show();
            } catch (e) {
                console.error('解析表单字段失败:', e);
                $wrapper.hide();
            }
        }
        
        // 确认购买
        $('#confirm-buy').on('click', function() {
            if (!selectedProgramId) return;
            
            var $btn = $(this);
            $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> <?php echo L('processing', 'menu'); ?>');
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: {
                    egn: 'purchase_program',
                    program_id: selectedProgramId
                },
                dataType: 'json',
                success: function(data) {
                    $('#buyModal').modal('hide');
                    if (data.status === true || data.code === 'success') {
                        alert('<?php echo L('purchase_success', 'menu'); ?>');
                        location.reload();
                    } else if (data.msg && data.msg.indexOf('余额') >= 0) {
                        if (confirm(data.msg + '。<?php echo L('goto_recharge', 'menu'); ?>?')) {
                            window.location.href = 'pay.php';
                        }
                    } else {
                        alert(data.msg || '<?php echo L('purchase_failed', 'menu'); ?>');
                    }
                },
                error: function() {
                    alert('<?php echo L('network_error', 'menu'); ?>');
                },
                complete: function() {
                    $btn.prop('disabled', false).html('<?php echo L('confirm_purchase', 'menu'); ?>');
                }
            });
        });
        
        // 确认部署
        $('#confirm-deploy').on('click', function() {
            if (!selectedProgramId) return;
            
            var $btn = $(this);
            $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> <?php echo L('deploying', 'menu'); ?>');
            
            // 收集表单字段数据
            var formData = {
                egn: 'deploy_program',
                program_id: selectedProgramId
            };
            
            // 如果有表单字段，收集它们的值
            // 使用 form_fields 对象来存储表单字段数据
            var formFieldsData = {};
            $('#form-fields-container input, #form-fields-container textarea, #form-fields-container select').each(function() {
                var name = $(this).attr('name');
                var value = $(this).val();
                if (name) {
                    // 提取字段名（从 form_fields[field_name] 中提取 field_name）
                    var match = name.match(/form_fields\[(.+?)\]/);
                    if (match) {
                        formFieldsData[match[1]] = value;
                    }
                }
            });
            
            // 如果有表单字段数据，添加到 formData
            if (Object.keys(formFieldsData).length > 0) {
                formData.form_fields = formFieldsData;
            }
            
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: formData,
                dataType: 'json',
                timeout: 300000, // 5分钟超时
                success: function(data) {
                    $('#deployModal').modal('hide');
                    if (data.code === 0 || data.code === 'success' || data.status === true || data.status === 'success') {
                        alert('<?php echo L('deploy_success', 'menu'); ?>');
                    } else {
                        alert(data.msg || '<?php echo L('deploy_failed', 'menu'); ?>');
                    }
                },
                error: function(xhr, status, error) {
                    if (status === 'timeout') {
                        alert('请求超时，请稍后查看部署状态');
                    } else {
                        var errorMsg = '<?php echo L('network_error', 'menu'); ?>';
                        if (error) errorMsg += ': ' + error;
                        if (xhr.status) errorMsg += ' (HTTP ' + xhr.status + ')';
                        if (xhr.responseText) {
                            try {
                                var resp = JSON.parse(xhr.responseText);
                                if (resp.msg || resp.code) {
                                    errorMsg += '\n' + (resp.msg || resp.code);
                                }
                            } catch(e) {
                                if (xhr.responseText.length < 200) {
                                    errorMsg += '\n' + xhr.responseText;
                                }
                            }
                        }
                        alert(errorMsg);
                    }
                },
                complete: function() {
                    $btn.prop('disabled', false).html('<?php echo L('confirm', 'menu'); ?>');
                }
            });
        });
    });
    </script>
</body>
</html>
