<?php 
/**
 * 搜索页面
 */
get_header(); ?>

<!-- 新闻搜索功能模块 -->
<div class="news-search-section">
    <div class="search-container">
        <div class="search-header">
            <h2 class="font-display text-[2.66rem] font-black text-slate-800 tracking-widest leading-[1.2] mb-6">新闻中心2</h2>
             <div class="w-12 h-1 bg-primary mx-auto"></div>
        </div>
        <div class="search-form-wrapper">
            <?php
            $form_action = home_url('/');
            ?>
            <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="s" id="news-search" class="search-input" 
                               placeholder="关键词" 
                               value="<?php echo get_search_query(); ?>"
                               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-display-wrapper">
    <div class="article-content">
        <?php
        // 获取随机的一篇文章
        $random_post = new WP_Query(array(
            'post_type' => 'post',
            'posts_per_page' => 1,
            'post_status' => 'publish',
            'orderby' => 'rand'
        ));

        if ($random_post->have_posts()) :
            while ($random_post->have_posts()) : $random_post->the_post();
                // 获取文章特色图片
                $featured_image = get_the_post_thumbnail_url(get_the_ID(), 'large');
                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(), 30, '...');
                }
        ?>
        <div class="article-item">
            <div class="left-column">
                <a href="<?php echo esc_url(get_permalink()); ?>" class="image-link">
                    <img src="<?php echo esc_url($featured_image); ?>" alt="<?php echo esc_attr(get_the_title()); ?>">
                </a>
            </div>
            <div class="right-column">
                <div class="content-top">
                    <a href="<?php echo esc_url(get_permalink()); ?>" class="title-link">
                        <h2 class="article-title"><?php echo esc_html(get_the_title()); ?></h2>
                    </a>
                    <p class="article-description">
                        <?php echo esc_html($excerpt); ?>
                    </p>
                    <a href="<?php echo esc_url(get_permalink()); ?>" class="view-more-link">查看更多</a>
                </div>
            </div>
        </div>
        <?php
            endwhile;
            wp_reset_postdata();
        else :
        ?>
        <div class="article-item">
            <div class="left-column">
                <img src="<?php echo get_template_directory_uri(); ?>/assets/images/default-post.jpg" alt="暂无文章">
            </div>
            <div class="right-column">
                <div class="content-top">
                    <h2 class="article-title">暂无文章</h2>
                    <p class="article-description">
                        目前还没有发布任何文章，请稍后再来查看。
                    </p>
                    <a href="<?php echo esc_url(home_url('/')); ?>" class="view-more-link">返回首页</a>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- 文章列表板块 -->
<div class="article-list-section">
    <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);

            // 调试信息
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Search.php - Current page: ' . $paged);
            }

            // 获取文章列表
            $args = array(
                'post_type' => 'post',
                'posts_per_page' => 5,
                'post_status' => 'publish',
                'orderby' => 'date',
                'order' => 'DESC',
                'paged' => $paged
            );

            // 处理分类筛选
            if (isset($_GET['category']) && !empty($_GET['category'])) {
                $args['category_name'] = sanitize_text_field($_GET['category']);
            }

            // 处理关键词搜索
            if (get_query_var('s')) {
                $args['s'] = get_query_var('s');
            } elseif (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();

                // 分页
                $total_pages = $articles_query->max_num_pages;
                if ($total_pages > 1) {
                    echo '<nav class="pagination">';
                    
                    $big = 999999999; 
                    
                    echo paginate_links(array(
                        'base' => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))),
                        'format' => '?paged=%#%',
                        'current' => max(1, $paged),
                        'total' => $articles_query->max_num_pages,
                        'prev_text' => '&laquo; 上一页',
                        'next_text' => '下一页 &raquo;',
                        'add_args' => array(
                            'category' => isset($_GET['category']) ? $_GET['category'] : ''
                        )
                    ));
                    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() ?>
