<?php

class digital_News_Posts_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'digital_News_Posts_Widget',
            'Digital News Posts',
            array('description' => 'Category Widget for News 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'] : 'News 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;
    $num_rows = isset($instance['num_rows']) ? $instance['num_rows'] : 1;
	$widget_fontcolor = isset($instance['widget_fontcolor']) ? $instance['widget_fontcolor'] : '#e40e0e';
	
    $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="digital-news-widget">';
    echo '<h3 class="wp-block-heading""><a style="color:' .$widget_fontcolor . ' !important;" href="'. $catlink  . '">' . apply_filters('widget_title', $title) . '</a></h3>';
    echo '<div class="row row-cols-'.$num_rows.' g-2">';

    if ($latest_posts_query->have_posts()) {
        while ($latest_posts_query->have_posts()) {
            $latest_posts_query->the_post();
       echo '<div class="d-flex align-items-center mb-4">';
               
       if ($show_featured_image && has_post_thumbnail()) {
        echo '<div class="me-2">';
        echo '<a href="' . esc_url(get_permalink(get_the_ID())) . '">';
        echo get_the_post_thumbnail($post->ID, 'digital-post-thumbnail');
        echo '</a>';
        echo '</div>';
        }
        echo '<header class="entry-header">';
        the_title(
            sprintf('<h2 class="entry-title mb-0"><a href="%s" rel="bookmark">', esc_url(get_permalink())),
            '</a></h2>'
        );
        echo '</header>';
        echo '</div>';
        }
        echo '</div>';
        wp_reset_postdata();
    }       

    echo '</div>'; // Close the digital-latest div
}
    public function form($instance) {
        $title = isset($instance['title']) ? $instance['title'] : 'News 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;
        $num_rows = isset($instance['num_rows']) ? $instance['num_rows'] : 2;
		$widget_fontcolor = isset($instance['widget_fontcolor']) ? $instance['widget_fontcolor'] : '#e40e0e'; 
        ?>
        <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_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>
            <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>
        <p>
            <label for="<?php echo $this->get_field_id('num_rows'); ?>">Number of columns:</label>
            <input type="number" id="<?php echo $this->get_field_id('num_rows'); ?>"
                   name="<?php echo $this->get_field_name('num_rows'); ?>" value="<?php echo $num_rows; ?>">
        </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['num_posts'] = !empty($new_instance['num_posts']) ? intval($new_instance['num_posts']) : 5;
        $instance['num_rows'] = !empty($new_instance['num_rows']) ? intval($new_instance['num_rows']) : 1;
		$instance['widget_color'] = sanitize_hex_color($new_instance['widget_color']);
		$instance['widget_fontcolor'] = sanitize_hex_color($new_instance['widget_fontcolor']);
        return $instance;
    }
}

function register_digital_News_Posts_Widget() {
    register_widget('digital_News_Posts_Widget');
}
add_action('widgets_init', 'register_digital_News_Posts_Widget');
