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

class WCMLIM_Widget extends WP_Widget
{

    public function __construct()
    {

        parent::__construct(
            __CLASS__,
            __('WCMLIM - Filter Products By Locations (Single)', 'wcmlim'),
            array(
                'classname' => __CLASS__,
                'description' => __('Display a single-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 (Single)') . $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 (Single Select)</strong><br>';
            echo 'This widget will display a location dropdown 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">
                    <select class="wcmlim_locwid_dd" name="wcmlim_locations_wid">
                        <option value="-1"><?php _e(' - Select - ', 'wcmlim'); ?></option>
                        <?php
                        global $wp;
                        $activeLocation = '';
                        if (function_exists('getLocation')) {
                            $activeLocation = getLocation('wcmlim_widget_chosenlc') ?: "";
                        }
                        foreach ($terms as $k => $term) {
                            $term_meta = get_option("taxonomy_$term->term_id");
                            $term_meta = array_map(function ($term) {
                                if (!is_array($term)) {
                                    return $term;
                                }
                            }, $term_meta);
                            $term_meta = array_filter($term_meta);
                            $rl = implode(" ", $term_meta);
                        ?>
                            <option <?php if ($activeLocation == $term->term_id) {
                                echo "selected='selected'";
                            } ?>value="<?php echo $term->term_id; ?>"><?php echo $term->name . '(' . $term->count . ')'; ?></option>
                        <?php
                        } ?>
                    </select>
                </form>
        <?php
            }
        }
        // Keep this line
        echo $args['after_widget'];
    }

    public function form($instance)
    {
        $defaults = array(
            'title' => __('WooCommerce Products Filter', '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;
    }
}
