<?php
/**
 * 古籍章节卷管理功能
 */

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

class AncientTextChapters {
    
    public function __construct() {
        add_action('init', array($this, 'register_chapter_post_type'));
        add_action('add_meta_boxes', array($this, 'add_chapter_meta_boxes'));
        add_action('save_post', array($this, 'save_chapter_meta'));
        add_action('admin_menu', array($this, 'add_chapters_submenu'), 20);
        add_action('admin_init', array($this, 'redirect_chapters_menu'));
        add_action('wp_ajax_add_chapter_annotation', array($this, 'add_chapter_annotation'));
        add_action('wp_ajax_edit_chapter_annotation', array($this, 'edit_chapter_annotation'));
        add_action('wp_ajax_delete_chapter_annotation', array($this, 'delete_chapter_annotation'));
        add_filter('comment_text', array($this, 'add_annotation_anchor_link'), 10, 2);
        add_filter('the_content', array($this, 'add_annotation_anchors_to_content'));
        add_filter('the_content', array($this, 'highlight_annotated_text'));
    }
    
    /**
     * 注册章节文章类型
     */
    public function register_chapter_post_type() {
        $labels = array(
            'name'                  => '章节',
            'singular_name'         => '章节',
            'menu_name'             => '章节',
            'name_admin_bar'        => '章节',
            'archives'              => '章节档案',
            'attributes'            => '章节属性',
            'parent_item_colon'     => '父级章节',
            'all_items'             => '所有章节',
            'add_new_item'          => '新增章节',
            'add_new'               => '新增',
            'new_item'              => '新章节',
            'edit_item'             => '编辑章节',
            'update_item'           => '更新章节',
            'view_item'             => '查看章节',
            'view_items'            => '查看章节',
            'search_items'          => '搜索章节',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '章节封面',
            'set_featured_image'    => '设置章节封面',
            'remove_featured_image' => '移除章节封面',
            'use_featured_image'    => '用作章节封面',
            'insert_into_item'      => '插入到章节中',
            'uploaded_to_this_item' => '上传到此章节',
            'items_list'            => '章节列表',
            'items_list_navigation' => '章节列表导航',
            'filter_items_list'     => '筛选章节列表',
        );
        
        $args = array(
            'label'                 => '章节',
            'description'           => '古籍章节条目',
            'labels'                => $labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions', 'page-attributes'),
            'hierarchical'          => true,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => false,
            'menu_position'         => 6, // 调整菜单位置，与古籍管理菜单一致
            'menu_icon'             => 'dashicons-book-alt',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => false,
            'exclude_from_search'   => true,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'ancient-text-chapter'),
        );
        
        register_post_type('ancient_text_chapter', $args);
    }
    
    /**
     * 添加章节子菜单到古籍菜单
     */
    public function add_chapters_submenu() {
        // 添加章节管理子菜单
        add_submenu_page(
            'chinese_ancient_text',
            '章节管理',
            '章节管理',
            'manage_options',
            'edit.php?post_type=ancient_text_chapter'
        );
        
        // 添加章节到古籍的关联
        add_submenu_page(
            'chinese_ancient_text',
            '添加章节',
            '添加章节',
            'manage_options',
            'post-new.php?post_type=ancient_text_chapter'
        );
    }
    
    /**
     * 重定向章节菜单，确保正确显示
     */
    public function redirect_chapters_menu() {
        global $pagenow, $typenow;
        
        // 如果当前是章节编辑页面，但父菜单不是古籍，则重定向
        if ($pagenow === 'edit.php' && $typenow === 'ancient_text_chapter') {
            // 检查当前页面是否是章节管理页面但不在古籍菜单下
            if (isset($_GET['post_type']) && $_GET['post_type'] === 'ancient_text_chapter') {
                // 不需要重定向，正常显示
                return;
            }
        }
    }
    
    /**
     * 添加章节元框
     */
    public function add_chapter_meta_boxes() {
        add_meta_box(
            'chapter-ancient-text-info',
            '关联古籍',
            array($this, 'render_chapter_ancient_text_meta_box'),
            'ancient_text_chapter',
            'normal',
            'high'
        );
        
        add_meta_box(
            'chapter-basic-info',
            '章节基本信息',
            array($this, 'render_chapter_basic_info_meta_box'),
            'ancient_text_chapter',
            'normal',
            'high'
        );
    }
    
    /**
     * 渲染关联古籍元框
     */
    public function render_chapter_ancient_text_meta_box($post) {
        // 获取所有古籍
        $ancient_texts = get_posts(array(
            'post_type' => 'chinese_ancient_text',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        $related_ancient_text = get_post_meta($post->ID, '_chapter_ancient_text', true);
        ?>
        <table class="form-table">
            <tr>
                <th><label for="chapter_ancient_text">选择古籍</label></th>
                <td>
                    <select id="chapter_ancient_text" name="chapter_ancient_text" class="regular-text">
                        <option value="">请选择关联的古籍</option>
                        <?php foreach ($ancient_texts as $ancient_text): ?>
                            <option value="<?php echo esc_attr($ancient_text->ID); ?>" <?php selected($related_ancient_text, $ancient_text->ID); ?>>
                                <?php echo esc_html($ancient_text->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择此章节所属的古籍</p>
                </td>
            </tr>
            <tr>
                <th><label for="chapter_volume">卷数</label></th>
                <td>
                    <input type="text" id="chapter_volume" name="chapter_volume" value="<?php echo esc_attr(get_post_meta($post->ID, '_chapter_volume', true)); ?>" class="regular-text" />
                    <p class="description">输入章节所属的卷数（如：卷一、卷二等）</p>
                </td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * 渲染章节基本信息元框
     */
    public function render_chapter_basic_info_meta_box($post) {
        $chapter_number = get_post_meta($post->ID, '_chapter_number', true);
        ?>
        <table class="form-table">
            <tr>
                <th><label for="chapter_number">章节编号</label></th>
                <td>
                    <input type="text" id="chapter_number" name="chapter_number" value="<?php echo esc_attr($chapter_number); ?>" class="regular-text" />
                    <p class="description">输入章节编号（如：1.1、1.2等）</p>
                </td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * 保存章节元数据
     */
    public function save_chapter_meta($post_id) {
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查文章类型
        if (get_post_type($post_id) !== 'ancient_text_chapter') {
            return;
        }
        
        // 保存关联古籍
        if (isset($_POST['chapter_ancient_text'])) {
            update_post_meta($post_id, '_chapter_ancient_text', intval($_POST['chapter_ancient_text']));
        }
        
        // 保存卷数
        if (isset($_POST['chapter_volume'])) {
            update_post_meta($post_id, '_chapter_volume', sanitize_text_field($_POST['chapter_volume']));
        }
        
        // 保存章节编号
        if (isset($_POST['chapter_number'])) {
            update_post_meta($post_id, '_chapter_number', sanitize_text_field($_POST['chapter_number']));
        }
    }
    
    /**
     * 添加章节批注
     */
    public function add_chapter_annotation() {
        // 检查权限
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => '权限不足'));
        }
        
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'add_annotation_nonce')) {
            wp_send_json_error(array('message' => '安全验证失败'));
        }
        
        // 获取参数
        $chapter_id = intval($_POST['chapter_id']);
        $content = sanitize_textarea_field($_POST['content']);
        $selection = isset($_POST['selection']) ? sanitize_text_field($_POST['selection']) : '';
        
        // 检查章节是否存在
        if (!get_post($chapter_id)) {
            wp_send_json_error(array('message' => '章节不存在'));
        }
        
        // 添加批注
        $comment_id = wp_insert_comment(array(
            'comment_post_ID' => $chapter_id,
            'comment_content' => $content,
            'comment_author' => wp_get_current_user()->display_name,
            'comment_author_email' => wp_get_current_user()->user_email,
            'comment_type' => 'annotation',
            'comment_meta' => array(
                'is_annotation' => '1',
                'selected_text' => $selection
            )
        ));
        
        if ($comment_id) {
            wp_send_json_success();
        } else {
            wp_send_json_error(array('message' => '保存失败'));
        }
    }
    
    /**
     * 编辑章节批注
     */
    public function edit_chapter_annotation() {
        // 检查权限
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => '权限不足'));
        }
        
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'edit_annotation_nonce')) {
            wp_send_json_error(array('message' => '安全验证失败'));
        }
        
        // 获取参数
        $annotation_id = intval($_POST['annotation_id']);
        $content = sanitize_textarea_field($_POST['content']);
        
        // 检查批注是否存在
        $comment = get_comment($annotation_id);
        if (!$comment) {
            wp_send_json_error(array('message' => '批注不存在'));
        }
        
        // 检查权限（只能编辑自己的批注或管理员可以编辑所有批注）
        if (!current_user_can('edit_others_posts') && $comment->user_id != get_current_user_id()) {
            wp_send_json_error(array('message' => '权限不足'));
        }
        
        // 更新批注
        $updated = wp_update_comment(array(
            'comment_ID' => $annotation_id,
            'comment_content' => $content
        ));
        
        if ($updated) {
            wp_send_json_success();
        } else {
            wp_send_json_error(array('message' => '更新失败'));
        }
    }
    
    /**
     * 删除章节批注
     */
    public function delete_chapter_annotation() {
        // 检查权限
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => '权限不足'));
        }
        
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'delete_annotation_nonce')) {
            wp_send_json_error(array('message' => '安全验证失败'));
        }
        
        // 获取参数
        $annotation_id = intval($_POST['annotation_id']);
        
        // 检查批注是否存在
        $comment = get_comment($annotation_id);
        if (!$comment) {
            wp_send_json_error(array('message' => '批注不存在'));
        }
        
        // 检查权限（只能删除自己的批注或管理员可以删除所有批注）
        if (!current_user_can('edit_others_posts') && $comment->user_id != get_current_user_id()) {
            wp_send_json_error(array('message' => '权限不足'));
        }
        
        // 删除批注
        $deleted = wp_delete_comment($annotation_id, true);
        
        if ($deleted) {
            wp_send_json_success();
        } else {
            wp_send_json_error(array('message' => '删除失败'));
        }
    }
    
    /**
     * 为批注添加锚点链接
     */
    public function add_annotation_anchor_link($comment_text, $comment) {
        // 检查是否是批注
        if (get_comment_meta($comment->comment_ID, 'is_annotation', true) === '1') {
            // 生成锚点链接
            $anchor_link = get_permalink($comment->comment_post_ID) . '?mode=reading#annotation-' . $comment->comment_ID;
            $comment_text .= '<div class="annotation-anchor-link"><a href="' . esc_url($anchor_link) . '">引用此批注</a> | <a href="#" class="copy-annotation-link" data-annotation-id="' . esc_attr($comment->comment_ID) . '">复制链接</a></div>';
        }
        
        return $comment_text;
    }
    
    /**
     * 为内容中的批注添加锚点
     */
    public function add_annotation_anchors_to_content($content) {
        // 检查是否是古籍章节页面
        if (is_singular('ancient_text_chapter')) {
            // 获取当前章节的所有批注
            $annotations = get_comments(array(
                'post_id' => get_the_ID(),
                'meta_key' => 'is_annotation',
                'meta_value' => '1',
                'orderby' => 'comment_date',
                'order' => 'ASC'
            ));
            
            // 为每个批注在内容末尾添加锚点
            if (!empty($annotations)) {
                $content .= '<div class="annotations-anchors">';
                foreach ($annotations as $annotation) {
                    $content .= '<div id="annotation-' . esc_attr($annotation->comment_ID) . '" class="annotation-anchor"></div>';
                }
                $content .= '</div>';
            }
        }
        
        return $content;
    }
    
    /**
     * 高亮显示已批注的文本
     */
    public function highlight_annotated_text($content) {
        // 检查是否是古籍章节页面
        if (is_singular('ancient_text_chapter')) {
            // 获取当前章节的所有批注
            $annotations = get_comments(array(
                'post_id' => get_the_ID(),
                'meta_key' => 'is_annotation',
                'meta_value' => '1',
                'orderby' => 'comment_date',
                'order' => 'ASC'
            ));
            
            // 为每个带有选中文本的批注高亮对应内容
            foreach ($annotations as $annotation) {
                $selected_text = get_comment_meta($annotation->comment_ID, 'selected_text', true);
                if (!empty($selected_text)) {
                    // 创建高亮的HTML标记
                    $highlighted_text = '<span class="annotation-highlight" data-annotation-id="' . esc_attr($annotation->comment_ID) . '">' . esc_html($selected_text) . '</span>';
                    // 替换内容中的文本
                    $content = str_replace($selected_text, $highlighted_text, $content);
                }
            }
        }
        
        return $content;
    }
}

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