<?php
/*
*  Template Name: 分类模板
*/
?>
<?php get_header() ?>

<!-- 新闻搜索功能模块 -->
<div class="news-search-section">
    <div class="search-container">
        <div class="search-header mt-[8rem]">
            <h2 class="font-display text-[2.66rem] font-black text-slate-800 tracking-widest leading-[1.2] mb-6">新闻中心</h2>
             <div class="w-16 h-1 bg-primary mx-auto mb-6 transition-all duration-700 group-hover:w-32"></div>
        </div>
        <div class="search-form-wrapper">
            <?php
            $form_action = home_url('/');
            if (is_page()) {
                $form_action = get_permalink(get_queried_object_id());
            } elseif (is_category()) {
                $form_action = get_category_link(get_queried_object_id());
            }
            ?>
            <form class="news-search-form" method="get" action="<?php echo esc_url($form_action); ?>">
                <div class="search-controls">
                    <!-- 分类选择下拉菜单 -->
                    <div class="category-selector">
                        <?php
                        $current_cat = isset($_GET['category']) ? $_GET['category'] : '';
                        if (empty($current_cat) && is_category()) {
                            $current_cat = get_queried_object()->slug;
                        }
                        ?>
                        <select name="category" id="news-category" class="category-dropdown">
                            <option value="" data-url="<?php echo esc_url(home_url('/category/news-center/')); ?>" <?php selected(empty($current_cat) || $current_cat === 'news-center', true); ?>>显示全部</option>
                            <?php
                            $categories = get_categories(array(
                                'hide_empty' => false,
                                'orderby' => 'name',
                                'order' => 'ASC'
                            ));
                            foreach ($categories as $category) {
                                if ($category->slug === 'news-center') continue;
                                $cat_link = get_category_link($category->term_id);
                                echo '<option value="' . esc_attr($category->slug) . '" data-url="' . esc_url($cat_link) . '" ' . selected($current_cat, $category->slug, false) . '>' . esc_html($category->name) . '</option>';
                            }
                            ?>
                        </select>

                    </div>
                    
                    <!-- 搜索输入框 -->
                    <div class="search-input-wrapper">
                        <input type="text" name="search_keyword" id="news-search" class="search-input" 
                               placeholder="关键词" 
                               value="<?php echo isset($_GET['search_keyword']) ? esc_attr($_GET['search_keyword']) : ''; ?>"
                               autocomplete="off">
                        <div class="search-suggestions" id="search-suggestions"></div>
                    </div>
                    
                    <!-- 搜索按钮 -->
                    <button type="submit" class="search-button">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                            <path d="M19 19L13 13M15 8C15 11.866 11.866 15 8 15C4.134 15 1 11.866 1 8C1 4.134 4.134 1 8 1C11.866 1 15 4.134 15 8Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </button>
                </div>
                <input type="hidden" name="post_type" value="post">
            </form>
        </div>
    </div>
</div>
<!-- 文章展示组件 -->


<!-- 文章列表板块 -->
<div class="article-list-section mt-[5rem]">
    <div class="container">
        <div class="article-list-wrapper">
            <?php
            // 获取当前页码（用于分页，兼容页面模板）
            $paged = get_query_var('paged') ? get_query_var('paged') : (get_query_var('page') ? get_query_var('page') : 1);

            // 获取文章列表（支持数字分页）
            $args = array(
                'post_type' => 'post',
                'posts_per_page' => 5,
                'post_status' => 'publish',
                'orderby' => 'date',
                'order' => 'DESC',
                'paged' => $paged
            );

            // 如果是分类归档页面，添加分类筛选
            if (is_category()) {
                $args['cat'] = get_query_var('cat');
            }

            // 处理分类筛选（URL参数优先）
            if (isset($_GET['category']) && !empty($_GET['category'])) {
                $args['category_name'] = sanitize_text_field($_GET['category']);
                // 修复：如果有明确的分类筛选参数，且该参数与当前归档分类不同，则移除归档分类限制
                // 这样可以避免 "在分类A下搜索分类B" 导致的结果为空（除非文章同时属于两个分类）
                if (isset($args['cat'])) {
                    unset($args['cat']);
                }
            }

            // 处理关键词搜索
            if (isset($_GET['search_keyword']) && !empty($_GET['search_keyword'])) {
                $args['s'] = sanitize_text_field($_GET['search_keyword']);
            }

            $articles_query = new WP_Query($args);

            if ($articles_query->have_posts()) :
                while ($articles_query->have_posts()) : $articles_query->the_post();
                    // 获取文章特色图片
                    $featured_image = get_the_post_thumbnail_url(get_the_ID(), 'medium');
                    if (!$featured_image) {
                        $featured_image = get_template_directory_uri() . '/assets/images/default-post.jpg';
                    }
                    
                    // 获取文章摘要
                    $excerpt = get_the_excerpt();
                    if (empty($excerpt)) {
                        $excerpt = wp_trim_words(get_the_content(), 20, '...');
                    }
                    
                    // 获取发布时间
                    $post_date = get_the_date('Y-m-d');
            ?>
            <div class="article-list-item">
                <div class="article-image">
                    <a href="<?php echo esc_url(get_permalink()); ?>">
                        <img src="<?php echo esc_url($featured_image); ?>" alt="<?php echo esc_attr(get_the_title()); ?>">
                    </a>
                </div>
                <div class="article-content">
                    <div class="article-meta">
                        <span class="article-date"><?php echo esc_html($post_date); ?></span>
                    </div>
                    <h3 class="article-title">
                        <a href="<?php echo esc_url(get_permalink()); ?>"><?php echo esc_html(get_the_title()); ?></a>
                    </h3>
                    <p class="article-excerpt"><?php echo esc_html($excerpt); ?></p>
                    <div class="article-actions">
                        <a href="<?php echo esc_url(get_permalink()); ?>" class="read-more-btn">
                            <span class="btn-circle">→</span>
                        </a>
                    </div>
                </div>
            </div>
            <?php
                endwhile;
                wp_reset_postdata();

                // 数字分页 - 修复静态首页模式下的分页URL问题
                $total_pages = $articles_query->max_num_pages;
                if ($total_pages > 1) {
                    echo '<nav class="pagination">';
                    
                    $big = 999999999; // 需要一个不太可能碰撞的整数
                    
                    // 获取当前页面URL（archive.php的URL）
                    global $wp;
                    $current_url = home_url($wp->request);
                    
                    // 如果是根目录访问archive.php，需要特殊处理
                    if (empty($wp->request) || $wp->request === '/') {
                        // 为archive页面创建专门的URL结构
                        $base_url = home_url('/news'); // 使用/news作为归档页面的基础URL
                        $format = '/page/%#%/';
                    } else {
                        $base_url = $current_url;
                        $format = '/page/%#%/';
                    }
                    
                    // 检查是否使用了永久链接
                    if (get_option('permalink_structure')) {
                        $base = str_replace($big, '%#%', esc_url(get_pagenum_link($big)));
                        // 确保base URL不会与首页冲突
                        if (strpos($base, home_url('/page/')) === 0) {
                            $base = home_url('/news/page/%#%/');
                        }
                    } else {
                        $base = add_query_arg('paged', '%#%', $base_url);
                        $format = '';
                    }
                    
                    // 获取当前查询参数
                    $current_query = $_GET;
                    unset($current_query['paged']); // 移除paged参数避免重复
                    
                    echo paginate_links(array(
                        'base' => $base,
                        'format' => $format,
                        'current' => max(1, $paged),
                        'total' => $articles_query->max_num_pages,
                        'prev_text' => '&laquo; 上一页',
                        'next_text' => '下一页 &raquo;',
                        'add_args' => $current_query,
                        'add_fragment' => false,
                    ));
                    echo '</nav>';
                }
            ?>
            <?php else : ?>
            <div class="no-articles">
                <p>暂无文章发布</p>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var categorySelect = document.getElementById('news-category');
    var searchForm = document.querySelector('.news-search-form');
    var searchInput = document.getElementById('news-search');

    if (categorySelect && searchForm) {
        categorySelect.addEventListener('change', function() {
            var keyword = searchInput ? searchInput.value.trim() : '';
            var selectedOption = this.options[this.selectedIndex];
            
            // 如果没有关键词，直接跳转到分类页
            if (!keyword && selectedOption && selectedOption.dataset.url) {
                window.location.href = selectedOption.dataset.url;
            } else {
                // 如果有关键词，或者没有分类url（比如"显示全部"且没配置url），则提交表单
                searchForm.submit();
            }
        });
    }
});
</script>

<?php get_footer() ?>