<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */


$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$licenseCenterBaseUrl = 'http://yutou.wtbidc.cn/license-center';
$licenseCenterApiUrl = $licenseCenterBaseUrl . '/api.php';

if ($action === 'switch_template' && isset($_POST['legacy_template_switch'])) {
    $template_key = trim(isset($_POST['template_key']) ? $_POST['template_key'] : '');
    if (empty($template_key)) {
        echo '<script>alert("模板标识不能为空");history.back();</script>';
        exit;
    }
    // 下载模板zip包
    $zipUrl = $licenseCenterApiUrl . '?action=template_download&key=' . urlencode($template_key);
    $zipFile = tempnam(sys_get_temp_dir(), 'tpl_') . '.zip';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $zipUrl);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $zipContent = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_err = curl_error($ch);
    $curl_errno = curl_errno($ch);
    curl_close($ch);

    if (!$zipContent || $http_code !== 200) {
        echo '<script>alert("无法连接到授权平台");location.href="?act=template";</script>';
        exit;
    }

    // 判断是zip还是JSON错误
    if (strpos($zipContent, '{"code":') === 0) {
        $data = json_decode($zipContent, true);
        echo '<script>alert("' . (isset($data['msg']) ? $data['msg'] : '下载失败') . '");location.href="?act=template";</script>';
        exit;
    }

    // 保存zip并解压到 default 目录（替换现有文件）
    file_put_contents($zipFile, $zipContent);
    $extractDir = dirname(__DIR__, 2) . '/template/default/';
    if (!is_dir($extractDir)) {
        mkdir($extractDir, 0755, true);
    }
    // 清空default目录下的模板文件（保留目录结构）
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($extractDir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($iterator as $file) {
        $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
    }
    // 解压模板到default目录
    $zip = new ZipArchive();
    if ($zip->open($zipFile) === true) {
        // 检查第一层目录是否和模板key同名，若是则去掉该层再解压，否则直接解压全部
        $firstEntry = $zip->statIndex(0);
        $firstName = isset($firstEntry['name']) ? $firstEntry['name'] : '';
        if (strpos($firstName, '/') !== false) {
            $topDir = explode('/', $firstName)[0];
            if ($topDir === $template_key) {
                // 去掉顶层目录再解压
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $stat = $zip->statIndex($i);
                    $innerPath = implode('/', array_slice(explode('/', $stat['name']), 1));
                    if (!empty($innerPath)) {
                        $targetPath = $extractDir . $innerPath;
                        $dir = dirname($targetPath);
                        if (!is_dir($dir)) mkdir($dir, 0755, true);
                        file_put_contents($targetPath, $zip->getFromIndex($i));
                    }
                }
            } else {
                $zip->extractTo($extractDir);
            }
        } else {
            $zip->extractTo($extractDir);
        }
        $zip->close();
    }
    unlink($zipFile);

    // 始终写入 default，但记录当前激活的模板key（UPSERT）
    $db->update('config', ['config_value' => 'default'], 'config_key = ?', ['site_template']);
    $db->query("INSERT INTO {$db->table('config')} (config_key, config_value) VALUES ('last_template_key', ?) ON DUPLICATE KEY UPDATE config_value = ?", [$template_key, $template_key]);
    addLog('切换模板: ' . $template_key);
    echo '<script>alert("模板切换成功：' . htmlspecialchars($template_key) . '");location.href="?act=template";</script>';
    exit;
}

if ($action === 'list') {
    $license = $license->getStatus();
    $current_level = isset($license['level']) ? $license['level'] : 0;
    $level_filter = isset($_GET['level_filter']) ? trim($_GET['level_filter']) : 'all';
    $row = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'site_template'");
    $current_template_key = ($row && isset($row['config_value']) && $row['config_value'] !== '') ? $row['config_value'] : 'default';
    $lastRow = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'last_template_key'");
    if ($lastRow && isset($lastRow['config_value'])) {
        $current_template_key = $lastRow['config_value'];
    }
    $localTemplateBaseDir = dirname(__DIR__, 2) . '/template/';
    $installedTemplateKeys = [];
    if (is_dir($localTemplateBaseDir)) {
        foreach (glob($localTemplateBaseDir . '*', GLOB_ONLYDIR) as $dir) {
            $templateKey = basename($dir);
            if ($templateKey === 'default' || (isset($templateLoader) && $templateLoader->isInstalled($templateKey))) {
                $installedTemplateKeys[] = $templateKey;
            }
        }
    }

    $api_url = $licenseCenterApiUrl . '?action=template_list';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['level' => 999]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $template_list = [];
    $debug_info = '';
    if ($http_code == 200 && $response) {
        $data = json_decode($response, true);
        if (isset($data['templates']) && is_array($data['templates'])) {
            $template_list = $data['templates'];
        }
    }

    $levelNames = ['体验版', '免费版', '基础版', '专业版'];
    $templateLevelNames = [1 => '免费版', 2 => '基础版', 3 => '专业版'];
    $currentLevelName = isset($levelNames[$current_level]) ? $levelNames[$current_level] : '体验版';
    $templateFilters = [
        'all' => '所有模板',
        '1' => '免费版',
        '2' => '基础版',
        '3' => '专业版',
    ];
    $templateFilterCounts = [
        'all' => count($template_list),
        '1' => 0,
        '2' => 0,
        '3' => 0,
    ];
    foreach ($template_list as $tpl) {
        $requiredLevel = (string) (isset($tpl['required_level']) ? (int) $tpl['required_level'] : 1);
        if (isset($templateFilterCounts[$requiredLevel])) {
            $templateFilterCounts[$requiredLevel]++;
        }
    }
    if (!isset($templateFilters[$level_filter])) {
        $level_filter = 'all';
    }
    $display_template_list = array_values(array_filter($template_list, function ($tpl) use ($level_filter) {
        if ($level_filter === 'all') {
            return true;
        }

        return (int) (isset($tpl['required_level']) ? $tpl['required_level'] : 1) === (int) $level_filter;
    }));
    ?>
    <div class="page-container fade-in">
        <!-- 页面标题 -->
        <div class="page-header">
            <div>
                <h2><svg style="width:22px;height:22px;color:var(--primary);margin-right:8px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18.37 2.63L14 7l-1.59-1.59a2 2 0 0 0-2.82 0L8 7l9 9 1.59-1.59a2 2 0 0 0 0-2.82L17 10l4.37-4.37a2.12 2.12 0 1 0-3-3z"/></svg> 模板中心</h2>
                <p style="font-size:13px;color:var(--text-light);margin:4px 0 0 0;">从授权平台选择精品网站模板</p>
            </div>
            <div style="display:flex;gap:12px;align-items:center;">
                <div style="padding:8px 16px;background:var(--primary-bg);border-radius:var(--radius);display:flex;align-items:center;gap:8px;">
                    <svg style="width:22px;height:22px;color:var(--primary);" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 4l3 12h14l3-12-6 7-4-7-4 7-6-7z"/><path d="M5 16v4h14v-4"/></svg>
                    <span style="font-size:13px;font-weight:600;color:var(--primary);"><?php echo $currentLevelName; ?></span>
                </div>
            </div>
        </div>

        <!-- 统计信息 -->
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:24px;">
            <div class="stat-card">
                <div class="stat-header">
                    <div class="stat-label">全部模板</div>
                    <div class="stat-icon blue"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg></div>
                </div>
                <div class="stat-value"><?php echo count($template_list); ?></div>
                <div class="stat-change">当前显示 <?php echo count($display_template_list); ?> / <?php echo count($template_list); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-header">
                    <div class="stat-label">当前使用</div>
                    <div class="stat-icon green"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
                </div>
                <div class="stat-value" style="font-size:18px;"><?php echo htmlspecialchars($current_template_key); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-header">
                    <div class="stat-label">授权版本</div>
                    <div class="stat-icon orange"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg></div>
                </div>
                <div class="stat-value">V<?php echo $current_level; ?></div>
                <div class="stat-change"><?php echo $currentLevelName; ?></div>
            </div>
        </div>

        <div class="content-card" style="padding:16px 20px;margin-bottom:20px;">
            <div class="template-filter-bar">
                <?php foreach ($templateFilters as $filterValue => $filterLabel): ?>
                <a href="?act=template&level_filter=<?php echo urlencode($filterValue); ?>" class="template-filter-chip <?php echo $level_filter === $filterValue ? 'active' : ''; ?>">
                    <?php echo htmlspecialchars($filterLabel); ?>
                    <span class="template-filter-count"><?php echo isset($templateFilterCounts[$filterValue]) ? (int) $templateFilterCounts[$filterValue] : 0; ?></span>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if (empty($display_template_list)): ?>
        <!-- 空状态 -->
        <div class="content-card">
            <div class="empty-state" style="padding:80px 20px;">
                <svg style="width:56px;height:56px;color:var(--gray-300);margin-bottom:20px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                <h3 style="font-size:16px;color:var(--dark);margin-bottom:8px;">当前筛选下暂无模板</h3>
                <p style="font-size:14px;color:var(--text-light);margin:0;">请切换筛选项或检查授权平台服务是否正常</p>
            </div>
        </div>
        <?php else: ?>
        <!-- 模板卡片网格 -->
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:20px;">
            <?php foreach ($display_template_list as $tpl):
                $tpl_key = isset($tpl['template_key']) ? trim($tpl['template_key']) : '';
                $is_active = ($tpl_key === $current_template_key);
                $price = isset($tpl['price']) ? ($tpl['price'] == 0 ? '免费' : '¥' . $tpl['price']) : '免费';
                $is_free = isset($tpl['is_free']) && $tpl['is_free'] == 1;
                $category = isset($tpl['category']) ? $tpl['category'] : '通用';
                $thumbnail = isset($tpl['thumbnail']) ? $tpl['thumbnail'] : '';
                $description = isset($tpl['description']) ? $tpl['description'] : '';
                $required_level = isset($tpl['required_level']) ? $tpl['required_level'] : 1;
                $required_level_name = isset($templateLevelNames[$required_level]) ? $templateLevelNames[$required_level] : '免费版';
                $is_installed = in_array($tpl_key, $installedTemplateKeys, true);
                $is_locked = !$is_free && $required_level > $current_level;
            ?>
            <div class="template-card <?php echo $is_active ? 'active' : ''; ?> <?php echo $is_locked ? 'locked' : ''; ?>">
                <!-- 缩略图 -->
                <div class="template-thumb">
                    <?php if ($thumbnail): ?>
                    <img src="<?php echo htmlspecialchars($thumbnail); ?>" alt="<?php echo htmlspecialchars(isset($tpl['name']) ? $tpl['name'] : ''); ?>" onerror="this.style.display='none';this.nextElementSibling.style.display='flex';">
                    <?php endif; ?>
                    <div class="template-thumb-placeholder" style="<?php echo $thumbnail ? 'display:none;' : ''; ?>">
                        <svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18.37 2.63L14 7l-1.59-1.59a2 2 0 0 0-2.82 0L8 7l9 9 1.59-1.59a2 2 0 0 0 0-2.82L17 10l4.37-4.37a2.12 2.12 0 1 0-3-3z"/></svg>
                    </div>
                    <?php if ($is_active): ?>
                    <div class="template-badge active-badge">
                        <svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> 使用中
                    </div>
                    <?php elseif ($is_locked): ?>
                    <div class="template-badge lock-badge">
                        <svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg> 需升级
                    </div>
                    <?php endif; ?>
                </div>
                <!-- 信息 -->
                <div class="template-info">
                    <div class="template-header">
                        <h3 class="template-name"><?php echo htmlspecialchars(isset($tpl['name']) ? $tpl['name'] : $tpl['template_key']); ?></h3>
                        <span class="badge badge-<?php echo $is_free ? 'success' : 'primary'; ?>" style="font-size:11px;">
                            <?php echo $is_free ? '免费' : $price; ?>
                        </span>
                    </div>
                    <div class="template-meta">
                        <span><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg> <?php echo htmlspecialchars($category); ?></span>
                        <span><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg> <?php echo htmlspecialchars($required_level_name); ?>模板</span>
                    </div>
                    <?php if ($description): ?>
                    <p class="template-desc"><?php echo htmlspecialchars($description); ?></p>
                    <?php endif; ?>
                    <!-- 操作 -->
                    <div class="template-actions">
                        <?php if ($is_active): ?>
                        <button class="btn btn-sm" disabled style="background:var(--gray-100);color:var(--gray-400);cursor:not-allowed;width:100%;">
                            <svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> 当前使用
                        </button>
                        <?php elseif ($is_locked): ?>
                        <a href="/admin/main.php?act=auth" class="btn btn-sm upgrade-btn" style="width:100%;text-align:center;">
                            <svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg> 升级解锁
                        </a>
                        <?php elseif ($is_installed): ?>
                        <form method="post" action="?act=template&action=switch_template" style="margin:0;" class="template-switch-form">
                            <input type="hidden" name="action" value="switch_template">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                            <input type="hidden" name="template_key" value="<?php echo htmlspecialchars($tpl['template_key']); ?>">
                            <button type="submit" class="btn btn-primary btn-sm" style="width:100%;">
                                <svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> 启用此模板
                            </button>
                        </form>
                        <?php else: ?>
                        <form method="post" action="?act=template&action=switch_template" style="margin:0;" class="template-switch-form">
                            <input type="hidden" name="action" value="switch_template">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                            <input type="hidden" name="template_key" value="<?php echo htmlspecialchars($tpl['template_key']); ?>">
                            <button type="submit" class="btn btn-secondary btn-sm" style="width:100%;">
                                <svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> 下载并启用
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
    <style>
        .template-card {
            background: var(--white);
            border-radius: var(--radius-lg);
            overflow: hidden;
            border: 1px solid var(--border-light);
            box-shadow: var(--shadow-xs);
            transition: var(--transition);
        }
        .template-card:hover {
            box-shadow: var(--shadow);
            transform: translateY(-4px);
            border-color: var(--primary-light);
        }
        .template-card.active {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.1);
        }
        .template-card.locked {
            opacity: 0.92;
            border-color: rgba(245, 158, 11, 0.38);
            box-shadow: 0 0 0 1px rgba(245, 158, 11, 0.12);
        }
        .template-thumb {
            position: relative;
            height: 160px;
            background: linear-gradient(135deg, var(--gray-50), var(--gray-100));
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
        .template-thumb img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            background: #f8fafc;
        }
        .template-thumb-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #eef4ff, #f5f8ff);
            color: var(--primary);
            font-size: 48px;
        }
        .template-badge {
            position: absolute;
            top: 12px;
            right: 12px;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .active-badge {
            background: var(--primary);
            color: #fff;
        }
        .lock-badge {
            background: linear-gradient(135deg, #dc2626, #f59e0b);
            color: #fff;
            box-shadow: 0 10px 24px rgba(220, 38, 38, 0.28);
        }
        .template-info {
            padding: 16px;
        }
        .template-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
        .template-name {
            font-size: 15px;
            font-weight: 600;
            color: var(--dark);
            margin: 0;
        }
        .template-meta {
            display: flex;
            gap: 16px;
            font-size: 12px;
            color: var(--text-light);
            margin-bottom: 10px;
        }
        .template-meta span {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .template-desc {
            font-size: 13px;
            color: var(--text-light);
            margin: 0 0 12px 0;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        .template-actions {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid var(--border-light);
        }
        .upgrade-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            background: linear-gradient(135deg, #dc2626, #f59e0b);
            color: #fff !important;
            border: 0;
            border-radius: 12px;
            font-weight: 700;
            letter-spacing: 0.02em;
            box-shadow: 0 14px 30px rgba(220, 38, 38, 0.24);
            transition: transform 0.2s ease, box-shadow 0.2s ease, filter 0.2s ease;
        }
        .upgrade-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 18px 34px rgba(220, 38, 38, 0.3);
            filter: saturate(1.08);
        }
        .upgrade-btn svg {
            flex: 0 0 auto;
        }
        .template-filter-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }
        .template-filter-chip {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            min-width: 88px;
            padding: 10px 16px;
            border-radius: 999px;
            border: 1px solid var(--border);
            background: var(--white);
            color: var(--text);
            font-size: 13px;
            font-weight: 600;
            text-decoration: none;
            transition: var(--transition);
        }
        .template-filter-chip:hover {
            border-color: var(--primary);
            color: var(--primary);
            background: var(--primary-bg);
        }
        .template-filter-chip.active {
            background: var(--primary);
            border-color: var(--primary);
            color: #fff;
            box-shadow: 0 8px 20px rgba(22, 93, 255, 0.16);
        }
        .template-filter-count {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 22px;
            height: 22px;
            padding: 0 6px;
            border-radius: 999px;
            background: rgba(15, 23, 42, 0.08);
            color: inherit;
            font-size: 12px;
            line-height: 1;
        }
        .template-filter-chip.active .template-filter-count {
            background: rgba(255, 255, 255, 0.2);
        }
    </style>
    <script>
    document.querySelectorAll('.template-switch-form').forEach(function(form) {
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            var submitButton = form.querySelector('button[type="submit"]');
            var originalText = submitButton ? submitButton.innerHTML : '';
            var submitUrl = form.getAttribute('action') || window.location.href;
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.innerHTML = '处理中...';
            }

            fetch(submitUrl, {
                method: 'POST',
                body: new FormData(form),
                credentials: 'same-origin'
            })
            .then(function(response) {
                return response.text();
            })
            .then(function(text) {
                var result = null;
                try {
                    result = JSON.parse(text);
                } catch (error) {
                    throw new Error(text || '模板操作失败');
                }

                if (parseInt(result.code || 0, 10) === 200) {
                    alert('模板操作成功');
                    window.location.href = '?act=template';
                    return;
                }

                alert(result.msg || '模板操作失败');
            })
            .catch(function(error) {
                alert(error.message || '模板操作失败');
            })
            .finally(function() {
                if (submitButton) {
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalText;
                }
            });
        });
    });
    </script>
    <?php
}

if ($action === 'download' && isset($_GET['legacy_download'])) {
    $template_key = trim(isset($_GET['key']) ? $_GET['key'] : '');
    if (empty($template_key)) {
        echo json_encode(['code' => 400, 'msg' => '模板标识不能为空']);
        exit;
    }
    $result = @file_get_contents($licenseCenterApiUrl . '?action=template_download&key=' . urlencode($template_key));
    if ($result) {
        $data = json_decode($result, true);
        if (isset($data['code']) && $data['code'] == 200) {
            echo json_encode(['code' => 200, 'msg' => '下载成功']);
        } else {
            echo json_encode(['code' => 400, 'msg' => (isset($data['msg']) ? $data['msg'] : '下载失败')]);
        }
    } else {
        echo json_encode(['code' => 400, 'msg' => '无法连接到授权平台']);
    }
    exit;
}
?>
