<?php
/**
 * 子分类筛选功能
 * 在分类页面添加子分类筛选区域
 */

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

class SubcategoryFilter {
    
    public function __construct() {
        // 在分类页面添加筛选区域（使用WordPress默认主题中存在的钩子）
        add_action('woocommerce_archive_description', array($this, 'display_subcategory_filter')); // WooCommerce钩子
        add_action('loop_start', array($this, 'maybe_display_subcategory_filter')); // 通用钩子
        
        // 处理AJAX筛选请求
        add_action('wp_ajax_filter_posts_by_subcategory', array($this, 'filter_posts_by_subcategory'));
        add_action('wp_ajax_nopriv_filter_posts_by_subcategory', array($this, 'filter_posts_by_subcategory'));
        
        // 处理搜索请求
        add_action('wp_ajax_search_posts_in_category', array($this, 'search_posts_in_category'));
        add_action('wp_ajax_nopriv_search_posts_in_category', array($this, 'search_posts_in_category'));
        
        // 修改主查询以支持子分类筛选
        add_action('pre_get_posts', array($this, 'modify_category_query'));
        
        // 在分类页面添加必要的CSS和JS
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // 注册自定义查询变量
        add_filter('query_vars', array($this, 'add_custom_query_vars'));
    }
    
    /**
     * 添加自定义查询变量
     */
    public function add_custom_query_vars($vars) {
        $vars[] = 'subcategory';
        $vars[] = 'category_search';
        return $vars;
    }
    
    /**
     * 在分类页面添加筛选区域
     */
    public function display_subcategory_filter() {
        // 检查是否是分类页面
        if (!is_category()) {
            return;
        }
        
        // 获取当前分类
        $current_category = get_queried_object();
        
        // 获取子分类
        $subcategories = get_categories(array(
            'parent' => $current_category->term_id,
            'hide_empty' => false,
        ));
        
        // 获取当前选择的子分类（如果有）
        $selected_subcat = get_query_var('subcategory');
        
        // 获取搜索关键词（如果有）
        $search_keyword = get_query_var('category_search');
        
        // 输出筛选区域
        echo '<div class="subcategory-filter">';
       // echo '<h3>子分类筛选</h3>';
        
        // 添加搜索框
        echo '<div class="category-search-box">';
        echo '<form method="get" class="category-search-form">';
        //echo '<input type="text" name="category_search" placeholder="搜索分类下的文章..." value="' . esc_attr($search_keyword) . '" class="category-search-input">';
        echo '<input type="text" name="category_search" placeholder="搜索..." value="' . esc_attr($search_keyword) . '" class="category-search-input">';        
        echo '<button type="submit" class="category-search-button">搜索</button>';
        echo '</form>';
        echo '</div>';
        
        // 只有当存在子分类时才显示子分类列表
        if (!empty($subcategories)) {
            echo '<ul class="subcategory-list" data-category="' . esc_attr($current_category->term_id) . '">';
            $all_link = esc_url(remove_query_arg('subcategory', remove_query_arg('category_search')));
            echo '<li><a href="' . $all_link . '" class="subcategory-item' . ($selected_subcat ? '' : ' active') . '" data-subcat="0">全部</a></li>';
            
            foreach ($subcategories as $subcategory) {
                $class = ($selected_subcat == $subcategory->term_id) ? ' active' : '';
                $link = esc_url(add_query_arg('subcategory', $subcategory->term_id));
                if ($search_keyword) {
                    $link = add_query_arg('category_search', $search_keyword, $link);
                }
                echo '<li><a href="' . $link . '" class="subcategory-item' . $class . '" data-subcat="' . esc_attr($subcategory->term_id) . '">' . esc_html($subcategory->name) . ' (' . esc_html($subcategory->count) . ')</a></li>';
            }
            
            echo '</ul>';
        }
        
        echo '</div>';
    }
    
    /**
     * 条件性地显示子分类筛选区域（避免在不适当的地方显示）
     */
    public function maybe_display_subcategory_filter($query) {
        // 确保只在主查询的分类页面上显示
        if (!is_main_query() || !is_category()) {
            return;
        }
        
        // 移除钩子以避免重复显示
        remove_action('loop_start', array($this, 'maybe_display_subcategory_filter'));
        
        // 显示筛选区域
        $this->display_subcategory_filter();
    }
    
    /**
     * 修改分类页面的主查询以支持子分类筛选
     */
    public function modify_category_query($query) {
        // 只在前端分类页面主查询中应用
        if (!is_admin() && is_category() && $query->is_main_query()) {
            $subcategory = get_query_var('subcategory');
            $search_keyword = get_query_var('category_search');
            
            // 如果有搜索关键词，则添加搜索条件
            if (!empty($search_keyword)) {
                $query->set('s', $search_keyword);
            }
            
            // 如果有子分类筛选参数，则修改查询
            if (!empty($subcategory)) {
                $query->set('cat', intval($subcategory));
            } else {
                // 默认显示当前分类及其所有子分类的文章
                // 获取当前分类及其所有子分类的ID
                $current_category = get_queried_object();
                if ($current_category) {
                    $child_categories = get_term_children($current_category->term_id, 'category');
                    if (!is_wp_error($child_categories) && !empty($child_categories)) {
                        $category_ids = array_merge(array($current_category->term_id), $child_categories);
                        $query->set('category__in', $category_ids);
                    }
                }
            }
        }
    }
    
    /**
     * 处理AJAX筛选请求
     */
    public function filter_posts_by_subcategory() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'subcategory_filter_nonce')) {
            wp_send_json_error('安全验证失败');
        }
        
        // 检查必要的参数
        if (!isset($_POST['category']) || !isset($_POST['subcategory'])) {
            wp_send_json_error('缺少必要参数');
        }
        
        $category_id = intval($_POST['category']);
        $subcategory_id = intval($_POST['subcategory']);
        $search_keyword = isset($_POST['search_keyword']) ? sanitize_text_field($_POST['search_keyword']) : '';
        
        // 构建查询参数
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => get_option('posts_per_page', 10),
            'paged' => 1,
        );
        
        // 根据是否选择子分类设置查询条件
        if ($subcategory_id > 0) {
            $args['cat'] = $subcategory_id;
        } else {
            // 如果选择"全部"，则显示当前分类及其所有子分类的文章
            $child_categories = get_term_children($category_id, 'category');
            if (!is_wp_error($child_categories) && !empty($child_categories)) {
                $category_ids = array_merge(array($category_id), $child_categories);
                $args['category__in'] = $category_ids;
            } else {
                $args['cat'] = $category_id;
            }
        }
        
        // 如果有搜索关键词，则添加搜索条件
        if (!empty($search_keyword)) {
            $args['s'] = $search_keyword;
        }
        
        // 执行查询
        $query = new WP_Query($args);
        
        // 准备返回数据
        if ($query->have_posts()) {
            ob_start();
            while ($query->have_posts()) {
                $query->the_post();
                ?>
                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                    <header class="entry-header">
                        <h2 class="entry-title">
                            <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
                        </h2>
                        <div class="entry-meta">
                            <?php echo get_the_date(); ?>
                        </div>
                    </header>
                    <div class="entry-summary">
                        <?php the_excerpt(); ?>
                    </div>
                </article>
                <?php
            }
            $content = ob_get_clean();
            wp_reset_postdata();
            
            wp_send_json_success(array(
                'content' => $content,
                'max_num_pages' => $query->max_num_pages,
                'found_posts' => $query->found_posts,
            ));
        } else {
            wp_send_json_success(array(
                'content' => '<p>没有找到相关文章。</p>',
                'max_num_pages' => 0,
                'found_posts' => 0,
            ));
        }
    }
    
    /**
     * 处理分类页面搜索请求
     */
    public function search_posts_in_category() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'subcategory_filter_nonce')) {
            wp_send_json_error('安全验证失败');
        }
        
        $category_id = isset($_POST['category']) ? intval($_POST['category']) : 0;
        $search_keyword = isset($_POST['search_keyword']) ? sanitize_text_field($_POST['search_keyword']) : '';
        
        if (empty($search_keyword)) {
            wp_send_json_error('搜索关键词不能为空');
        }
        
        // 构建查询参数
        $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => get_option('posts_per_page', 10),
            'paged' => 1,
            's' => $search_keyword,
        );
        
        // 获取当前分类及其所有子分类的ID
        if ($category_id > 0) {
            $child_categories = get_term_children($category_id, 'category');
            if (!is_wp_error($child_categories) && !empty($child_categories)) {
                $category_ids = array_merge(array($category_id), $child_categories);
                $args['category__in'] = $category_ids;
            } else {
                $args['cat'] = $category_id;
            }
        }
        
        // 执行查询
        $query = new WP_Query($args);
        
        // 准备返回数据
        if ($query->have_posts()) {
            ob_start();
            while ($query->have_posts()) {
                $query->the_post();
                ?>
                <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                    <header class="entry-header">
                        <h2 class="entry-title">
                            <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
                        </h2>
                        <div class="entry-meta">
                            <?php echo get_the_date(); ?>
                        </div>
                    </header>
                    <div class="entry-summary">
                        <?php the_excerpt(); ?>
                    </div>
                </article>
                <?php
            }
            $content = ob_get_clean();
            wp_reset_postdata();
            
            wp_send_json_success(array(
                'content' => $content,
                'max_num_pages' => $query->max_num_pages,
                'found_posts' => $query->found_posts,
            ));
        } else {
            wp_send_json_success(array(
                'content' => '<p>没有找到相关文章。</p>',
                'max_num_pages' => 0,
                'found_posts' => 0,
            ));
        }
    }
    
    /**
     * 加载必要的CSS和JS
     */
    public function enqueue_scripts() {
        // 只在分类页面加载
        if (is_category()) {
            wp_enqueue_script('subcategory-filter-js', plugin_dir_url(__FILE__) . '../assets/frontend.js', array('jquery'), '1.0', true);
            
            // 传递AJAX URL到JavaScript
            wp_localize_script('subcategory-filter-js', 'subcategory_filter_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('subcategory_filter_nonce')
            ));
        }
    }
}

// 初始化类
new SubcategoryFilter();