<?php
/**
 * WCMLIM Address Widget
 *
 * @link       http://www.techspawn.com
 * @since      1.0.0
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/public
 */

/**
 * Address Management Widget
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/public
 * @author     techspawn1 <contact@techspawn.com>
 */
class WCMLIM_Address_Widget extends WP_Widget {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct(
            'wcmlim_address_widget',
            __('WCMLIM Address Selector', 'wcmlim'),
            array(
                'description' => __('Display address selector for users to manage and select their delivery addresses', 'wcmlim'),
                'classname' => 'wcmlim-address-widget',
            )
        );
    }

    /**
     * Front-end display of widget
     */
    public function widget($args, $instance) {
        // Check if feature is enabled
        $is_enabled = get_option('wcmlim_enable_user_address_management');
        
        if ($is_enabled !== 'on' || !is_user_logged_in()) {
            return;
        }

        echo $args['before_widget'];

        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }

        // Render the address selector
        echo do_shortcode('[wcmlim_address_selector]');

        echo $args['after_widget'];
    }

    /**
     * Back-end widget form
     */
    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : '';
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
                <?php _e('Title (optional):', 'wcmlim'); ?>
            </label>
            <input class="widefat" 
                   id="<?php echo esc_attr($this->get_field_id('title')); ?>" 
                   name="<?php echo esc_attr($this->get_field_name('title')); ?>" 
                   type="text" 
                   value="<?php echo esc_attr($title); ?>">
        </p>
        <p class="description">
            <?php _e('This widget displays the address selector for logged-in users. It allows them to manage and select delivery addresses.', 'wcmlim'); ?>
        </p>
        <p class="description">
            <strong><?php _e('Note:', 'wcmlim'); ?></strong> 
            <?php _e('Make sure "Enable Users To Manage Address" is turned ON in the plugin settings.', 'wcmlim'); ?>
        </p>
        <?php
    }

    /**
     * Sanitize widget form values as they are saved
     */
    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }
}
