<?php
class wrockmetro_block_posts_widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'wrockmetro_block_posts_widget',
            'Wrock Metro Categories',	
            array(
			'classname' => 'wrockmetro_widget',	
			'customize_selective_refresh' => true,
			'description' => 'A widget to display latest posts Block with options.')
        );

    }

    public function widget($args, $instance) {
        $category = isset($instance['category']) ? $instance['category'] : '';
        $show_featured_image = isset($instance['show_featured_image']) ? $instance['show_featured_image'] : true;
        $num_posts = isset($instance['num_posts']) ? $instance['num_posts'] : 5;

        $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;
        }

        $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">'; // 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" alt="<?php the_title(); ?>" /><?php } ?>                       
						</div>				
						<div class="blocklinks"><?php the_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>";
	
echo '</div>';	
    }

    public function form($instance) {
        $category = isset($instance['category']) ? $instance['category'] : '';
        $show_featured_image = isset($instance['show_featured_image']) ? $instance['show_featured_image'] : true;      
        $num_posts = isset($instance['num_posts']) ? $instance['num_posts'] : 5;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('category'); ?>">Choose Category:</label>
            <?php
            $categories = get_categories(array('hide_empty' => 0));
            ?>
            <select id="<?php echo $this->get_field_id('category'); ?>"
                    name="<?php echo $this->get_field_name('category'); ?>">
                <option value="all"<?php selected($category, 'all'); ?>>All Categories</option>
                <?php foreach ($categories as $cat) : ?>
                    <option value="<?php echo esc_attr($cat->slug); ?>" <?php selected($category, $cat->slug); ?>><?php echo esc_html($cat->name); ?></option>
                <?php endforeach; ?>
            </select>
        </p>
        <p>
            <input type="checkbox" id="<?php echo $this->get_field_id('show_featured_image'); ?>"
                   name="<?php echo $this->get_field_name('show_featured_image'); ?>" <?php checked($show_featured_image, true); ?>>
            <label for="<?php echo $this->get_field_id('show_featured_image'); ?>">Show Featured Image</label>
        </p>
        <p>
            <label for="<?php echo $this->get_field_id('num_posts'); ?>">Number of Latest Posts to Display:</label>
            <input type="number" id="<?php echo $this->get_field_id('num_posts'); ?>"
                   name="<?php echo $this->get_field_name('num_posts'); ?>" value="<?php echo $num_posts; ?>">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();        
        $instance['category'] = !empty($new_instance['category']) ? sanitize_text_field($new_instance['category']) : 'all';
        $instance['show_featured_image'] = isset($new_instance['show_featured_image']) ? true : false;
        $instance['num_posts'] = !empty($new_instance['num_posts']) ? intval($new_instance['num_posts']) : 5;
        return $instance;
    }
}

function register_wrockmetro_block_posts_widget() {
    register_widget('wrockmetro_block_posts_widget');
}
add_action('widgets_init', 'register_wrockmetro_block_posts_widget');

// Add JavaScript/jQuery Code
function add_custom_widget_script() {
    ?>
    <script>
       jQuery(document).ready(function($) {
    var page = 1; // Initialize the current page
    var $loadingIndicator = $('.loading-indicator'); // Reference to the loading indicator
    var $loadingBlock = $('.blockwidget'); // 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: 'load_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', 'add_custom_widget_script');

// Create an AJAX Handler
function load_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" alt="<?php the_title(); ?>" /><?php } ?>                       
						<div class="blocklinks"><?php the_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', 'load_more_posts'); // For logged-in users
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts'); // For non-logged-in users
?>
