<?php
if (!defined('ABSPATH'))
    die('No direct access allowed');

class WCMLIM_Widget_Multiselect extends WP_Widget
{

    public function __construct()
    {

        parent::__construct(
            __CLASS__,
            __('WCMLIM - Filter Products By Locations (Multiple)', 'wcmlim'),
            array(
                'classname' => __CLASS__,
                'description' => __('Display a multi-select location dropdown to filter products in your store.', 'wcmlim')
            )
        );
    }

    public function widget($args, $instance)
    {
        // Check if we're in the customizer
        $is_customizer = is_customize_preview();
        
        // Only show on shop page or in customizer
        if (!is_shop() && !$is_customizer) {
            return;
        }
        
        $backendMode = get_option("wcmlim_allow_only_backend");
        if ($backendMode == "on" && !$is_customizer) {
            return;
        }
        
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo "<span class='gamma widget-title'>{$instance['title']}</span>";
        } else {
            echo $args['before_title'] . apply_filters('widget_title', 'WCMLIM - Filter Products By Locations (Multiple)') . $args['after_title'];
        }
        
        // Show preview message in customizer
        if ($is_customizer) {
            echo '<p style="padding: 10px; background: #f0f0f1; border-left: 4px solid #2271b1;">';
            echo '<strong>Location Filter Widget (Multiple)</strong><br>';
            echo 'This widget will display a checkbox list of locations with filter buttons on the shop page.';
            echo '</p>';
        } else {
            // Check if taxonomy exists before querying
            if (!taxonomy_exists('locations')) {
                echo '<p>' . __('Location taxonomy not found.', 'wcmlim') . '</p>';
                echo $args['after_widget'];
                return;
            }
            
            $excludeLocations = get_option("wcmlim_exclude_locations_from_frontend");
            
            if (!empty($excludeLocations)) {
                $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'exclude' => $excludeLocations));
            } else {
                $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
            }
            
            // Check if get_terms returned an error
            if (is_wp_error($terms)) {
                echo '<p>' . __('Error loading locations.', 'wcmlim') . '</p>';
                echo $args['after_widget'];
                return;
            }
            
            if (!empty($terms)) {
               
?>
                <form action="" name="wcmlimWidFrom" method="POST" class="wcmlim_multiselect_checkbox_form">
                    <div class="wcmlim_checkbox_list">
                        <?php
                        global $wp;
                        $activeLocation = '';
                        if (function_exists('getLocation')) {
                            $activeLocation = getLocation('wcmlim_widget_chosenlc') ?: "";
                        }
                        $exploded_activeLocation = explode(',', $activeLocation);
                        foreach ($terms as $k => $term) {
                            $is_checked = in_array($term->term_id, $exploded_activeLocation) ? 'checked' : '';
                        ?>
                            <label class="wcmlim_checkbox_item">
                                <input type="checkbox" 
                                       name="wcmlim_locations_wid[]" 
                                       value="<?php echo $term->term_id; ?>" 
                                       <?php echo $is_checked; ?>>
                                <span><?php echo $term->name . ' (' . $term->count . ')'; ?></span>
                            </label>
                        <?php
                        } ?>
                    </div>
                    <div class="wcmlim_location_search_container" style="margin-top:15px;">
                        <a class="button wcmlim_submit_location_form_checkbox">Filter</a>
                        <a class="button wcmlim_reset_location_form_checkbox" style="margin-left:10px;">Reset</a>
                    </div>
                </form>
        <?php
            }
        }
        // Keep this line
        echo $args['after_widget'];
    }

    public function form($instance)
    {
        $defaults = array(
            'title' => __('WooCommerce Products Filter (Multi-Select)', 'wcmlim'),
        );
        $instance = wp_parse_args((array) $instance, $defaults);
        $args = array();
        $args['instance'] = $instance;
        $args['widget'] = $this;
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'wcmlim') ?>:</label>
            <input class="widefat" type="text" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" />
        </p>
<?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = $old_instance;
        $instance['title'] = $new_instance['title'];
        return $instance;
    }
}
