<?php
/**
 * Block News Template
 * 新闻区块模板
 *
 * @package Nenghui Energy Theme
 * @since 1.0.0
 *
 * @param array $args {
 *     Optional. Array of arguments.
 *     @type string $category    文章分类slug或ID，默认为空（所有分类）
 *     @type int    $posts_count 显示文章数量，默认为4
 *     @type string $title       区块标题，默认为"新闻资讯"
 *     @type string $subtitle    区块副标题，默认为"NEWS"
 * }
 */

// 设置默认参数
$defaults = array(
    'category'    => '',
    'posts_count' => 4,
    'title'       => '新闻资讯',
    'subtitle'    => 'NEWS'
);

$args = wp_parse_args($args ?? array(), $defaults);

// 构建查询参数
$query_args = array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => $args['posts_count'],
    'orderby'        => 'date',
    'order'          => 'DESC',
    // 移除特色图片强制要求，允许显示没有特色图片的文章
    // 'meta_query'     => array(
    //     array(
    //         'key'     => '_thumbnail_id',
    //         'compare' => 'EXISTS'
    //     )
    // )
);

// 如果指定了分类，添加分类查询
if (!empty($args['category'])) {
    if (is_numeric($args['category'])) {
        // 使用分类ID
        $query_args['cat'] = intval($args['category']);
    } else {
        // 使用分类别名
        $query_args['category_name'] = sanitize_text_field($args['category']);
    }
    
    // 调试信息：记录分类查询参数
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('News Block Category Query: ' . print_r(array(
            'category_param' => $args['category'],
            'is_numeric' => is_numeric($args['category']),
            'query_args' => $query_args
        ), true));
    }
}

// 尝试获取缓存
$cache_key = 'news_block_' . md5(serialize($query_args) . (function_exists('get_theme_cache_version') ? get_theme_cache_version() : ''));
$posts = get_transient($cache_key);

if ($posts === false) {
    // 执行查询
    $news_query = new WP_Query($query_args);
    $posts = $news_query->posts;
    
    // 如果有文章，设置缓存（缓存1小时）
    if (!empty($posts)) {
        set_transient($cache_key, $posts, 3600);
    }
}

// 如果没有文章，显示提示信息
if (empty($posts)) {
    wp_reset_postdata();
    echo '<div class="news-container"><div class="news-header"><p>' . esc_html($args['subtitle']) . '</p><h1>' . esc_html($args['title']) . '</h1></div><div class="no-posts-message"><p>暂无相关文章</p></div></div>';
    return;
}

// 获取文章数组
$featured_post = $posts[0] ?? null;
$other_posts = array_slice($posts, 1, 3);
?>

<div class="news-container">
    <!-- 头部导航 -->
    <div class="news-header">
        <p><?php echo esc_html($args['subtitle']); ?></p>
        <h1><?php echo esc_html($args['title']); ?></h1>
        <div class="w-12 h-1 bg-primary mt-2"></div>
    </div>
    
    <?php if ($featured_post) : ?>
    <!-- 主要新闻条目 -->
    <div class="main-news">
        <div class="main-news-left">
            <h2>
                <a href="<?php echo esc_url(get_permalink($featured_post->ID)); ?>">
                    <?php echo esc_html(get_the_title($featured_post->ID)); ?>
                </a>
            </h2>
            <?php 
            $excerpt = get_the_excerpt($featured_post->ID);
            if ($excerpt) : 
            ?>
            <p><?php echo esc_html(wp_trim_words($excerpt, 20, '...')); ?></p>
            <?php endif; ?>
            <div class="main-news-info">
                <span>
                    <i class="fas fa-calendar-alt"></i> 
                    <?php echo esc_html(get_the_date('Y.m.d', $featured_post->ID)); ?>
                </span>
                <?php 
                $post_views = get_post_meta($featured_post->ID, 'post_views_count', true);
                if ($post_views) : 
                ?>
                <span>
                    <i class="fas fa-eye"></i> 
                    <?php echo esc_html(number_format($post_views)); ?>
                </span>
                <?php endif; ?>
            </div>
        </div>
        <div class="main-news-right">
            <?php if (has_post_thumbnail($featured_post->ID)) : ?>
                <a href="<?php echo esc_url(get_permalink($featured_post->ID)); ?>">
                    <?php echo get_the_post_thumbnail($featured_post->ID, 'news-large', array(
                        'alt' => esc_attr(get_the_title($featured_post->ID))
                    )); ?>
                </a>
            <?php else : ?>
                <div class="no-image-placeholder">
                    <i class="fas fa-image"></i>
                    <span>暂无图片</span>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($other_posts)) : ?>
    <!-- 新闻卡片列表 -->
    <div class="news-grid">
        <?php foreach ($other_posts as $post) : ?>
        <div class="news-card">
            <?php if (has_post_thumbnail($post->ID)) : ?>
                <a href="<?php echo esc_url(get_permalink($post->ID)); ?>">
                    <?php echo get_the_post_thumbnail($post->ID, 'news-medium', array(
                        'alt' => esc_attr(get_the_title($post->ID))
                    )); ?>
                </a>
            <?php else : ?>
                <div class="no-image-placeholder">
                    <i class="fas fa-image"></i>
                    <span>暂无图片</span>
                </div>
            <?php endif; ?>
            <div class="news-card-content">
                <h3>
                    <a href="<?php echo esc_url(get_permalink($post->ID)); ?>">
                        <?php echo esc_html(get_the_title($post->ID)); ?>
                    </a>
                </h3>
                <div class="news-card-info">
                    <span>
                        <i class="fas fa-calendar-alt"></i> 
                        <?php echo esc_html(get_the_date('Y.m.d', $post->ID)); ?>
                    </span>
                    <?php 
                    $post_views = get_post_meta($post->ID, 'post_views_count', true);
                    if ($post_views) : 
                    ?>
                    <span>
                        <i class="fas fa-eye"></i> 
                        <?php echo esc_html(number_format($post_views)); ?>
                    </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<?php
// 重置全局 $post 对象
wp_reset_postdata();
?>