<?php 

class magazinestyle_Index_Posts_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'magazinestyle_Index_Posts_Widget',
            'Magazine Style Index Posts',
            array('description' => 'Category Widget for Index Posts.')
        );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'admin_footer-widgets.php', array( $this, 'print_scripts' ), 9999 );
    }
public function enqueue_scripts( $hook_suffix ) {
	                if ( 'widgets.php' !== $hook_suffix ) {
	                        return;
	                }
	
	                wp_enqueue_style( 'wp-color-picker' );
	                wp_enqueue_script( 'wp-color-picker' );
	                wp_enqueue_script( 'underscore' );
	        }
			  public function print_scripts() {
	                ?>
	                <script>
	                        ( function( $ ){
	                                function initColorPicker( widget ) {
	                                        widget.find( '.color-picker' ).wpColorPicker( {
	                                                change: _.throttle( function() { // For Customizer
	                                                        $(this).trigger( 'change' );
	                                                }, 3000 )
	                                        });
	                                }
	
	                                function onFormUpdate( event, widget ) {
	                                        initColorPicker( widget );
	                                }
	
	                                $( document ).on( 'widget-added widget-updated', onFormUpdate );
	
	                                $( document ).ready( function() {
	                                        $( '#widgets-right .widget:has(.color-picker)' ).each( function () {
	                                                initColorPicker( $( this ) );
	                                        } );
	                                } );
	                        }( jQuery ) );
	                </script>
	                <?php
	        }
public function widget($args, $instance) {
    $title = isset($instance['title']) ? $instance['title'] : 'Latest Posts';
    $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;
	$show_view_counts = isset($instance['show_view_counts']) ? $instance['show_view_counts'] : true;
	$show_post_date = isset($instance['show_post_date']) ? $instance['show_post_date'] : true;
	$widget_color = isset($instance['widget_color']) ? $instance['widget_color'] : '#333333';
	$widget_fontcolor = isset($instance['widget_fontcolor']) ? $instance['widget_fontcolor'] : '#ffffff';
	

    $args_query = array(
       // 'ignore_sticky_posts' => true,
        'posts_per_page' => $num_posts,
        'orderby' => 'post_date',
		'post_status' => 'publish',		// Always sort by date for Latest posts
    );
	$catid = get_cat_ID($category);
	$catlink = get_category_link($catid);

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

    $latest_posts_query = new WP_Query($args_query);
	
    echo '<div class="magazinestyle-indexwid">';
    echo '<h2 class="wp-block-heading" style="border-color:' . $widget_color . ' !important;"><a style="color:' .$widget_fontcolor . ' !important;background:' . $widget_color . ' !important;" href="'. $catlink  . '">' . apply_filters('widget_title', $title) . '</a><a href="'. $catlink  . '" class="viewposts" title="$category">View all <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-right-fill" viewBox="0 0 16 16">
    <path d="m12.14 8.753-5.482 4.796c-.646.566-1.658.106-1.658-.753V3.204a1 1 0 0 1 1.659-.753l5.48 4.796a1 1 0 0 1 0 1.506z"/>
  </svg></a></h2>';
    echo '<div class="tst">';

    if ($latest_posts_query->have_posts()) {
        echo '<div class="row">';
        $first_post = true; // Flag to identify the first post

        echo '<div class="col-md-5">'; // Open the first col-md-6 div

        while ($latest_posts_query->have_posts()) {
            $latest_posts_query->the_post();

            if ($first_post) {
				$link = get_permalink();				
				 $title = get_the_title();
				 if (get_theme_mod('magazinestyle_blogmeta_comments') !== 'disable') { ?>
				<div class="comment block"><p><?php printf( _nx( '1', '%1$s', get_comments_number(), 'comments title', 'magazine-style' ), number_format_i18n( get_comments_number() ) ); ?><p></div><?php }
                echo '<a href="' . get_permalink() . '">';
                if ($show_featured_image && has_post_thumbnail()) {
                    echo '<div class="post-thumbnail-block">';
                    the_post_thumbnail('large');                    
                    echo '</div>';
                }
				echo '<h4>' . $title . '</h4>';
                echo '</a>';
				 if ($show_view_counts) : display_post_view_count();  endif; 
			if ($show_post_date) : echo '<span class="posted-on"><time>'.esc_attr( get_the_date()) . '</time></span>';  endif;
				echo the_excerpt();
                $first_post = false; // Set to false after the first post
            } else {
                break; // Exit the loop after the first post
            }
        }

        echo '</div>'; // Close the first col-md-6 div

        // Open another col-md-6 div to combine the rest of the posts
        echo '<div class="col-md-7"><ul>';

        while ($latest_posts_query->have_posts()) {
            $latest_posts_query->the_post();
            echo '<li><a href="' . get_permalink() . '">';
            if ($show_featured_image && has_post_thumbnail()) {
                echo '<div class="post-thumbnail">';
                the_post_thumbnail(array(80, 80));               
                echo '</div>';
            }
			 echo '<h4>' . get_the_title() . '</h4>';
            echo '</a>';
			 if ($show_view_counts) : display_post_view_count();  endif; 
			if ($show_post_date) : echo '<span class="posted-on"><time>'.esc_attr( get_the_date()) . '</time></span>';  endif;
            echo '</li>';
        }

        echo '</ul></div>'; // Close the combined col-md-6 div

        wp_reset_postdata();
        echo '</div>'; // Close the row
    }

    echo '</div>'; // Close the tst div
    echo '</div>'; // Close the magazinestyle-latest div
}
    public function form($instance) {
        $title = isset($instance['title']) ? $instance['title'] : 'Latest Posts';
        $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;
		$show_view_counts = isset($instance['show_view_counts']) ? $instance['show_view_counts'] : true;
		$show_post_date = isset($instance['show_post_date']) ? $instance['show_post_date'] : true;
		$widget_color = isset($instance['widget_color']) ? $instance['widget_color'] : '#333333'; 
		$widget_fontcolor = isset($instance['widget_fontcolor']) ? $instance['widget_fontcolor'] : '#ffffff'; 
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>">Widget Title:</label>
            <input type="text" id="<?php echo $this->get_field_id('title'); ?>"
                   name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>">
        </p>
		<p>
			<label for="<?php echo $this->get_field_id('widget_color'); ?>">Widget Color:</label></br>
			<input type="text" class="color-picker" id="<?php echo $this->get_field_id('widget_color'); ?>"
               name="<?php echo $this->get_field_name('widget_color'); ?>" value="<?php echo esc_attr($widget_color); ?>">
		</p>
		<p>
			<label for="<?php echo $this->get_field_id('widget_fontcolor'); ?>">Widget Font Color:</label></br>
			<input type="text" class="color-picker" id="<?php echo $this->get_field_id('widget_fontcolor'); ?>"
               name="<?php echo $this->get_field_name('widget_fontcolor'); ?>" value="<?php echo esc_attr($widget_fontcolor); ?>">
		</p>
        <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>
            <input type="checkbox" id="<?php echo $this->get_field_id('show_view_counts'); ?>"
                   name="<?php echo $this->get_field_name('show_view_counts'); ?>" <?php checked($show_view_counts, true); ?>>
            <label for="<?php echo $this->get_field_id('show_view_counts'); ?>">Show View Counts</label>
        </p>
		  <p>
            <input type="checkbox" id="<?php echo $this->get_field_id('show_post_date'); ?>"
                   name="<?php echo $this->get_field_name('show_post_date'); ?>" <?php checked($show_post_date, true); ?>>
            <label for="<?php echo $this->get_field_id('show_post_date'); ?>">Show Post Date</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['title'] = !empty($new_instance['title']) ? sanitize_text_field($new_instance['title']) : 'Latest Posts';
        $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['show_view_counts'] = isset($new_instance['show_view_counts']) ? true : false;
		$instance['show_post_date'] = isset($new_instance['show_post_date']) ? true : false;
        $instance['num_posts'] = !empty($new_instance['num_posts']) ? intval($new_instance['num_posts']) : 5;
		$instance['widget_color'] = sanitize_hex_color($new_instance['widget_color']);
		$instance['widget_fontcolor'] = sanitize_hex_color($new_instance['widget_fontcolor']);
        return $instance;
    }
}

function register_magazinestyle_Index_Posts_Widget() {
    register_widget('magazinestyle_Index_Posts_Widget');
}
add_action('widgets_init', 'register_magazinestyle_Index_Posts_Widget');
