<?php

include_module('blog');

function get_posts_by_page_and_category($paged = 1, $category = '') {
    $args = [
        'post_type' => 'post',
        'posts_per_page' => 9, // Adjust the number of posts per page
        'paged' => intval($paged) + 1,
    ];

    if (!empty($category)) {
        $args['tax_query'] = [
            [
                'taxonomy' => 'category',
                'field' => 'slug', // or 'term_id', 'name' depending on how you identify categories
                'terms' => $category,
            ],
        ];
    }
    $q = new WP_Query($args);
    return new Timber\PostQuery($q);
}

function ajax_load_blog_posts() {
    $page_num = isset($_POST['page_num']) ? sanitize_text_field($_POST['page_num']) : '';
    $context = Timber::context();
    $context['posts'] = get_posts_by_page_and_category($page_num);
    $html = Timber::compile('/blog/components/news-list/component-template.twig', $context);
    echo $html;
    wp_die();
}


add_action('wp_ajax_load_blog_posts', 'ajax_load_blog_posts'); 
add_action('wp_ajax_nopriv_load_blog_posts', 'ajax_load_blog_posts'); 


