<?php
namespace Jet_Engine_Divi_Views\Components\Jet_Smart_Filters\Modules;

if ( ! defined( 'ABSPATH' ) ) {
    die( 'Direct access forbidden.' );
}

use ET\Builder\Framework\DependencyManagement\Interfaces\DependencyInterface;
use ET\Builder\Packages\ModuleLibrary\ModuleRegistration;
use ET\Builder\Packages\Module\Module;
use ET\Builder\FrontEnd\BlockParser\BlockParserStore;
use ET\Builder\FrontEnd\Module\Style;
use ET\Builder\Packages\Module\Options\Text\TextStyle;
use Jet_Engine_Divi_Views\Utils;

class Select_Filter implements DependencyInterface {

    private static function get_default_settings() {

        return [
            'filter_id'         => 0,
            'content_provider'  => 'not-selected',
            'apply_type'        => 'ajax',
            'apply_on'          => 'value',
            'apply_button'      => true,
            'apply_button_text' => __( 'Apply filter', 'jet-smart-filters' ),
            'show_label'        => false,
            'query_id'          => '',
            'apply_indexer'     => false,
            'show_counter'      => false,
            'counter_prefix'    => '(',
            'counter_suffix'    => ')',
            'show_items_rule'   => 'show',
            'change_items_rule' => 'always',
            'show_items_label'  => true,
            'filter_image_size' => 'full',
        ];
    }

    private static function normalize_toggle_value( $value ) {

        if ( is_bool( $value ) ) {
            return $value;
        }

        if ( is_numeric( $value ) ) {
            return (bool) absint( $value );
        }

        if ( ! is_string( $value ) ) {
            return $value;
        }

        $normalized = strtolower( trim( $value ) );

        if ( in_array( $normalized, [ 'on', 'true', 'yes' ], true ) ) {
            return true;
        }

        if ( in_array( $normalized, [ 'off', 'false', 'no', '' ], true ) ) {
            return false;
        }

        return $value;
    }

    private static function get_prepared_attrs( $attrs ) {

        $prepared_attrs = [];

        foreach ( $attrs as $key => $value ) {
            if ( isset( $value['innerContent']['desktop']['value'] ) ) {
                $prepared_attrs[ $key ] = $value['innerContent']['desktop']['value'];
            }
        }

        $prepared_attrs = wp_parse_args( $prepared_attrs, self::get_default_settings() );

        foreach ( [ 'apply_button', 'show_label', 'apply_indexer', 'show_counter', 'show_items_label' ] as $toggle_key ) {
            if ( array_key_exists( $toggle_key, $prepared_attrs ) ) {
                $prepared_attrs[ $toggle_key ] = self::normalize_toggle_value( $prepared_attrs[ $toggle_key ] );
            }
        }

        return $prepared_attrs;
    }

    private static function map_responsive_value( $attr, $map ) {

        if ( empty( $attr ) ) {
            return null;
        }

        $breakpoints = [ 'desktop', 'tablet', 'phone' ];
        $has_bp      = false;

        foreach ( $breakpoints as $bp ) {
            if ( isset( $attr[ $bp ] ) ) {
                $has_bp = true;
                break;
            }
        }

        if ( $has_bp ) {
            $out = $attr;

            foreach ( $breakpoints as $bp ) {
                if ( ! isset( $attr[ $bp ] ) ) {
                    continue;
                }

                $val = $attr[ $bp ]['value'] ?? $attr[ $bp ]['default'] ?? null;

                if ( null === $val ) {
                    continue;
                }

                $mapped               = $map( $val );
                $out[ $bp ]['value']  = $mapped;
                $out[ $bp ]['default'] = $mapped;
            }

            return $out;
        }

        $val = $attr['value'] ?? $attr['default'] ?? null;

        if ( null === $val ) {
            return $attr;
        }

        $mapped          = $map( $val );
        $attr['value']   = $mapped;
        $attr['default'] = $mapped;

        return $attr;
    }

    public static function module_styles( $args ) {

        $elements                    = $args['elements'];
        $settings                    = $args['settings'] ?? [];
        $default_printed_style_attrs = $args['defaultPrintedStyleAttrs'] ?? [];
        $attrs                       = $args['attrs'] ?? [];
        $order_class                 = $args['orderClass'] ?? '';

        $select_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['selectTypography'] ?? null );
        $select_typography_styles = Utils\build_typography_styles(
            "{$args['orderClass']} .jet-select__control",
            $select_typography
        );

        $select_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['selectSpacing'] ?? null );
        $select_spacing_styles = Utils\build_spacing_styles(
            "{$args['orderClass']} .jet-select__control",
            $select_spacing
        );

        $select_border = Utils\extract_border_attrs( $attrs['module']['decoration']['selectBorder'] ?? null );
        $select_border_styles = Utils\build_border_styles(
            "{$args['orderClass']} .jet-select__control",
            $select_border
        );

        $label_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['labelTypography'] ?? null );
        $label_typography_styles = Utils\build_typography_styles(
            "{$args['orderClass']} .jet-filter-label",
            $label_typography
        );

        $label_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['labelSpacing'] ?? null );
        $label_spacing_styles = Utils\build_spacing_styles(
            "{$args['orderClass']} .jet-filter-label",
            $label_spacing
        );

        
        $button_typography = Utils\extract_typography_attrs( $attrs['module']['decoration']['buttonTypography'] ?? null );
        $button_typography_styles = Utils\build_typography_styles(
            "{$args['orderClass']} .apply-filters__button",
            $button_typography
        );

        $button_spacing = Utils\extract_spasing_attrs( $attrs['module']['decoration']['buttonSpacing'] ?? null );
        $button_spacing_styles = Utils\build_spacing_styles(
            "{$args['orderClass']} .apply-filters__button",
            $button_spacing
        );

        $button_border = Utils\extract_border_attrs( $attrs['module']['decoration']['buttonBorder'] ?? null );
        $button_border_styles = Utils\build_border_styles(
            "{$args['orderClass']} .apply-filters__button",
            $button_border
        );

        $hierarchical_position = self::map_responsive_value(
            $attrs['module']['decoration']['hierarchicalPosition'] ?? null,
            static function( $value ) {
                return in_array( $value, [ 'line', 'flex' ], true ) ? 'flex' : 'block';
            }
        );

        Style::add(
            [
                'id'            => $args['id'],
                'name'          => $args['name'],
                'orderIndex'    => $args['orderIndex'],
                'storeInstance' => $args['storeInstance'],
                'styles'        => [
                    $elements->style(
                        [
                            'attrName'   => 'module',
                            'styleProps' => [
                                'defaultPrintedStyleAttrs' => $default_printed_style_attrs['module']['decoration'] ?? [],
                                'disabledOn'               => [
                                    'disabledModuleVisibility' => $settings['disabledModuleVisibility'] ?? null,
                                ],
                                'advancedStyles'           => array_merge(
                                    $select_typography_styles,
                                    $select_spacing_styles,
                                    $select_border_styles,
                                    $label_typography_styles,
                                    $label_spacing_styles,
                                                            $button_typography_styles,
                                    $button_spacing_styles,
                                    $button_border_styles,
                                    [
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-select.jet-filter .jet-select, {$args['orderClass']} .jet-smart-filters-hierarchy.jet-filter .jet-select__control",
                                                'attr'     => $attrs['module']['decoration']['selectWidth'] ?? [],
                                                'property' => 'max-width',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-select.jet-filter .jet-select, {$args['orderClass']} .jet-smart-filters-hierarchy.jet-filter .jet-select__control",
                                                'attr'     => $attrs['module']['decoration']['selectWidth'] ?? [],
                                                'property' => 'flex-basis',
                                            ],
                                        ],

                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-hierarchy.jet-filter .jet-filters-group",
                                                'attr'     => $hierarchical_position,
                                                'property' => 'display',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-hierarchy.jet-filter .jet-filters-group .jet-select + .jet-select",
                                                'attr'     => $attrs['module']['decoration']['hierarchicalVerticalOffset'] ?? [],
                                                'property' => 'margin-top',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-hierarchy.jet-filter .jet-select",
                                                'attr'     => $attrs['module']['decoration']['hierarchicalItemWidth'] ?? [],
                                                'property' => 'width',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-smart-filters-hierarchy.jet-filter .jet-filters-group",
                                                'attr'     => $attrs['module']['decoration']['hierarchicalHorizontalOffset'] ?? [],
                                                'property' => 'gap',
                                            ],
                                        ],

                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-select__control",
                                                'attr'     => $attrs['module']['decoration']['selectColor'] ?? [],
                                                'property' => 'color',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-select__control option:disabled",
                                                'attr'     => $attrs['module']['decoration']['selectDisabledColor'] ?? [],
                                                'property' => 'color',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-select__control",
                                                'attr'     => $attrs['module']['decoration']['selectBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ],
                                        ],

                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-filter-label",
                                                'attr'     => $attrs['module']['decoration']['labelAlignment'] ?? [],
                                                'property' => 'text-align',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .jet-filter-label",
                                                'attr'     => $attrs['module']['decoration']['labelColor'] ?? [],
                                                'property' => 'color',
                                            ],
                                        ],

                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button",
                                                'attr'     => $attrs['module']['decoration']['buttonTextColor'] ?? [],
                                                'property' => 'color',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button",
                                                'attr'     => $attrs['module']['decoration']['buttonBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button:hover",
                                                'attr'     => $attrs['module']['decoration']['buttonHoverTextColor'] ?? [],
                                                'property' => 'color',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button:hover",
                                                'attr'     => $attrs['module']['decoration']['buttonHoverBgColor'] ?? [],
                                                'property' => 'background-color',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button:hover",
                                                'attr'     => $attrs['module']['decoration']['buttonHoverBorderColor'] ?? [],
                                                'property' => 'border-color',
                                            ],
                                        ],
                                        [
                                            'componentName' => 'divi/common',
                                            'props'         => [
                                                'selector' => "{$args['orderClass']} .apply-filters__button",
                                                'attr'     => $attrs['module']['decoration']['buttonAlignment'] ?? [],
                                                'property' => 'align-self',
                                            ],
                                        ],
                                    ]
                                ),
                            ],
                        ]
                    ),
                    TextStyle::style(
                        [
                            'selector' => $order_class . ' .jet-select',
                            'attr'     => $attrs['module']['advanced']['text'] ?? [],
                        ]
                    ),
                ],
            ]
        );
    }

    public static function module_script_data( $args ) {}
    public static function module_classnames( $args ) {}

    public static function render_callback( $attrs, $content, $block, $elements ) {

        $prepared_attrs = self::get_prepared_attrs( $attrs );

        $parent       = BlockParserStore::get_parent( $block->parsed_block['id'], $block->parsed_block['storeInstance'] );
        $parent_attrs = $parent->attrs ?? [];

        $filters_block_type = jet_smart_filters()->blocks->get_block_type( 'select' );
        $content            = $filters_block_type->render_callback( $prepared_attrs );

        return Module::render(
            [
                'orderIndex'          => $block->parsed_block['orderIndex'],
                'storeInstance'       => $block->parsed_block['storeInstance'],

                'id'                  => $block->parsed_block['id'],
                'name'                => $block->block_type->name,
                'moduleCategory'      => $block->block_type->category,
                'attrs'               => $attrs,
                'elements'            => $elements,
                'classnamesFunction'  => [ Select_Filter::class, 'module_classnames' ],
                'stylesComponent'     => [ Select_Filter::class, 'module_styles' ],
                'scriptDataComponent' => [ Select_Filter::class, 'module_script_data' ],
                'parentAttrs'         => $parent_attrs,
                'parentId'            => $parent->id ?? '',
                'parentName'          => $parent->blockName ?? '',
                'children'            => [ $content ],
            ]
        );
    }

    public function load() {

        $module_json_folder_path = JET_ENGINE_DIVI_VIEWS_MODULES_JSON_PATH . 'select-filter/';

        add_action(
            'init',
            function() use ( $module_json_folder_path ) {
                ModuleRegistration::register_module(
                    $module_json_folder_path,
                    [
                        'render_callback' => [ Select_Filter::class, 'render_callback' ],
                    ]
                );
            }
        );
    }
}
