<?php
/**
 * News区块模板 - 3行4列卡片布局
 * 支持自定义器设置和短代码调用
 * 
 * 功能特性：
 * 1. 支持查询当前分类文章内容（在分类页面自动使用当前分类）
 * 2. 支持指定分类ID查询特定分类文章（支持多个ID，用逗号分隔）
 * 3. 分类ID优先级：短代码参数 > 当前分类页面 > 自定义器设置
 * 
 * 使用方法：
 * - 在分类页面使用：[nenghui_news_grid] （自动显示当前分类文章）
 * - 指定分类使用：[nenghui_news_grid category_id="5"] （显示分类ID为5的文章）
 * - 指定多个分类：[nenghui_news_grid category_id="5,6,7"] （显示分类ID为5、6、7的文章）
 * - 显示所有文章：[nenghui_news_grid category_id=""] （覆盖当前分类，显示所有文章）
 */
 
 // 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 检查是否通过短代码调用
global $news_shortcode_atts;

// 确保 $news_shortcode_atts 是数组
if (!is_array($news_shortcode_atts)) {
    $news_shortcode_atts = array();
}

// 获取自定义器设置，如果有短代码参数则优先使用短代码参数
$news_title = !empty($news_shortcode_atts['title']) ? $news_shortcode_atts['title'] : get_theme_mod('news_title', 'NEWS');

// 分类ID优先级：短代码参数 > 当前分类页面 > 自定义器设置
$news_category_id = '';
$news_tag_id = '';
$news_author_id = '';

if (!empty($news_shortcode_atts['category_id'])) {
    // 优先使用短代码指定的分类ID
    $news_category_id = $news_shortcode_atts['category_id'];
} elseif (is_category()) {
    // 如果是分类页面，使用当前分类ID
    $news_category_id = get_queried_object_id();
} elseif (is_tag()) {
    // 如果是标签页面
    $news_tag_id = get_queried_object_id();
} elseif (is_author()) {
    // 如果是作者页面
    $news_author_id = get_queried_object_id();
} else {
    // 否则使用自定义器设置的分类ID
    $news_category_id = get_theme_mod('news_category_id', '');
}

$news_order_by = !empty($news_shortcode_atts['order_by']) ? $news_shortcode_atts['order_by'] : get_theme_mod('news_order_by', 'date');
$news_order = !empty($news_shortcode_atts['order']) ? $news_shortcode_atts['order'] : get_theme_mod('news_order', 'DESC');

// 检查是否启用分页
$enable_pagination = !empty($news_shortcode_atts['enable_pagination']) ? wp_validate_boolean($news_shortcode_atts['enable_pagination']) : get_theme_mod('news_enable_pagination', false);

// 根据是否启用分页设置文章数量
if ($enable_pagination) {
    $news_posts_count = !empty($news_shortcode_atts['posts_per_page']) ? intval($news_shortcode_atts['posts_per_page']) : get_theme_mod('news_posts_per_page', 6);
} else {
    $news_posts_count = !empty($news_shortcode_atts['posts_count']) ? intval($news_shortcode_atts['posts_count']) : get_theme_mod('news_posts_count', 12);
    // 确保文章数量为12（3行4列）
    if ($news_posts_count < 12) {
        $news_posts_count = 12;
    }
}

// 设置容器ID和CSS类
$container_id = !empty($news_shortcode_atts['id']) ? $news_shortcode_atts['id'] : 'nenghui-news-block';
$container_class = !empty($news_shortcode_atts['class']) ? $news_shortcode_atts['class'] : '';

// 获取当前页码
$current_page = max(1, get_query_var('paged', 1));
if (!$current_page) {
    $current_page = max(1, get_query_var('page', 1));
}

// 构建查询参数
$query_args = array(
    'post_type' => 'post',
    'posts_per_page' => $news_posts_count,
    'orderby' => $news_order_by,
    'order' => $news_order,
    'post_status' => 'publish'
);

// 如果启用分页，添加分页参数
if ($enable_pagination) {
    $query_args['paged'] = $current_page;
}

// 如果指定了分类ID，添加分类过滤
if (!empty($news_category_id)) {
    // 支持多分类（逗号分隔），清理可能存在的空格
    if (strpos($news_category_id, ',') !== false) {
        $news_category_id = implode(',', array_map('trim', explode(',', $news_category_id)));
    }
    $query_args['cat'] = $news_category_id;
}

// 如果是标签页面
if (!empty($news_tag_id)) {
    $query_args['tag_id'] = $news_tag_id;
}

// 如果是作者页面
if (!empty($news_author_id)) {
    $query_args['author'] = $news_author_id;
}

if (is_archive() && !is_category() && !is_tag() && !is_author()) {
    // 处理其他类型的存档页面（如日期存档）
    // 通常 WP_Query 会自动处理，但在自定义查询中我们需要显式处理或者不限制分类
}

// 查询文章
$news_query = new WP_Query($query_args);
?>

<style>
/* News区块样式 - 3行4列卡片布局 */
.news-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 60px 20px;
}

.news-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 50px;
}

.news-title {
    font-size: 36px;
    color: #333;
    margin: 0;
}



.news-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24px;
}

.news-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    cursor: pointer;
}

.news-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
}

.news-card-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.news-card-content {
    padding: 20px;
}

.news-card-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 8px;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.news-card-description {
    font-size: 12px;
    color: #666;
    line-height: 1.6;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    margin-bottom: 12px;
}

.news-card-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #999;
}

.news-card-category {
    background: #f0f8ff;
    color: #007cba;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
}

.news-card-date {
    color: #999;
}

/* 分页样式 */
.news-pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 40px;
    gap: 8px;
}

.news-pagination a,
.news-pagination span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 40px;
    height: 40px;
    padding: 0 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    text-decoration: none;
    color: #333;
    font-size: 14px;
    margin: 5px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.news-pagination a:hover {
    background-color: #0069a0;
    color: white;
    border-color: #0069a0;
    transition: all 0.3s ease;
}

.news-pagination .current {
    background-color: #007cba;
    border-color: #007cba;
    color: white;
}

.news-pagination .dots {
    border: none;
    background: none;
    color: #999;
}

.news-pagination .prev,
.news-pagination .next {
    padding: 0 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .news-grid {
        grid-template-columns: repeat(3, 1fr);
    }
    
    .news-grid.pagination-enabled {
        grid-template-rows: auto;
    }
}

@media (max-width: 768px) {
    .news-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .news-grid.pagination-enabled {
        grid-template-rows: auto;
    }
    
    .news-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .news-title {
        font-size: 28px;
    }
    
    .news-pagination a,
    .news-pagination span {
        min-width: 36px;
        height: 36px;
        font-size: 13px;
    }
}

@media (max-width: 480px) {
    .news-grid {
        grid-template-columns: 1fr;
    }
    
    .news-grid.pagination-enabled {
        grid-template-rows: auto;
    }
    
    .news-container {
        padding: 40px 15px;
    }
    
    .news-pagination {
        gap: 4px;
        flex-wrap: wrap;
        justify-content: center;
    }
    
    .news-pagination a,
    .news-pagination span {
        min-width: 36px;
        height: 36px;
        padding: 0 8px;
        font-size: 13px;
    }

    .news-pagination .prev,
    .news-pagination .next {
        width: 100%;
        order: -1; /* 将上一页/下一页在极小屏幕下排在第一行或最后一行，或者根据需要调整 */
        margin-bottom: 8px;
    }
    
    .news-pagination .prev {
        order: 1;
    }
    .news-pagination .next {
        order: 3;
    }
    .news-pagination-numbers {
        display: flex;
        gap: 4px;
        order: 2;
    }
}

@media (max-width: 480px) {
    .news-pagination {
        gap: 5px;
    }
    
    .news-pagination a,
    .news-pagination span {
        min-width: 32px;
        height: 32px;
        padding: 0 6px;
        font-size: 12px;
    }
    
    /* 在极小屏幕下，隐藏非必要的页码，只保留关键页码 */
    .news-pagination-numbers a.page-num:not(.first):not(.last):not(.current-neighbor):not(.current) {
        display: none;
    }
}
</style>

<div id="<?php echo esc_attr($container_id); ?>" class="news-section news-container <?php echo esc_attr($container_class); ?>" data-aos="fade-up">
    <div class="news-header" data-aos="fade-up" data-aos-delay="200">
        <h1 class="news-title"><?php echo esc_html($news_title); ?></h1>
    </div>

    <div class="news-grid <?php echo $enable_pagination ? 'pagination-enabled' : ''; ?>" data-aos="fade-up" data-aos-delay="400">
        <?php
        if ($news_query->have_posts()) :
            while ($news_query->have_posts()) : $news_query->the_post();
                // 获取文章分类
                $categories = get_the_category();
                $category_name = !empty($categories) ? $categories[0]->name : 'News';
                
                // 获取文章摘要
                $excerpt = get_the_excerpt();
                if (empty($excerpt)) {
                    $excerpt = wp_trim_words(get_the_content(), 30);
                }
                
                // 获取特色图像
                $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
                if (empty($thumbnail_url)) {
                    $thumbnail_url = get_template_directory_uri() . '/assets/images/NaN-img.png';
                }
        ?>
        <div class="news-card" data-aos="fade-up" data-aos-delay="<?php echo (200 * ($news_query->current_post + 1)); ?>">
            <a href="<?php the_permalink(); ?>">
                <img src="<?php echo esc_url($thumbnail_url); ?>" alt="<?php the_title_attribute(); ?>" class="news-card-image">
                <div class="news-card-content">
                    <h3 class="news-card-title"><?php the_title(); ?></h3>
                    <p class="news-card-description"><?php echo esc_html($excerpt); ?></p>
                    <div class="news-card-meta">
                        <span class="news-card-category"><?php echo esc_html($category_name); ?></span>
                        <span class="news-card-date"><?php echo date('M j, Y', get_the_time('U')); ?></span>
                    </div>
                </div>
            </a>
        </div>
        <?php
            endwhile;
        ?>
    </div>

    <?php
            // 如果启用分页，显示分页组件
            if ($enable_pagination && $news_query->max_num_pages > 1) :
                $total_pages = $news_query->max_num_pages;
                $current_page = max(1, get_query_var('paged', 1));
                if (!$current_page) {
                    $current_page = max(1, get_query_var('page', 1));
                }
                
                echo '<div class="news-pagination" data-aos="fade-up" data-aos-delay="600">';
                
                // 上一页链接
                if ($current_page > 1) {
                    $prev_link = get_pagenum_link($current_page - 1);
                    echo '<a href="' . esc_url($prev_link) . '" class="prev">‹ Previous</a>';
                }

                echo '<div class="news-pagination-numbers">';
                
                // 页码链接
                $start_page = max(1, $current_page - 2);
                $end_page = min($total_pages, $current_page + 2);
                
                // 如果不是从第1页开始，显示第1页和省略号
                if ($start_page > 1) {
                    echo '<a href="' . esc_url(get_pagenum_link(1)) . '" class="page-num first">1</a>';
                    if ($start_page > 2) {
                        echo '<span class="dots">...</span>';
                    }
                }
                
                // 显示页码
                for ($i = $start_page; $i <= $end_page; $i++) {
                    $class = 'page-num';
                    if ($i == $current_page) {
                        $class .= ' current';
                        echo '<span class="' . $class . '">' . $i . '</span>';
                    } else {
                        if ($i == $current_page - 1 || $i == $current_page + 1) {
                            $class .= ' current-neighbor';
                        }
                        echo '<a href="' . esc_url(get_pagenum_link($i)) . '" class="' . $class . '">' . $i . '</a>';
                    }
                }
                
                // 如果不是到最后一页，显示省略号和最后一页
                if ($end_page < $total_pages) {
                    if ($end_page < $total_pages - 1) {
                        echo '<span class="dots">...</span>';
                    }
                    echo '<a href="' . esc_url(get_pagenum_link($total_pages)) . '" class="page-num last">' . $total_pages . '</a>';
                }

                echo '</div>';
                
                // 下一页链接
                if ($current_page < $total_pages) {
                    $next_link = get_pagenum_link($current_page + 1);
                    echo '<a href="' . esc_url($next_link) . '" class="next">Next ›</a>';
                }
                
                echo '</div>';
            endif;
            
            wp_reset_postdata();
        else :
        ?>
        <div class="news-card" style="grid-column: 1 / -1; text-align: center; padding: 40px;">
            <h3>No Posts Found</h3>
            <p>Please add some posts to display in this block.</p>
        </div>
        <?php endif; ?>
</div>