<?php
/**
 * 古籍管理页面，包含Tab栏功能
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

class AncientTextAdminPage {
    
    public function __construct() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('admin_print_footer_scripts', array($this, 'admin_footer_scripts'));
        add_action('wp_ajax_load_chapter_edit_form', array($this, 'load_chapter_edit_form'));
        add_action('wp_ajax_save_chapter', array($this, 'save_chapter'));
        add_action('wp_ajax_create_chapter', array($this, 'create_chapter'));
        add_action('wp_ajax_delete_chapter', array($this, 'delete_chapter'));
        add_action('wp_ajax_test_ajax', array($this, 'test_ajax'));
        
        // 添加调试信息
        error_log('AncientTextAdminPage constructor called');
    }
    
    /**
     * 测试AJAX功能
     */
    public function test_ajax() {
        error_log('Test AJAX function called');
        wp_die('Test AJAX working');
    }
    
    /**
     * 添加管理菜单
     */
    public function add_admin_menu() {
        add_menu_page(
            '古籍管理',
            '古籍管理',
            'manage_options',
            'chinese_ancient_text',
            array($this, 'display_admin_page'),
            'dashicons-book',
            6
        );
    }
    
    /**
     * 加载脚本和样式
     */
    public function enqueue_scripts($hook) {
        // 只在古籍管理页面加载
        if ($hook !== 'toplevel_page_chinese_ancient_text') {
            return;
        }
        
        // 加载编辑器相关脚本
        wp_enqueue_editor();
        wp_enqueue_media();
        
        // 可以在这里添加需要的CSS和JS
        wp_enqueue_style('ancient-text-admin-css', plugin_dir_url(__FILE__) . '../assets/admin.css');
        wp_enqueue_script('ancient-text-admin-js', plugin_dir_url(__FILE__) . '../assets/admin.js', array('jquery'), '1.0', true);
        
        // 传递AJAX URL到JavaScript
        wp_localize_script('ancient-text-admin-js', 'ajax_object', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('chapter_edit_nonce')
        ));
    }
    
    /**
     * 在页脚添加编辑器初始化脚本
     */
    public function admin_footer_scripts() {
        global $pagenow;
        
        // 只在古籍管理页面添加
        if ($pagenow !== 'admin.php' || !isset($_GET['page']) || $_GET['page'] !== 'chinese_ancient_text') {
            return;
        }
        ?>
        <script>
        jQuery(document).ready(function($) {
            // 确保编辑器相关脚本已加载
            if (typeof tinymce !== 'undefined') {
                // 编辑器配置 - 增强版配置
                var editorSettings = {
                    quicktags: true,
                    tinymce: {
                        plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,code,media,image,anchor,advlist,autoresize,insertdatetime,searchreplace,visualblocks,visualchars',
                        toolbar1: "formatselect,bold,italic,underline,strikethrough,bullist,numlist,blockquote,alignleft,aligncenter,alignright,justifyleft,justifycenter,justifyright,justifyfull,link,unlink,wp_more,table,image,anchor",
                        toolbar2: "outdent,indent,forecolor,backcolor,pastetext,removeformat,charmap,hr,searchreplace,visualblocks,visualchars,undo,redo,code,fullscreen,help"
                    },
                    mediaButtons: true
                };
                
                // 初始化编辑器函数
                window.initializeChapterEditor = function() {
                    if (typeof tinymce !== 'undefined' && $('#chapter_content').length) {
                        // 移除现有编辑器实例
                        if (tinymce.get('chapter_content')) {
                            tinymce.remove('#chapter_content');
                        }
                        
                        // 初始化新的编辑器
                        // 初始化编辑器并添加自动调整高度功能
            wp.editor.initialize('chapter_content', editorSettings);
            
            // 添加自动调整编辑器高度的插件
            if (typeof tinymce !== 'undefined') {
                tinymce.PluginManager.add('autoresize', function(editor) {
                    function resize() {
                        var contentHeight = editor.dom.getStyle(editor.getDoc().documentElement, 'height', true);
                        editor.iframeElement.style.height = (parseInt(contentHeight) + 20) + 'px';
                    }
                    
                    editor.on('init keyup setcontent change', resize);
                    editor.on('init', function() {
                        editor.iframeElement.style.transition = 'height 0.2s';
                    });
                });
                
                // 如果编辑器已存在，重新初始化时确保使用增强配置
                if (tinymce.get('chapter_content')) {
                    tinymce.get('chapter_content').settings.plugins += ',autoresize';
                    tinymce.get('chapter_content').settings.toolbar3 = 'autoresize';
                }
            }
                    }
                };
            }
        });
        </script>
        <?php
    }
    
    /**
     * AJAX处理函数：加载章节编辑表单
     */
    public function load_chapter_edit_form() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'chapter_edit_nonce')) {
            wp_die('安全验证失败');
        }
        
        // 获取章节ID
        $chapter_id = intval($_POST['chapter_id']);
        
        // 获取章节数据
        $chapter = get_post($chapter_id);
        if (!$chapter || $chapter->post_type !== 'ancient_text_chapter') {
            wp_die('章节不存在');
        }
        
        // 获取章节元数据
        $ancient_text_id = get_post_meta($chapter_id, '_chapter_ancient_text', true);
        $volume = get_post_meta($chapter_id, '_chapter_volume', true);
        $chapter_number = get_post_meta($chapter_id, '_chapter_number', true);
        
        // 获取所有古籍
        $ancient_texts = get_posts(array(
            'post_type' => 'chinese_ancient_text',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        // 输出HTML表单
        ?>
        <h2>编辑章节</h2>
        <form id="chapter-edit-form" data-chapter-id="<?php echo $chapter_id; ?>">
            <div class="form-field">
                <label for="chapter_title">章节标题</label>
                <input type="text" id="chapter_title" name="chapter_title" value="<?php echo esc_attr($chapter->post_title); ?>">
            </div>
            
            <div class="form-field">
                <label for="chapter_ancient_text">所属古籍</label>
                <select id="chapter_ancient_text" name="chapter_ancient_text">
                    <option value="">请选择关联的古籍</option>
                    <?php foreach ($ancient_texts as $ancient_text): ?>
                        <option value="<?php echo $ancient_text->ID; ?>" <?php selected($ancient_text_id, $ancient_text->ID); ?>>
                            <?php echo esc_html($ancient_text->post_title); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="form-field">
                <label for="chapter_volume">卷数</label>
                <input type="text" id="chapter_volume" name="chapter_volume" value="<?php echo esc_attr($volume); ?>">
            </div>
            
            <div class="form-field">
                <label for="chapter_number">章节编号</label>
                <input type="text" id="chapter_number" name="chapter_number" value="<?php echo esc_attr($chapter_number); ?>">
            </div>
            
            <div class="form-field">
                <label for="chapter_status">章节状态</label>
                <select id="chapter_status" name="chapter_status">
                    <option value="draft" <?php selected($chapter->post_status, 'draft'); ?>>草稿</option>
                    <option value="publish" <?php selected($chapter->post_status, 'publish'); ?>>已发布</option>
                    <option value="private" <?php selected($chapter->post_status, 'private'); ?>>私有</option>
                </select>
            </div>
            
            <div class="form-field">
                <label for="chapter_content">章节内容</label>
                <?php 
                // 使用WordPress默认的编辑器设置
                wp_editor($chapter->post_content, 'chapter_content', array(
                    'textarea_name' => 'chapter_content',
                    'textarea_rows' => 20,
                    //'media_buttons' => true,
                    'teeny' => false
                    //'quicktags' => true,
                    //'drag_drop_upload' => true
                )); 
                ?>
            </div>
            
            <div class="submit-buttons">
                <button type="button" class="button button-primary" id="save-chapter-button">保存章节</button>
                <button type="button" class="button button-secondary" id="publish-chapter-button">发布章节</button>
                <button type="button" class="button" id="preview-chapter-button">预览</button>
                <a href="<?php echo admin_url('post.php?post=' . $chapter_id . '&action=edit'); ?>" class="button" target="_blank">在新页面编辑</a>
                <?php 
                // 添加查看已发布章节的链接
                $chapter_permalink = get_permalink($chapter_id);
                if ($chapter_permalink): ?>
                    <a href="<?php echo esc_url($chapter_permalink); ?>" class="button" target="_blank">查看已发布章节</a>
                <?php endif; ?>
                
                <?php if (current_user_can('edit_posts')): ?>
                    <button type="button" class="button" id="view-annotations-button">查看批注</button>
                <?php endif; ?>
            </div>
            
            <?php if (current_user_can('edit_posts')): ?>
                <div id="annotations-section" style="display:none; margin-top: 20px;">
                    <h3>章节批注</h3>
                    <?php
                    // 获取章节批注
                    $annotations = get_comments(array(
                        'post_id' => $chapter_id,
                        'meta_key' => 'is_annotation',
                        'meta_value' => '1',
                        'orderby' => 'comment_date',
                        'order' => 'ASC'
                    ));
                    
                    if (!empty($annotations)):
                        foreach ($annotations as $annotation):
                            $selected_text = get_comment_meta($annotation->comment_ID, 'selected_text', true);
                            ?>
                            <div class="annotation-item" style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; background: #f9f9f9;">
                                <div class="annotation-content">
                                    <?php echo wp_kses_post($annotation->comment_content); ?>
                                </div>
                                <?php if (!empty($selected_text)): ?>
                                    <div class="annotation-selected-text" style="margin-top: 5px; padding: 5px; background: #ffffcc; border: 1px solid #ddd;">
                                        <strong>选中文本：</strong><?php echo esc_html($selected_text); ?>
                                    </div>
                                <?php endif; ?>
                                <div class="annotation-meta" style="font-size: 0.9em; color: #666; margin-top: 5px;">
                                    <span class="annotation-author"><?php echo esc_html($annotation->comment_author); ?></span>
                                    <span class="annotation-date"><?php echo esc_html(get_comment_date('Y-m-d H:i', $annotation->comment_ID)); ?></span>
                                    <?php if (current_user_can('edit_comment', $annotation->comment_ID)): ?>
                                        <a href="#" class="edit-annotation-admin" data-annotation-id="<?php echo esc_attr($annotation->comment_ID); ?>" style="margin-left: 10px;">编辑</a>
                                        <a href="#" class="delete-annotation-admin" data-annotation-id="<?php echo esc_attr($annotation->comment_ID); ?>" style="margin-left: 10px; color: #d63638;">删除</a>
                                    <?php endif; ?>
                                    <!-- 添加批注锚点链接 -->
                                    <?php
                                    $annotation_link = get_permalink($chapter_id) . '?mode=reading#annotation-' . $annotation->comment_ID;
                                    ?>
                                    <a href="<?php echo esc_url($annotation_link); ?>" target="_blank" style="margin-left: 10px;">引用链接</a>
                                    <a href="#" class="copy-annotation-link-admin" data-annotation-id="<?php echo esc_attr($annotation->comment_ID); ?>" style="margin-left: 10px;">复制链接</a>
                                </div>
                            </div>
                        <?php
                        endforeach;
                    else:
                        echo '<p>暂无批注</p>';
                    endif;
                    ?>
                    
                    <div class="add-annotation-form-admin" style="margin-top: 20px; padding: 15px; border: 1px solid #ddd; background: #f5f5f5;">
                        <h4>添加批注</h4>
                        <textarea id="admin-annotation-content" placeholder="请输入批注内容" style="width: 100%; min-height: 100px; padding: 8px;"></textarea>
                        <input type="hidden" id="admin-annotation-selection" value="">
                        <div style="margin-top: 10px;">
                            <button type="button" class="button button-primary" id="save-annotation-admin">保存批注</button>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </form>
        
        <script>
        jQuery(document).ready(function($) {
            // 查看批注按钮
            $('#view-annotations-button').on('click', function() {
                $('#annotations-section').toggle();
            });
            
            // 保存批注
            $('#save-annotation-admin').on('click', function() {
                var content = $('#admin-annotation-content').val().trim();
                var selection = $('#admin-annotation-selection').val();
                
                if (!content) {
                    alert('请输入批注内容');
                    return;
                }
                
                var data = {
                    action: 'add_chapter_annotation',
                    chapter_id: <?php echo $chapter_id; ?>,
                    content: content,
                    selection: selection,
                    nonce: '<?php echo wp_create_nonce('add_annotation_nonce'); ?>'
                };
                
                $.post(ajaxurl, data, function(response) {
                    if (response.success) {
                        alert('批注保存成功');
                        location.reload();
                    } else {
                        alert('保存失败: ' + response.data.message);
                    }
                });
            });
            
            // 编辑批注
            $('.edit-annotation-admin').on('click', function(e) {
                e.preventDefault();
                var annotationId = $(this).data('annotation-id');
                var annotationContent = $(this).closest('.annotation-item').find('.annotation-content').text();
                
                var newContent = prompt('编辑批注:', annotationContent);
                if (newContent !== null && newContent.trim() !== '') {
                    var data = {
                        action: 'edit_chapter_annotation',
                        annotation_id: annotationId,
                        content: newContent,
                        nonce: '<?php echo wp_create_nonce('edit_annotation_nonce'); ?>'
                    };
                    
                    $.post(ajaxurl, data, function(response) {
                        if (response.success) {
                            alert('批注更新成功');
                            location.reload();
                        } else {
                            alert('更新失败: ' + response.data.message);
                        }
                    });
                }
            });
            
            // 删除批注
            $('.delete-annotation-admin').on('click', function(e) {
                e.preventDefault();
                var annotationId = $(this).data('annotation-id');
                
                if (confirm('确定要删除这条批注吗？')) {
                    var data = {
                        action: 'delete_chapter_annotation',
                        annotation_id: annotationId,
                        nonce: '<?php echo wp_create_nonce('delete_annotation_nonce'); ?>'
                    };
                    
                    $.post(ajaxurl, data, function(response) {
                        if (response.success) {
                            alert('批注删除成功');
                            location.reload();
                        } else {
                            alert('删除失败: ' + response.data.message);
                        }
                    });
                }
            });
            
            // 复制批注链接
            $('.copy-annotation-link-admin').on('click', function(e) {
                e.preventDefault();
                var annotationId = $(this).data('annotation-id');
                var link = '<?php echo esc_url(get_permalink($chapter_id)); ?>?mode=reading#annotation-' + annotationId;
                
                // 使用Clipboard API复制链接
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(link).then(function() {
                        // 显示成功提示
                        var originalText = $('.copy-annotation-link-admin[data-annotation-id="' + annotationId + '"]').text();
                        $('.copy-annotation-link-admin[data-annotation-id="' + annotationId + '"]').text('已复制');
                        setTimeout(function() {
                            $('.copy-annotation-link-admin[data-annotation-id="' + annotationId + '"]').text(originalText);
                        }, 2000);
                    }).catch(function(err) {
                        console.error('复制失败:', err);
                        // 降级到传统方法
                        fallbackCopyTextToClipboard(link);
                    });
                } else {
                    // 降级到传统方法
                    fallbackCopyTextToClipboard(link);
                }
            });
            
            // 传统复制方法（兼容旧浏览器）
            function fallbackCopyTextToClipboard(text) {
                var textArea = document.createElement("textarea");
                textArea.value = text;
                textArea.style.position = "fixed";  //avoid scrolling to bottom
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();
                
                try {
                    var successful = document.execCommand('copy');
                    if (successful) {
                        alert('链接已复制到剪贴板');
                    } else {
                        alert('复制失败，请手动复制链接');
                    }
                } catch (err) {
                    console.error('复制失败:', err);
                    alert('复制失败，请手动复制链接');
                }
                
                document.body.removeChild(textArea);
            }
            
            // 在编辑器中选择文本添加批注
            if (typeof tinymce !== 'undefined' && tinymce.get('chapter_content')) {
                tinymce.get('chapter_content').on('mouseup', function(e) {
                    var editor = tinymce.get('chapter_content');
                    var selectedText = editor.selection.getContent({format: 'text'}).trim();
                    
                    if (selectedText.length > 0) {
                        $('#admin-annotation-selection').val(selectedText);
                    }
                });
            }
        });
        </script>
        <?php
        
        // 确保编辑器脚本正确输出
        _WP_Editors::editor_js();
        
        wp_die(); // 必须有这个结束语句
    }
    
    /**
     * AJAX处理函数：保存章节
     */
    public function save_chapter() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'chapter_edit_nonce')) {
            wp_die('安全验证失败');
        }
        
        // 检查权限
        if (!current_user_can('edit_posts')) {
            wp_die('权限不足');
        }
        
        // 获取数据
        $chapter_id = intval($_POST['chapter_id']);
        $title = sanitize_text_field($_POST['title']);
        $content = wp_kses_post($_POST['content']);
        $ancient_text_id = intval($_POST['ancient_text_id']);
        $volume = sanitize_text_field($_POST['volume']);
        $chapter_number = sanitize_text_field($_POST['chapter_number']);
        $status = sanitize_text_field($_POST['status']);
        
        // 更新章节文章
        $updated = wp_update_post(array(
            'ID' => $chapter_id,
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => $status
        ));
        
        if (is_wp_error($updated)) {
            wp_die('保存失败: ' . $updated->get_error_message());
        }
        
        // 更新元数据
        update_post_meta($chapter_id, '_chapter_ancient_text', $ancient_text_id);
        update_post_meta($chapter_id, '_chapter_volume', $volume);
        update_post_meta($chapter_id, '_chapter_number', $chapter_number);
        
        echo '保存成功';
        wp_die();
    }
    
    /**
     * AJAX处理函数：创建新章节
     */
    public function create_chapter() {
        // 记录调试信息
        error_log('Create chapter function called');
        error_log('POST data: ' . print_r($_POST, true));
        
        // 防止重复执行的检查
        static $already_run = false;
        if ($already_run) {
            error_log('Create chapter function already run in this request');
            wp_die('创建章节失败: 重复请求');
        }
        $already_run = true;
        
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'chapter_edit_nonce')) {
            error_log('Nonce verification failed');
            wp_die('安全验证失败');
        }
        
        // 检查权限
        if (!current_user_can('edit_posts')) {
            error_log('Insufficient permissions');
            wp_die('权限不足');
        }
        
        // 获取数据
        $ancient_text_id = intval($_POST['ancient_text_id']);
        error_log('Ancient text ID: ' . $ancient_text_id);
        
        // 检查古籍是否存在
        $ancient_text = get_post($ancient_text_id);
        error_log('Ancient text post: ' . print_r($ancient_text, true));
        
        if (!$ancient_text) {
            error_log('Ancient text not found: ' . $ancient_text_id);
            wp_die('指定的古籍不存在: ' . $ancient_text_id);
        }
        
        if ($ancient_text->post_type !== 'chinese_ancient_text') {
            error_log('Invalid post type: ' . $ancient_text->post_type);
            wp_die('指定的文章不是古籍类型: ' . $ancient_text->post_type);
        }
        
        // 计算新章节的序号
        $chapter_count = get_posts(array(
            'post_type' => 'ancient_text_chapter',
            'post_status' => 'any',
            'meta_query' => array(
                array(
                    'key' => '_chapter_ancient_text',
                    'value' => $ancient_text_id,
                    'compare' => '='
                )
            ),
            'numberposts' => -1,
            'fields' => 'ids'
        ));
        
        $next_chapter_number = count($chapter_count) + 1;
        
        // 创建新章节
        $chapter_post = array(
            'post_title'   => '章节 ' . $next_chapter_number,
            'post_content' => '',
            'post_status'  => 'draft',
            'post_type'    => 'ancient_text_chapter',
            'post_author'  => get_current_user_id(),
        );
        
        error_log('Creating chapter with data: ' . print_r($chapter_post, true));
        $chapter_id = wp_insert_post($chapter_post, true); // 添加true参数以在出错时返回WP_Error对象
        error_log('Chapter creation result: ' . print_r($chapter_id, true));
        
        if (is_wp_error($chapter_id)) {
            error_log('Chapter creation failed: ' . $chapter_id->get_error_message());
            wp_die('创建章节失败: ' . $chapter_id->get_error_message());
        }
        
        if (!$chapter_id) {
            error_log('Chapter creation returned false');
            wp_die('创建章节失败: 未知错误');
        }
        
        // 设置章节关联的古籍
        $meta_result = update_post_meta($chapter_id, '_chapter_ancient_text', $ancient_text_id);
        error_log('Chapter meta update result: ' . print_r($meta_result, true));
        
        // 设置章节编号
        update_post_meta($chapter_id, '_chapter_number', $next_chapter_number);
        
        // 返回新章节ID
        echo $chapter_id;
        wp_die();
    }
    
    /**
     * AJAX处理函数：删除章节
     */
    public function delete_chapter() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'chapter_edit_nonce')) {
            wp_die('安全验证失败');
        }
        
        // 检查权限
        if (!current_user_can('delete_posts')) {
            wp_die('权限不足');
        }
        
        // 获取章节ID
        $chapter_id = intval($_POST['chapter_id']);
        
        // 检查章节是否存在
        $chapter = get_post($chapter_id);
        if (!$chapter || $chapter->post_type !== 'ancient_text_chapter') {
            wp_die('章节不存在');
        }
        
        // 删除章节
        $result = wp_delete_post($chapter_id, true);
        
        if ($result) {
            echo 'success';
        } else {
            echo '删除失败';
        }
        
        wp_die();
    }
    
    /**
     * 显示管理页面
     */
    public function display_admin_page() {
        // 获取当前标签页
        $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'overview';
        ?>
        <div class="wrap">
            <h1>古籍管理</h1>
            
            <h2 class="nav-tab-wrapper">
                <a href="?page=chinese_ancient_text&tab=overview" class="nav-tab <?php echo $active_tab == 'overview' ? 'nav-tab-active' : ''; ?>">概览</a>
                <a href="?page=chinese_ancient_text&tab=manage" class="nav-tab <?php echo $active_tab == 'manage' ? 'nav-tab-active' : ''; ?>">古籍管理</a>
                <a href="?page=chinese_ancient_text&tab=chapters" class="nav-tab <?php echo $active_tab == 'chapters' ? 'nav-tab-active' : ''; ?>">章节管理</a>
                <a href="?page=chinese_ancient_text&tab=settings" class="nav-tab <?php echo $active_tab == 'settings' ? 'nav-tab-active' : ''; ?>">设置</a>
            </h2>
            
            <div class="tab-content">
                <?php
                switch ($active_tab) {
                    case 'manage':
                        $this->display_manage_tab();
                        break;
                    case 'chapters':
                        $this->display_chapters_tab();
                        break;
                    case 'settings':
                        $this->display_settings_tab();
                        break;
                    case 'overview':
                    default:
                        $this->display_overview_tab();
                        break;
                }
                ?>
            </div>
        </div>
        
        <style>
        .nav-tab-wrapper {
            margin-bottom: 20px;
        }
        
        .tab-content {
            background: #fff;
            padding: 20px;
            border: 1px solid #c3c4c7;
            border-top: none;
        }
        
        .tab-content h2 {
            margin-top: 0;
        }
        
        .tab-content .manage-links {
            display: flex;
            gap: 20px;
            margin: 20px 0;
        }
        
        .tab-content .manage-link {
            flex: 1;
            text-align: center;
            padding: 20px;
            border: 1px solid #ddd;
            background: #f9f9f9;
            border-radius: 5px;
            text-decoration: none;
            color: #333;
            transition: all 0.3s ease;
        }
        
        .tab-content .manage-link:hover {
            background: #e9e9e9;
            border-color: #999;
        }
        
        .tab-content .manage-link h3 {
            margin-top: 0;
        }
        
        .tab-content .manage-link p {
            color: #666;
        }
        
        .breadcrumb {
            margin-bottom: 20px;
            padding: 10px 0;
            border-bottom: 1px solid #ddd;
        }
        
        .breadcrumb a {
            text-decoration: none;
            color: #0073aa;
        }
        
        .breadcrumb a:hover {
            text-decoration: underline;
        }
        
        .tab-content table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .tab-content table th,
        .tab-content table td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .tab-content table th {
            background: #f1f1f1;
        }
        
        .tab-content .button {
            background: #0073aa;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        
        .tab-content .button:hover {
            background: #005a87;
        }
        
        .tab-content .pagination {
            margin-top: 20px;
            text-align: center;
        }
        
        .tab-content .pagination a,
        .tab-content .pagination span {
            display: inline-block;
            padding: 5px 10px;
            margin: 0 2px;
            text-decoration: none;
            border: 1px solid #ddd;
            color: #0073aa;
        }
        
        .tab-content .pagination a:hover {
            background: #f1f1f1;
        }
        
        .tab-content .pagination .current {
            background: #0073aa;
            color: white;
        }
        
        /* 章节管理专用样式 */
        .chapter-manager {
            display: flex;
            gap: 20px;
            height: 700px;
        }
        
        .chapter-list-panel {
            flex: 1;
            border: 1px solid #ddd;
            background: #f9f9f9;
            overflow-y: auto;
            padding: 10px;
        }
        
        .chapter-edit-panel {
            flex: 2;
            border: 1px solid #ddd;
            background: #fff;
            padding: 20px;
            overflow-y: auto;
        }
        
        .chapter-list-panel h3 {
            margin-top: 0;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }
        
        .chapter-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .chapter-item:hover {
            background: #e9e9e9;
        }
        
        .chapter-item.active {
            background: #0073aa;
            color: white;
        }
        
        .chapter-item .chapter-title {
            font-weight: bold;
        }
        
        .chapter-item .chapter-meta {
            font-size: 0.9em;
            color: #666;
        }
        
        .chapter-item.active .chapter-meta {
            color: #ccc;
        }
        
        .chapter-edit-panel .form-field {
            margin-bottom: 15px;
        }
        
        .chapter-edit-panel .form-field label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .chapter-edit-panel .form-field input,
        .chapter-edit-panel .form-field textarea,
        .chapter-edit-panel .form-field select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .chapter-edit-panel .form-field textarea {
            min-height: 200px;
        }
        
        .chapter-edit-panel .submit-buttons {
            margin-top: 20px;
        }
        
        .chapter-edit-panel .submit-buttons .button {
            margin-right: 10px;
        }
        
        .no-chapter-selected {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #999;
        }
        
        .notice {
            background: #fff;
            border-left: 4px solid #ffb900;
            padding: 12px 16px;
            margin: 10px 0;
        }
        
        .notice-warning {
            border-left-color: #ffb900;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        
        /* 确保编辑器正确显示 */
        .wp-editor-wrap {
            margin: 10px 0;
        }
        
        .wp-editor-container {
            border: 1px solid #ddd;
        }
        
        .wp-editor-area {
            width: 100%;
            margin: 0;
        }
        </style>
        
        <script>
        // 章节管理JavaScript
        jQuery(document).ready(function($) {
            // 确保只绑定一次事件
            if (typeof window.chapterEventsBound === 'undefined') {
                window.chapterEventsBound = true;
                
                // 点击章节项目
                $(document).on('click', '.chapter-item', function() {
                    $('.chapter-item').removeClass('active');
                    $(this).addClass('active');
                    
                    // 获取章节ID
                    var chapterId = $(this).data('chapter-id');
                    
                    // 显示加载状态
                    $('.chapter-edit-panel').html('<div class="loading">加载中...</div>');
                    
                    // 通过AJAX加载章节编辑表单
                    $.post(ajax_object.ajax_url, {
                        action: 'load_chapter_edit_form',
                        chapter_id: chapterId,
                        nonce: ajax_object.nonce
                    }, function(response) {
                        $('.chapter-edit-panel').html(response);
                        
                        // 初始化WordPress编辑器
                        if (typeof window.initializeChapterEditor !== 'undefined') {
                            window.initializeChapterEditor();
                        } else if (typeof tinymce !== 'undefined') {
                            // 备用方案
                            if (tinymce.get('chapter_content')) {
                                tinymce.remove('#chapter_content');
                            }
                            wp.editor.initialize('chapter_content', {
                                quicktags: true,
                                tinymce: {
                                    toolbar1: "formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,wp_more",
                                    toolbar2: "strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo"
                                }
                            });
                        }
                        
                        // 绑定保存按钮事件
                        $('#save-chapter-button').off('click').on('click', function() {
                            saveChapter(chapterId);
                        });
                    }).fail(function(xhr, status, error) {
                        $('.chapter-edit-panel').html('<div class="error">加载失败: ' + error + '</div>');
                    });
                });
                
                // 保存章节
                function saveChapter(chapterId) {
                    // 获取表单数据
                    var title = $('#chapter_title').val();
                    var content = $('#chapter_content').val();
                    
                    // 检查是否使用可视化编辑器并且编辑器已初始化
                    if (typeof tinymce !== 'undefined' && tinymce.get('chapter_content')) {
                        content = tinymce.get('chapter_content').getContent();
                    } else if (typeof wp !== 'undefined' && wp.editor && wp.editor.getContent) {
                        content = wp.editor.getContent('chapter_content');
                    }
                    
                    var ancientTextId = $('#chapter_ancient_text').val();
                    var volume = $('#chapter_volume').val();
                    var chapterNumber = $('#chapter_number').val();
                    var status = $('#chapter_status').val();
                    
                    // 显示保存状态
                    $('#save-chapter-button').prop('disabled', true).text('保存中...');
                    
                    // 通过AJAX保存章节
                    $.post(ajax_object.ajax_url, {
                        action: 'save_chapter',
                        chapter_id: chapterId,
                        title: title,
                        content: content,
                        ancient_text_id: ancientTextId,
                        volume: volume,
                        chapter_number: chapterNumber,
                        status: status,
                        nonce: ajax_object.nonce
                    }, function(response) {
                        // 恢复按钮状态
                        $('#save-chapter-button').prop('disabled', false).text('保存章节');
                        
                        // 显示保存结果
                        alert(response);
                    }).fail(function(xhr, status, error) {
                        // 恢复按钮状态
                        $('#save-chapter-button').prop('disabled', false).text('保存章节');
                        alert('保存失败: ' + error);
                    });
                }
                
                // 发布章节
                $(document).on('click', '#publish-chapter-button', function(e) {
                    e.preventDefault();
                    
                    // 获取当前章节ID
                    var chapterId = $('#chapter-edit-form').data('chapter-id');
                    
                    // 获取表单数据
                    var title = $('#chapter_title').val();
                    var content = $('#chapter_content').val();
                    
                    // 检查是否使用可视化编辑器并且编辑器已初始化
                    if (typeof tinymce !== 'undefined' && tinymce.get('chapter_content')) {
                        content = tinymce.get('chapter_content').getContent();
                    } else if (typeof wp !== 'undefined' && wp.editor && wp.editor.getContent) {
                        content = wp.editor.getContent('chapter_content');
                    }
                    
                    var ancientTextId = $('#chapter_ancient_text').val();
                    var volume = $('#chapter_volume').val();
                    var chapterNumber = $('#chapter_number').val();
                    
                    // 显示发布状态
                    $('#publish-chapter-button').prop('disabled', true).text('发布中...');
                    
                    // 通过AJAX发布章节
                    $.post(ajax_object.ajax_url, {
                        action: 'save_chapter',
                        chapter_id: chapterId,
                        title: title,
                        content: content,
                        ancient_text_id: ancientTextId,
                        volume: volume,
                        chapter_number: chapterNumber,
                        status: 'publish',
                        nonce: ajax_object.nonce
                    }, function(response) {
                        // 恢复按钮状态
                        $('#publish-chapter-button').prop('disabled', false).text('发布章节');
                        
                        // 显示保存结果
                        alert('章节已发布');
                        
                        // 更新状态选择框
                        $('#chapter_status').val('publish');
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        // 恢复按钮状态
                        $('#publish-chapter-button').prop('disabled', false).text('发布章节');
                        alert('发布失败: ' + textStatus + ' - ' + errorThrown);
                    });
                });
                
                
                
                /*
                // 添加章节按钮点击事件
                var creatingButtons = {}; // 跟踪每个按钮的创建状态
                
                $(document).on('click', '.add-chapter-button', function(e) {
                    e.preventDefault();
                    
                    var ancientTextId = $(this).data('ancient-text-id');
                    var button = $(this);
                    
                    // 检查此按钮是否已经在创建过程中
                    if (creatingButtons[ancientTextId]) {
                        return;
                    }
                    
                    // 标记此按钮正在创建章节
                    creatingButtons[ancientTextId] = true;
                    
                    // 显示加载状态
                    button.text('创建中...').prop('disabled', true);
                    
                    // 通过AJAX创建新章节
                    $.post(ajax_object.ajax_url, {
                        action: 'create_chapter',
                        ancient_text_id: ancientTextId,
                        nonce: ajax_object.nonce
                    }, function(response) {
                        // 检查响应是否为数字（章节ID）
                        if (!isNaN(response)) {
                            // 重载当前页面以显示新章节
                            location.reload();
                        } else {
                            alert('创建章节失败: ' + response);
                            // 恢复按钮状态
                            button.text('添加章节').prop('disabled', false);
                            // 重置创建状态
                            creatingButtons[ancientTextId] = false;
                        }
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        alert('创建章节失败: ' + textStatus + ' - ' + errorThrown + ' - ' + jqXHR.responseText);
                        // 恢复按钮状态
                        button.text('添加章节').prop('disabled', false);
                        // 重置创建状态
                        creatingButtons[ancientTextId] = false;
                    });
                });
                
                */
                
                
                // 删除章节按钮点击事件
                $(document).on('click', '.delete-chapter-button', function(e) {
                    e.preventDefault();
                    
                    var chapterId = $(this).data('chapter-id');
                    var chapterItem = $(this).closest('.chapter-item');
                    var chapterTitle = chapterItem.find('.chapter-title').text();
                    
                    // 确认删除
                    if (confirm('确定要删除章节 "' + chapterTitle + '" 吗？此操作不可恢复。')) {
                        // 通过AJAX删除章节
                        $.post(ajax_object.ajax_url, {
                            action: 'delete_chapter',
                            chapter_id: chapterId,
                            nonce: ajax_object.nonce
                        }, function(response) {
                            if (response === 'success') {
                                // 从列表中移除章节项
                                chapterItem.remove();
                                alert('章节删除成功');
                            } else {
                                alert('删除章节失败: ' + response);
                            }
                        }).fail(function(jqXHR, textStatus, errorThrown) {
                            alert('删除章节失败: ' + textStatus + ' - ' + errorThrown);
                        });
                    }
                });
            }
        });
        </script>
        <?php
    }
    
    /**
     * 显示概览标签页
     */
    private function display_overview_tab() {
        // 获取统计信息
        $ancient_texts_count = wp_count_posts('chinese_ancient_text');
        $chapters_count = wp_count_posts('ancient_text_chapter');
        
        echo '<h2>概览</h2>';
        echo '<p>欢迎使用古籍管理系统。在这里您可以管理古籍文献及其章节内容。</p>';
        
        echo '<div class="manage-links">';
        echo '<a href="?page=chinese_ancient_text&tab=manage" class="manage-link">';
        echo '<h3>古籍管理</h3>';
        echo '<p>管理古籍文献，包括添加、编辑和删除古籍</p>';
        echo '<p><strong>' . (isset($ancient_texts_count->publish) ? $ancient_texts_count->publish : 0) . '</strong> 部已发布古籍</p>';
        echo '</a>';
        
        echo '<a href="?page=chinese_ancient_text&tab=chapters" class="manage-link">';
        echo '<h3>章节管理</h3>';
        echo '<p>管理古籍的章节内容</p>';
        echo '<p><strong>' . (isset($chapters_count->publish) ? $chapters_count->publish : 0) . '</strong> 个已发布章节</p>';
        echo '</a>';
        echo '</div>';
    }
    
    /**
     * 显示古籍管理标签页
     */
    private function display_manage_tab() {
        // 每页显示数量
        $per_page = 20;
        
        // 当前页码
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        
        // 计算偏移量
        $offset = ($current_page - 1) * $per_page;
        
        // 获取古籍总数
        $total_ancient_texts = wp_count_posts('chinese_ancient_text');
        $total = $total_ancient_texts->publish + $total_ancient_texts->draft + $total_ancient_texts->pending + $total_ancient_texts->private;
        
        // 获取古籍列表
        $ancient_texts = get_posts(array(
            'post_type' => 'chinese_ancient_text',
            'post_status' => 'any',
            'posts_per_page' => $per_page,
            'offset' => $offset,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        echo '<h2>古籍管理</h2>';
        echo '<p>在此页面您可以管理古籍文献。</p>';
        
        echo '<div class="manage-links">';
        echo '<a href="' . admin_url('post-new.php?post_type=chinese_ancient_text') . '" class="manage-link">';
        echo '<h3>添加新古籍</h3>';
        echo '<p>创建新的古籍文献条目</p>';
        echo '</a>';
        echo '</div>';
        
        if (!empty($ancient_texts)) {
            echo '<table>';
            echo '<thead>';
            echo '<tr>';
            echo '<th>标题</th>';
            echo '<th>朝代</th>';
            echo '<th>作者</th>';
            echo '<th>状态</th>';
            echo '<th>操作</th>';
            echo '</tr>';
            echo '</thead>';
            echo '<tbody>';
            
            foreach ($ancient_texts as $ancient_text) {
                $dynasty = get_post_meta($ancient_text->ID, '_ancient_text_dynasty', true);
                $author = get_post_meta($ancient_text->ID, '_ancient_text_author', true);
                
                echo '<tr>';
                echo '<td>' . esc_html($ancient_text->post_title) . '</td>';
                echo '<td>' . (!empty($dynasty) ? esc_html($dynasty) : '未设置') . '</td>';
                echo '<td>' . (!empty($author) ? esc_html($author) : '未设置') . '</td>';
                echo '<td>' . esc_html(ucfirst($ancient_text->post_status)) . '</td>';
                echo '<td>';
                echo '<a href="' . admin_url('post.php?post=' . $ancient_text->ID . '&action=edit') . '" class="button">编辑</a> ';
                echo '<a href="' . admin_url('admin.php?page=chinese_ancient_text&tab=chapters&ancient_text_id=' . $ancient_text->ID) . '" class="button button-primary">章节管理</a> ';
                echo '<a href="' . get_permalink($ancient_text->ID) . '" class="button" target="_blank">查看</a>';
                echo '</td>';
                echo '</tr>';
            }
            
            echo '</tbody>';
            echo '</table>';
            
            // 分页导航
            $total_pages = ceil($total / $per_page);
            if ($total_pages > 1) {
                echo '<div class="pagination">';
                echo paginate_links(array(
                    'base' => add_query_arg('paged', '%#%'),
                    'format' => '',
                    'prev_text' => '&laquo;',
                    'next_text' => '&raquo;',
                    'total' => $total_pages,
                    'current' => $current_page,
                    'add_args' => array(
                        'page' => 'chinese_ancient_text',
                        'tab' => 'manage'
                    )
                ));
                echo '</div>';
            }
        } else {
            echo '<p>暂无古籍文献。</p>';
        }
    }
    
    /**
     * 显示章节管理标签页
     */
    private function display_chapters_tab() {
        // 获取指定的古籍ID（如果有）
        $selected_ancient_text_id = isset($_GET['ancient_text_id']) ? intval($_GET['ancient_text_id']) : 0;
        
        // 获取所有古籍
        $ancient_texts = get_posts(array(
            'post_type' => 'chinese_ancient_text',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        echo '<h2>章节管理</h2>';
        
        // 古籍筛选器
        echo '<div class="ancient-text-filter">';
        echo '<label for="ancient_text_selector">筛选古籍：</label>';
        echo '<select id="ancient_text_selector" onchange="location = this.value;">';
        echo '<option value="' . admin_url('admin.php?page=chinese_ancient_text&tab=chapters') . '">全部古籍</option>';
        
        foreach ($ancient_texts as $ancient_text) {
            $selected = ($selected_ancient_text_id === $ancient_text->ID) ? 'selected' : '';
            echo '<option value="' . admin_url('admin.php?page=chinese_ancient_text&tab=chapters&ancient_text_id=' . $ancient_text->ID) . '" ' . $selected . '>' . esc_html($ancient_text->post_title) . '</option>';
        }
        
        echo '</select>';
        echo '</div>';
        
        echo '<p>在此页面您可以管理古籍的章节内容。</p>';
        
        echo '<div class="manage-links">';
        echo '<a href="' . admin_url('post-new.php?post_type=ancient_text_chapter') . '" class="manage-link">';
        echo '<h3>添加新章节</h3>';
        echo '<p>为古籍创建新的章节内容</p>';
        echo '</a>';
        echo '</div>';
        
        // 如果没有古籍，提示先创建古籍
        if (empty($ancient_texts)) {
            echo '<div class="notice notice-warning">';
            echo '<p>请先创建古籍，然后才能为其添加章节。</p>';
            echo '</div>';
            echo '</div>';
            return;
        }
        
        // 显示章节管理界面
        echo '<div class="chapter-manager">';
        // 左侧章节列表面板
        echo '<div class="chapter-list-panel">';
        echo '<h3>章节列表</h3>';
        
        // 确定要显示的古籍列表
        $display_ancient_texts = $ancient_texts;
        if ($selected_ancient_text_id > 0) {
            $display_ancient_texts = array_filter($ancient_texts, function($text) use ($selected_ancient_text_id) {
                return $text->ID == $selected_ancient_text_id;
            });
        }
        
        // 按古籍分组显示章节
        foreach ($display_ancient_texts as $ancient_text) {
            echo '<h4>' . esc_html($ancient_text->post_title) . '</h4>';
            
            // 添加章节按钮
            echo '<div style="margin-bottom: 10px;">';
            echo '<a href="#" class="add-chapter-button button" data-ancient-text-id="' . $ancient_text->ID . '">添加章节</a>';
            echo '</div>';
            
            // 获取该古籍的章节
            $chapters = get_posts(array(
                'post_type' => 'ancient_text_chapter',
                'post_status' => 'any',
                'posts_per_page' => -1,
                'meta_query' => array(
                    array(
                        'key' => '_chapter_ancient_text',
                        'value' => $ancient_text->ID,
                        'compare' => '='
                    )
                ),
                'orderby' => 'date',
                'order' => 'DESC'
            ));
            
            if (!empty($chapters)) {
                foreach ($chapters as $chapter) {
                    $volume = get_post_meta($chapter->ID, '_chapter_volume', true);
                    $chapter_number = get_post_meta($chapter->ID, '_chapter_number', true);
                    
                    echo '<div class="chapter-item" data-chapter-id="' . $chapter->ID . '">';
                    echo '<div class="chapter-title">' . esc_html($chapter->post_title) . '</div>';
                    echo '<div class="chapter-meta">';
                    
                    // 显示状态并添加特殊样式
                    $status_text = ucfirst($chapter->post_status);
                    if ($chapter->post_status === 'publish') {
                        $status_text = '<span style="color: #00a32a; font-weight: bold;">已发布</span>';
                        // 为已发布的章节添加查看链接
                        $chapter_permalink = get_permalink($chapter->ID);
                        if ($chapter_permalink) {
                            $status_text .= ' | <a href="' . esc_url($chapter_permalink) . '" target="_blank" style="color: #00a32a; text-decoration: none;">查看</a>';
                        }
                    } else if ($chapter->post_status === 'draft') {
                        $status_text = '<span style="color: #dba617;">草稿</span>';
                    } else if ($chapter->post_status === 'private') {
                        $status_text = '<span style="color: #8c8c8c;">私有</span>';
                    }
                    
                    echo '<span>状态: ' . $status_text . '</span>';
                    if (!empty($volume)) {
                        echo ' | 卷: ' . esc_html($volume);
                    }
                    if (!empty($chapter_number)) {
                        echo ' | 章节: ' . esc_html($chapter_number);
                    }
                    // 添加删除按钮
                    echo ' | <a href="#" class="delete-chapter-button" data-chapter-id="' . $chapter->ID . '" style="color: #d63638; text-decoration: none;">删除</a>';
                    echo '</div>';
                    echo '</div>';
                }
            } else {
                echo '<div class="chapter-item no-chapters">暂无章节</div>';
            }
        }
        echo '</div>';
        
        // 右侧章节编辑面板
        echo '<div class="chapter-edit-panel">';
        echo '<div class="no-chapter-selected">请选择一个章节进行编辑</div>';
        echo '</div>';
        
        echo '</div>'; // 结束 chapter-manager
        
        // 添加提示信息
        echo '<div class="notice notice-info">';
        echo '<p>提示：点击古籍标题旁的"添加章节"按钮可以快速创建新章节。</p>';
        echo '</div>';
    }
    
    /**
     * 显示设置标签页
     */
    private function display_settings_tab() {
        // 处理表单提交
        if (isset($_POST['submit']) && wp_verify_nonce($_POST['chinese_dictionary_settings_nonce'], 'save_settings')) {
            // 保存设置
            $show_default_characters = isset($_POST['show_default_characters']) ? 1 : 0;
            $show_default_words = isset($_POST['show_default_words']) ? 1 : 0;
            $show_default_idioms = isset($_POST['show_default_idioms']) ? 1 : 0;
            
            update_option('chinese_dictionary_show_default_characters', $show_default_characters);
            update_option('chinese_dictionary_show_default_words', $show_default_words);
            update_option('chinese_dictionary_show_default_idioms', $show_default_idioms);
            
            echo '<div class="notice notice-success"><p>设置已保存。</p></div>';
        }
        
        // 获取当前设置
        $show_default_characters = get_option('chinese_dictionary_show_default_characters', 1);
        $show_default_words = get_option('chinese_dictionary_show_default_words', 1);
        $show_default_idioms = get_option('chinese_dictionary_show_default_idioms', 1);
        
        echo '<h2>设置</h2>';
        echo '<form method="post">';
        wp_nonce_field('save_settings', 'chinese_dictionary_settings_nonce');
        
        echo '<table class="form-table">';
        echo '<tr>';
        echo '<th scope="row">显示默认汉字</th>';
        echo '<td>';
        echo '<input type="checkbox" name="show_default_characters" id="show_default_characters" value="1" ' . checked(1, $show_default_characters, false) . ' />';
        echo '<label for="show_default_characters">启用后，插件会自动创建默认的常用汉字</label>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th scope="row">显示默认词语</th>';
        echo '<td>';
        echo '<input type="checkbox" name="show_default_words" id="show_default_words" value="1" ' . checked(1, $show_default_words, false) . ' />';
        echo '<label for="show_default_words">启用后，插件会自动创建默认的常用词语</label>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th scope="row">显示默认成语</th>';
        echo '<td>';
        echo '<input type="checkbox" name="show_default_idioms" id="show_default_idioms" value="1" ' . checked(1, $show_default_idioms, false) . ' />';
        echo '<label for="show_default_idioms">启用后，插件会自动创建默认的常用成语</label>';
        echo '</td>';
        echo '</tr>';
        
        echo '</table>';
        
        submit_button('保存设置');
        echo '</form>';
    }
}

// 初始化管理页面
// 使用类名作为唯一标识，确保只实例化一次
if (!class_exists('AncientTextAdminPage')) {
    new AncientTextAdminPage();
} else if (!isset($GLOBALS['ancient_text_admin_page_instance'])) {
    $GLOBALS['ancient_text_admin_page_instance'] = new AncientTextAdminPage();
}