<?php
/**
 * Add List Block Posts
 *
 * @package Magazine Style
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;


function magazinestyle_listblockposts() {
      $categ = get_theme_mod('magazinestyle_list_block_posts_cat','all');			
		$category = !empty($categ) ? intval($categ) : 'all';

        //$category = 'all';
       // $show_featured_image = get_theme_mod('magazinestyle_header_style', 'enable');
        $num_posts = 5;
        $num_words = get_theme_mod('magazinestyle_listblock_posts_title', '45');
        //$num_words = 45;

        $args_query = array(
            'ignore_sticky_posts' => true,
            'posts_per_page' => $num_posts,
            'orderby' => 'date', // Always sort by views for Latest posts           
        );

        if (!empty($category) && $category !== 'all') {
            //$args_query['category_name'] = $category;
			$args_query['cat'] = $category;
        }

        $latest_posts_query = new WP_Query($args_query);

        echo '<div class="blockwidget">';
		echo '<div class="loading-indicator align-items-center"></div>';		
        if ($latest_posts_query->have_posts()) {
            echo ' <div class="row row-cols-2 row-cols-sm-2 row-cols-md-3 row-cols-lg-5 align-items-start post-list blockwidgetlist">'; // Add a class for the post list container
            while ($latest_posts_query->have_posts()) {
                $latest_posts_query->the_post();
                ?>
                <div class="col widgetblockpost">
                    <a href="<?php the_permalink(); ?>">
					<div class="post-thumbnail">
					    <?php if ( has_post_thumbnail() ) {the_post_thumbnail('medium');} else { ?>
                        <img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/nothumb.jpg" /><?php } ?>                       
					</div>				
					<div class="blocklinks"> 
                        <?php
							$title = get_the_title(); 
							$length = $num_words; 

							if (strlen($title) > $length) {
								$title = mb_substr($title, 0, $length) . '...';
							}

							echo $title; 
							?>
                    </div>						
                    </a>
                </div>
                <?php
            }
            echo '</div>';
            wp_reset_postdata();
        }

        
	// Add next and previous buttons
        echo '<div class="btn-group btn-group-sm post-pagination">';
		echo '<button class="prev-posts btn btn-outline-primary" data-category="' . esc_attr($category) . '" data-num-posts="' . esc_attr($num_posts) . '"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-left" viewBox="0 0 16 16">
		  <path fill-rule="evenodd" d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"/>
		</svg></button>';
		echo '<button class="next-posts btn btn-outline-primary" data-category="' . esc_attr($category) . '" data-num-posts="' . esc_attr($num_posts) . '"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-chevron-right" viewBox="0 0 16 16">
		  <path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z"/>
		</svg></button>';
		echo '</div>';
		echo '</div>';	
    }

// Add JavaScript/jQuery Code
function magazinestyle_listpostsblock_script() {
    ?>
    <script>
       jQuery(document).ready(function($) {
    var page = 1; // Initialize the current page
    var $loadingIndicator = $('.loading-indicator'); // Reference to the loading indicator
    var $loadingBlock = $('.blockwidgetlist'); // Reference to the loading indicator

    // Handle Next button click
    $('.next-posts').on('click', function() {
        var category = $(this).data('category');
        var numPosts = $(this).data('num-posts');
        page++; // Increment the page number
        showLoadingIndicator();
        loadPosts(page, category, numPosts);
    });

    // Handle Previous button click
    $('.prev-posts').on('click', function() {
        var category = $(this).data('category');
        var numPosts = $(this).data('num-posts');
        if (page > 1) {
            page--; // Decrement the page number if not on the first page
            showLoadingIndicator();
            loadPosts(page, category, numPosts);
        }
    });

    // Function to show the loading indicator
    function showLoadingIndicator() {
        $loadingIndicator.css('display', 'block');
        $loadingBlock.css('opacity', '0.3');
    }

    // Function to hide the loading indicator
    function hideLoadingIndicator() {
        $loadingIndicator.css('display', 'none');
		$loadingBlock.css('opacity', '1');
    }

    // Function to load posts via AJAX
    function loadPosts(page, category, numPosts) {
        var data = {
            action: 'magazinestyle_listpostsblock_more_posts',
            page: page,
            category: category,
            num_posts: numPosts
        };

        $.ajax({
            url: ajaxurl, // WordPress AJAX URL
            type: 'post',
            data: data,
            success: function(response) {
                hideLoadingIndicator(); // Hide the loading indicator
                if (response) {
                    $('.post-list').html(response);
                }
            },
            error: function() {
                hideLoadingIndicator(); // Hide the loading indicator in case of an error
            }
        });
    }
});

    </script>
    <?php
}
add_action('wp_footer', 'magazinestyle_listpostsblock_script');

// Create an AJAX Handler
function magazinestyle_listpostsblock_more_posts() {
    $category = sanitize_text_field($_POST['category']);
    $num_posts = intval($_POST['num_posts']);
    $page = intval($_POST['page']);

    $args_query = array(
        'ignore_sticky_posts' => true,
        'posts_per_page' => $num_posts,
        'orderby' => 'date',
        'paged' => $page,
    );

    if (!empty($category) && $category !== 'all') {
        $args_query['category_name'] = $category;
    }

    $latest_posts_query = new WP_Query($args_query);

    if ($latest_posts_query->have_posts()) {
        while ($latest_posts_query->have_posts()) {
            $latest_posts_query->the_post();
            ?>
         <div class="col widgetblockpost">
                    <a href="<?php the_permalink(); ?>">
					<div class="post-thumbnail">
					<?php if ( has_post_thumbnail() ) {the_post_thumbnail('medium');} else { ?><img src="<?php echo esc_url(get_template_directory_uri()); ?>/images/nothumb.jpg" /><?php } ?>                       
						<div class="blocklinks"><?php
							$title = get_the_title(); 
							$length = $num_words; 

							if (strlen($title) > $length) {
								$title = mb_substr($title, 0, $length) . '...';
							}

							echo $title; 
							?></div>						
						</div>				
                    </a>
                </div>
            <?php
        }
        wp_reset_postdata();
    }

    die(); // Important: This terminates the script and sends the response.
}
add_action('wp_ajax_load_more_posts', 'magazinestyle_listpostsblock_more_posts'); // For logged-in users
add_action('wp_ajax_nopriv_load_more_posts', 'magazinestyle_listpostsblock_more_posts'); // For non-logged-in users
?>
