<?php
/**
 * Product Filter Widget
 */

if (!defined('ABSPATH')) {
    exit;
}

add_action('widgets_init', 'askagento_register_widget');

/**
 * Register widget
 */
function askagento_register_widget() {
    register_widget('Askagento_Widget');
}

/**
 * Widget class
 */
class Askagento_Widget extends WP_Widget {
    
    public function __construct() {
        parent::__construct(
            'askagento_filter_widget',
            __('Product Filter', 'askagento'),
            [
                'description' => __('Display product filter in sidebar', 'askagento'),
                'classname'   => 'widget_askagento_filter',
            ]
        );
    }
    
    /**
     * Frontend output
     */
    public function widget($args, $instance) {
        $filter_id = !empty($instance['filter_id']) ? (int) $instance['filter_id'] : 0;
        
        if (!$filter_id) {
            return;
        }
        
        // Check if should show on current page
        if (!empty($instance['show_on'])) {
            if (!askagento_widget_should_show($instance['show_on'])) {
                return;
            }
        }
        
        $title = !empty($instance['title']) ? $instance['title'] : '';
        $title = apply_filters('widget_title', $title, $instance, $this->id_base);
        
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- widget $args are provided by WordPress core/theme.
        echo $args['before_widget'];

        if ($title) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- widget $args and apply_filters('widget_title') are WordPress-trusted HTML.
            echo $args['before_title'] . $title . $args['after_title'];
        }

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- askagento_render_filter() builds escaped HTML internally.
        echo askagento_render_filter($filter_id);

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- widget $args are provided by WordPress core/theme.
        echo $args['after_widget'];
    }
    
    /**
     * Backend form
     */
    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : '';
        $filter_id = !empty($instance['filter_id']) ? (int) $instance['filter_id'] : 0;
        $show_on = !empty($instance['show_on']) ? $instance['show_on'] : 'all';
        
        // Get all filters
        $filters = get_posts([
            'post_type'   => ASKAGENTO_POST_TYPE,
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby'     => 'title',
            'order'       => 'ASC',
        ]);
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('Title:', 'askagento'); ?></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>
            <label for="<?php echo esc_attr($this->get_field_id('filter_id')); ?>"><?php esc_html_e('Filter:', 'askagento'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('filter_id')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('filter_id')); ?>">
                <option value=""><?php esc_html_e('- Select Filter -', 'askagento'); ?></option>
                <?php foreach ($filters as $filter): ?>
                    <option value="<?php echo (int) $filter->ID; ?>" <?php selected($filter_id, $filter->ID); ?>>
                        <?php echo esc_html($filter->post_title); ?> (ID: <?php echo (int) $filter->ID; ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </p>
        
        <?php if (empty($filters)): ?>
            <p class="description">
                <?php esc_html_e('No filters found.', 'askagento'); ?>
                <a href="<?php echo esc_url(admin_url('post-new.php?post_type=' . ASKAGENTO_POST_TYPE)); ?>">
                    <?php esc_html_e('Create one', 'askagento'); ?>
                </a>
            </p>
        <?php endif; ?>
        
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('show_on')); ?>"><?php esc_html_e('Show on:', 'askagento'); ?></label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('show_on')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('show_on')); ?>">
                <option value="all" <?php selected($show_on, 'all'); ?>><?php esc_html_e('All pages', 'askagento'); ?></option>
                <option value="shop" <?php selected($show_on, 'shop'); ?>><?php esc_html_e('Shop pages only', 'askagento'); ?></option>
                <option value="archive" <?php selected($show_on, 'archive'); ?>><?php esc_html_e('Archive pages only', 'askagento'); ?></option>
                <option value="product_cat" <?php selected($show_on, 'product_cat'); ?>><?php esc_html_e('Product category pages', 'askagento'); ?></option>
            </select>
        </p>
        <?php
    }
    
    /**
     * Save settings
     */
    public function update($new_instance, $old_instance) {
        $instance = [];
        $instance['title'] = sanitize_text_field($new_instance['title'] ?? '');
        $instance['filter_id'] = (int) ($new_instance['filter_id'] ?? 0);
        $instance['show_on'] = sanitize_text_field($new_instance['show_on'] ?? 'all');
        
        return $instance;
    }
}

/**
 * Check if widget should show on current page
 */
function askagento_widget_should_show($show_on) {
    switch ($show_on) {
        case 'all':
            return true;
            
        case 'shop':
            if (function_exists('is_shop')) {
                return is_shop() || is_product_category() || is_product_tag();
            }
            return is_post_type_archive('product');
            
        case 'archive':
            return is_archive() || is_home();
            
        case 'product_cat':
            if (function_exists('is_product_category')) {
                return is_product_category();
            }
            return is_tax('product_cat');
            
        default:
            return true;
    }
}

/**
 * Also register as Gutenberg block
 */
add_action('init', 'askagento_register_block');

function askagento_register_block() {
    if (!function_exists('register_block_type')) {
        return;
    }
    
    wp_register_style(
        'askagento-block-editor',
        ASKAGENTO_PLUGIN_URL . 'assets/css/admin.css',
        [],
        ASKAGENTO_VERSION
    );
    
    wp_register_script(
        'askagento-block',
        ASKAGENTO_PLUGIN_URL . 'assets/js/block.js',
        ['wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor'],
        ASKAGENTO_VERSION
    );
    
    // Get filters for block
    $filters = get_posts([
        'post_type'   => ASKAGENTO_POST_TYPE,
        'post_status' => 'publish',
        'numberposts' => -1,
    ]);
    
    $filter_options = [['value' => 0, 'label' => __('- Select Filter -', 'askagento')]];
    foreach ($filters as $f) {
        $filter_options[] = ['value' => $f->ID, 'label' => $f->post_title];
    }
    
    wp_localize_script('askagento-block', 'askagentoBlock', [
        'filters' => $filter_options,
    ]);
    
    $block_args = [
        'editor_script'   => 'askagento-block',
        'editor_style'    => 'askagento-block-editor',
        'render_callback' => 'askagento_block_render',
        'attributes'      => [
            'filterId' => [
                'type'    => 'number',
                'default' => 0,
            ],
        ],
    ];

    register_block_type('askagento/filter', $block_args);

    // Legacy block name in saved post content (frontend render only).
    register_block_type('product-filter/filter', [
        'render_callback' => 'askagento_block_render',
        'attributes'      => $block_args['attributes'],
    ]);
}

/**
 * Block render callback
 */
function askagento_block_render($attributes) {
    $filter_id = !empty($attributes['filterId']) ? (int) $attributes['filterId'] : 0;
    
    if (!$filter_id) {
        return '<p>' . esc_html__('Please select a filter', 'askagento') . '</p>';
    }
    
    return askagento_render_filter($filter_id);
}
