<?php
/*-----------------------------------------------------------------------------------*/
/*  Select Categorie Home widget
/*-----------------------------------------------------------------------------------*/ 
function selected_home_categorie_widgets() {
	/*
	https://wordpress.stackexchange.com/questions/310535/multiple-selection-for-wordpress-widget
	*/
    register_widget( 'selected_home_categories_widgets' );
}
add_action( 'widgets_init', 'selected_home_categorie_widgets' );

class selected_home_categories_widgets extends WP_Widget {

	function __construct() { 
	parent::__construct('selected_home_categories_widgets', __('(MDR) Home Selected Category', strtolower(THEMES_NAMES)), 
	array( 'description' => __( 'Selected Categorie Home ', strtolower(THEMES_NAMES) ), ) 
	);
	 
    }
 
	
	public function form( $instance ) {	
	$instance = wp_parse_args(
	(array) $instance,
	array(
	'title'	=> __( 'List Categorie', THEMES_NAMES ), 
	'title_button'	=> 'Show More',
	'title_link'	=> home_url( '/#your_link_categorie' ),  
	)
	);
	
    $title	= isset($instance[ 'title' ]) ? $instance[ 'title' ] : 'Categories';
    
	$title_link	= $instance['title_link'];	 
	$title_button	= !empty( $instance['title_button'] ) ? $instance['title_button'] : ''; 


	$selected_cats_str = !empty($instance['select_categorie']) ? $instance['select_categorie'] : '';
	$selected_cats     = $selected_cats_str ? array_map('intval', explode(',', $selected_cats_str)) : array();

	// Get all categories
	$categories = get_categories(array(
		'hide_empty' => false,
	));
		
    ?>
	<p class="info-notice danger"><?php _e('Home Category by Selected', THEMES_NAMES); ?> </p>
	<hr />
    <p>
	<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title', THEMES_NAMES); ?></label>
	<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" style="width: 100%;" value="<?php echo $title; ?>"/>
    </p>
	<hr />
	<p>
	<label for="<?php echo $this->get_field_id( 'title_button' ); ?>"><?php _e('Button Title', THEMES_NAMES); ?></label>
	</p>
	<p>
	<input class="widefat" type="text" id="<?php echo $this->get_field_id( 'title_button' ); ?>" name="<?php echo $this->get_field_name( 'title_button' ); ?>" value="<?php echo esc_attr( $title_button ); ?>" />
	</p> 
	<hr />	
	<p>
	<label for="<?php echo esc_html( $this->get_field_id( 'title_link' ) ); ?>"><?php _e( 'Button Link Url:', THEMES_NAMES ); ?></label>
	</p>
	<p>
	<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'title_link' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'title_link' ) ); ?>" type="text" value="<?php echo $title_link; ?>" />
	</p>
	<p>
	<?php _e('link url for button', THEMES_NAMES); ?> (example: <b><?php echo home_url( '/#your_link_categorie' ) ?></b> )
	</p>
	<p>
	<?php _e('leave blank if you dont want to show button', THEMES_NAMES); ?>
	</p>
	<hr />    
	
	 <p>
            <label for="<?php echo $this->get_field_id('select_categorie'); ?>">
                <?php _e('Select Categories (hold CTRL/CMD to select multiple):'); ?>
            </label>
            <select multiple="multiple" class="widefat" size="8"
                    id="<?php echo $this->get_field_id('select_categorie'); ?>"
                    name="<?php echo $this->get_field_name('select_categorie'); ?>[]"
                    style="height: auto;">
                <?php foreach ($categories as $category): ?>
                    <option value="<?php echo $category->term_id; ?>"
                        <?php selected(in_array($category->term_id, $selected_cats), true); ?>>
                        <?php echo esc_html($category->name) . ' (' . $category->count . ')'; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <small><?php _e('Hold down Ctrl (Windows) or Cmd (Mac) to select multiple categories.'); ?></small>
        </p>
		
    <?php

	}

	public function update( $new_instance, $old_instance ) {
	$instance	= $old_instance;
	$new_instance	= wp_parse_args(
	(array) $new_instance,
	array(
	'title'	=> '',
	'title_link'	=> '', 
	'title_button'	=> '', 
	)
	); 

    $instance[ 'title' ]	= strip_tags( $new_instance['title'] );
 
	$instance[ 'title_link' ]	= $new_instance['title_link'];
	$instance[ 'title_button' ]	= $new_instance['title_button'];  
	 

	// Handle multiple select - $new_instance['select_categorie'] is an array
	if (!empty($new_instance['select_categorie']) && is_array($new_instance['select_categorie'])) {
		$sanitized = array_map('absint', $new_instance['select_categorie']);
		// Remove duplicates and empty values
		$sanitized = array_unique(array_filter($sanitized));
		$instance['select_categorie'] = implode(',', $sanitized);
	} else {
		$instance['select_categorie'] = '';
	}
		
    return $instance;
	}
 

	public function widget( $args, $instance ) {
    extract( $args );
	global $post, $opt_themes;
	$widget_id	= $this->id_base . '-' . $this->number;
	$before_widget	= '';
	$after_widget	= '';
    $title	= apply_filters( 'widget_title', $instance[ 'title' ] ); 
	$more	= ( ! empty( $instance['more'] ) ) ? $instance['more'] : '';
	$link_title	= ( ! empty( $instance['link_title'] ) ) ? $instance['link_title'] : ''; 
	
	
	// Get selected category IDs (stored as comma-separated string)
	$selected_categories = !empty($instance['select_categorie']) 
            ? explode(',', $instance['select_categorie']) 
            : array();

	// Make sure they are integers
	$selected_categories = array_map('intval', $selected_categories);
		
	?> 
	<section class="mb-4"  id="<?php echo $widget_id; ?>">
	<header class="d-flex align-items-center mb-4">
	<h2 class="font-weight-bold mb-0">
	<a class="text-body" href="<?php echo $instance['title_link']; ?>"><?php echo $instance[ 'title' ]; ?></a>
	</h2>
	<?php if($instance['title_link']){ ?>
	<a class="btn btn-primary ml-auto" href="<?php echo $instance['title_link']; ?>"><?php echo $instance['title_button']; ?></a>
	<?php } ?>
	</header>
 
 
	<div class="row"> 
	<?php
        if (!empty($selected_categories)) {
            foreach ($selected_categories as $cat_id) {
                $category = get_term($cat_id, 'category');
                if ($category && !is_wp_error($category)) {
					echo '<div class="col-4 col-md-3 col-lg-2 col-xl-2 mb-3">';
                    echo '<a class="h6 font-weight-semibold text-truncate text-center text-body bg-white border rounded shadow-sm d-block p-2 mb-0" href="' . get_category_link($cat_id) . '">' . esc_html($category->name) . '</a>';
					echo '</div>';
                }
            }
        }
	?>
	</div>
		 
	</section>  
    <?php
	}
}
 