<?php
function allNews_shortcode($atts) {
    ob_start(); // Start output buffering

    // Define default attributes and extract shortcode attributes
    $atts = shortcode_atts(array(
        'posts_per_page' => 12, // Default value for posts per page
    ), $atts);

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    
    $news_args = array(
        'post_type' => array('post'),
        'posts_per_page' => $atts['posts_per_page'],
        'category_name' => 'news, blog',
        'paged' => $paged,
    );

    $news_query = new WP_Query($news_args);
    if ($news_query->have_posts()) :
        ?>
        <div class="row">
            <?php while ($news_query->have_posts()) : $news_query->the_post(); ?>
                <div class="col-xl-3 col-lg-4 col-sm-6 kpy-news">
                    <article>
                        <a href="<?= esc_url(get_permalink()); ?>">
                            <div class="card shadow-sm mb-3 border-0" data-aos="fade-up">
                                <div class="post-thumbnail">
                                    <?php // Display the post thumbnail
                                    if (has_post_thumbnail()) {
                                        the_post_thumbnail('medium');
                                    } else {
                                        echo '<img src="' . get_template_directory_uri() . '/assets/images/photo-placeholder.jpg" alt="NGO" class="img-fluid"/>';
                                    }
                                    ?>
                                </div>
                                <div class="card-body">
                                    <h3><?php the_title(); ?></h3>
                                    <div class="catz">
                                        <i class="bi bi-calendar-check"></i> <?php echo get_the_date(); ?>
                                    </div>
                                    <a href="<?= esc_url(get_permalink()); ?>" class="btn btn-outline-info read-more">Read More</a>
                                </div>
                            </div>
                        </a>
                    </article>
                </div>
            <?php endwhile; ?>
        </div>
        <?php
        // Pagination
        $big = 999999999; // need an unlikely integer
        echo '<div class="pagination">';
        echo paginate_links(array(
            'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
            'format' => '?paged=%#%',
            'current' => max(1, $paged),
            'total' => $news_query->max_num_pages,
        ));
        echo '</div>';
        wp_reset_postdata();
    else :
        echo 'No news found.';
    endif;

    return ob_get_clean(); // Return the buffered content
}

// Register the shortcode
add_shortcode('all_news', 'allNews_shortcode');
?>
