<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

/*
 * ── Override shoptimizer_product_search() BEFORE the theme defines it ────────
 *
 * Shoptimizer wraps the function in `if ( ! function_exists() )`. Because
 * plugins load before themes, defining it here takes precedence. We add the
 * `glance-search` case while preserving every original case verbatim, so the
 * override is transparent when Glance is not selected.
 *
 * This is far more robust than remove_action / add_action on `wp`, because it
 * works everywhere the theme calls the function - desktop header, mobile nav,
 * modal, checkout minimal mode, Elementor Pro fallback, etc.
 */
if ( ! function_exists( 'shoptimizer_product_search' ) ) {
    function shoptimizer_product_search(): void {
        /*
         * This override replaces the theme's own definition, so a missing
         * shoptimizer_get_option() fatals the site through us. maybe_override()
         * checks it too, but each body has to stand on its own.
         */
        if ( ! function_exists( 'shoptimizer_get_option' ) ) {
            return;
        }

        $search_display      = shoptimizer_get_option( 'shoptimizer_layout_search_display' );
        $search_display_type = shoptimizer_get_option( 'shoptimizer_layout_search_display_type' );

        if ( ! function_exists( 'shoptimizer_is_woocommerce_activated' ) || ! shoptimizer_is_woocommerce_activated() ) {
            return;
        }

        $wrapper_class = 'outline' === $search_display_type ? 'site-search type-outline' : 'site-search';

        switch ( $search_display ) {
            case 'glance-search':
                printf(
                    '<div class="%s" role="search" aria-label="%s">',
                    esc_attr( $wrapper_class ),
                    esc_attr__( 'Product Search', 'glance-live-search' )
                );
                echo do_shortcode( '[glance_search]' );
                echo '</div>';
                break;

            case 'enable':
                printf(
                    '<div class="%s" role="search" aria-label="%s">',
                    esc_attr( $wrapper_class ),
                    esc_attr__( 'Product Search', 'glance-live-search' )
                );
                the_widget( 'WC_Widget_Product_Search', 'title=' );
                echo '</div>';
                break;

            case 'ajax-search-wc':
                printf(
                    '<div class="%s" role="search" aria-label="%s">',
                    esc_attr( $wrapper_class ),
                    esc_attr__( 'Product Search', 'glance-live-search' )
                );
                echo do_shortcode( '[fibosearch]' );
                echo '</div>';
                break;

            case 'advanced-woo-search':
                printf(
                    '<div class="%s" role="search" aria-label="%s">',
                    esc_attr( $wrapper_class ),
                    esc_attr__( 'Product Search', 'glance-live-search' )
                );
                echo do_shortcode( '[aws_search_form]' );
                echo '</div>';
                break;

            case 'smart-search-pro':
                printf(
                    '<div class="%s" role="search" aria-label="%s">',
                    esc_attr( $wrapper_class ),
                    esc_attr__( 'Product Search', 'glance-live-search' )
                );
                echo do_shortcode( '[smart_search id="1"]' );
                echo '</div>';
                break;

            case 'yith-search':
                printf(
                    '<div class="%s" role="search" aria-label="%s">',
                    esc_attr( $wrapper_class ),
                    esc_attr__( 'Product Search', 'glance-live-search' )
                );
                echo do_shortcode( '[yith_woocommerce_ajax_search]' );
                echo '</div>';
                break;

            case 'regular':
                printf(
                    '<div class="%s" role="search" aria-label="%s">',
                    esc_attr( $wrapper_class ),
                    esc_attr__( 'Product Search', 'glance-live-search' )
                );
                get_search_form();
                echo '</div>';
                break;
        }
    }
}

/*
 * ── Override shoptimizer_search_modal() BEFORE the theme defines it ──────────
 *
 * Used only for the "header-4 / One row header" layout. The theme wraps the
 * function in `if ( ! function_exists() )` so our definition wins. We add the
 * `glance-search` case and preserve every original case verbatim.
 */
if ( ! function_exists( 'shoptimizer_search_modal' ) ) {
    function shoptimizer_search_modal(): void {
        /*
         * This override replaces the theme's own definition, so a missing
         * shoptimizer_get_option() fatals the site through us. maybe_override()
         * checks it too, but each body has to stand on its own.
         */
        if ( ! function_exists( 'shoptimizer_get_option' ) ) {
            return;
        }

        $search_display      = shoptimizer_get_option( 'shoptimizer_layout_search_display' );
        $search_display_type = shoptimizer_get_option( 'shoptimizer_layout_search_display_type' );
        $search_title        = shoptimizer_get_option( 'shoptimizer_layout_search_title' );

        if ( 'disable' === $search_display ) {
            return;
        }

        $wrapper_class = 'outline' === $search_display_type ? 'site-search type-outline' : 'site-search';

        echo '<button class="search-trigger" data-trigger="searchToggle"><span>';
        echo '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">';
        echo '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />';
        echo '</svg></span></button>';
        ?>
        <dialog class="shoptimizer-modal" data-shoptimizermodal-id="searchToggle" aria-label="<?php esc_attr_e( 'Search', 'glance-live-search' ); ?>">
            <div class="shoptimizer-modal--container">
                <form method="dialog">
                    <div role="heading"><?php echo wp_kses_post( $search_title ); ?></div>
                    <button aria-label="<?php esc_attr_e( 'Close modal', 'glance-live-search' ); ?>" class="shoptimizer-modal--button_close" data-dismiss="modal">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </form>
                <div class="shoptimizer-modal--content">
                    <?php if ( function_exists( 'shoptimizer_is_woocommerce_activated' ) && shoptimizer_is_woocommerce_activated() ) : ?>
                        <?php if ( 'glance-search' === $search_display ) : ?>
                            <div class="<?php echo esc_attr( $wrapper_class ); ?>" role="search">
                                <?php echo do_shortcode( '[glance_search]' ); ?>
                            </div>
                        <?php elseif ( 'enable' === $search_display ) : ?>
                            <div class="<?php echo esc_attr( $wrapper_class ); ?>">
                                <?php the_widget( 'WC_Widget_Product_Search', 'title=' ); ?>
                            </div>
                        <?php elseif ( 'ajax-search-wc' === $search_display ) : ?>
                            <div class="<?php echo esc_attr( $wrapper_class ); ?>">
                                <?php echo do_shortcode( '[fibosearch]' ); ?>
                            </div>
                        <?php elseif ( 'advanced-woo-search' === $search_display ) : ?>
                            <div class="<?php echo esc_attr( $wrapper_class ); ?>">
                                <?php echo do_shortcode( '[aws_search_form]' ); ?>
                            </div>
                        <?php elseif ( 'smart-search-pro' === $search_display ) : ?>
                            <div class="<?php echo esc_attr( $wrapper_class ); ?>">
                                <?php echo do_shortcode( '[smart_search id="1"]' ); ?>
                            </div>
                        <?php elseif ( 'yith-search' === $search_display ) : ?>
                            <div class="<?php echo esc_attr( $wrapper_class ); ?>">
                                <?php echo do_shortcode( '[yith_woocommerce_ajax_search]' ); ?>
                            </div>
                        <?php elseif ( 'regular' === $search_display ) : ?>
                            <div class="<?php echo esc_attr( $wrapper_class ); ?>">
                                <?php get_search_form(); ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </dialog>
        <?php
    }
}

/**
 * Glance Live Search - Shoptimizer theme integration.
 *
 * Shoptimizer renders search in three distinct locations:
 *   1. Desktop header:  shoptimizer_product_search() on `shoptimizer_header` @ 25
 *   2. Mobile nav:      shoptimizer_product_search() on `shoptimizer_navigation` @ 45
 *   3. Header-4 modal:  shoptimizer_search_modal()   on `shoptimizer_navigation` @ 50
 *
 * Both function overrides above handle all three cases natively. The class
 * below handles the Customizer dropdown injection and the `get_search_form`
 * filter to catch any remaining native search form calls (widget areas,
 * content-none.php, etc.) when Glance is selected.
 *
 * Activation: Customizer → Header → Navigation Header → Display the search?
 *             → select "Glance Live Search".
 */
class GLSE_Compat_Shoptimizer extends GLSE_Compat_Base {

    public function register_customizer( WP_Customize_Manager $wp_customize ): void {
        $control = $wp_customize->get_control( 'shoptimizer_layout_search_display' );
        if ( ! $control ) {
            return;
        }
        // Insert "Glance Live Search" right after FiboSearch in the choices list.
        $new_choices = [];
        foreach ( $control->choices as $key => $label ) {
            $new_choices[ $key ] = $label;
            if ( 'ajax-search-wc' === $key ) {
                $new_choices['glance-search'] = __( 'Glance Live Search', 'glance-live-search' );
            }
        }
        // Fallback: if ajax-search-wc wasn't found, append at end.
        if ( ! isset( $new_choices['glance-search'] ) ) {
            $new_choices['glance-search'] = __( 'Glance Live Search', 'glance-live-search' );
        }
        $control->choices = $new_choices;
    }

    public function maybe_override(): void {
        if ( ! function_exists( 'shoptimizer_get_option' ) ) {
            return;
        }
        if ( 'glance-search' !== shoptimizer_get_option( 'shoptimizer_layout_search_display' ) ) {
            return;
        }
        $this->force_load_assets();

        /*
         * Filter get_search_form() to replace any remaining native WP search
         * form calls (widget areas, content-none.php, theme templates, etc.)
         * with our Glance search - same approach as FiboSearch.
         */
        add_filter( 'get_search_form', function (): string {
            return do_shortcode( '[glance_search]' );
        }, 10 );

        /*
         * ── Neutralise CommerceKit AJAX Search when Glance is active ────────
         *
         * CommerceKit (bundled with Shoptimizer) registers its own AJAX search
         * module that:
         *   1. Filters get_search_form / get_product_search_form at priority 99
         *      to overwrite the placeholder text of every search form.
         *   2. Enqueues its own ajax-search.css / ajax-search.js on all pages,
         *      attaching AJAX listeners to input[type="search"] inside
         *      .widget_search / .widget_product_search wrappers.
         *
         * When Glance is selected as the search provider, CommerceKit's filters
         * and assets are redundant and can cause visual conflicts (double
         * search bars, mismatched placeholders, broken live-search).
         *
         * We remove CommerceKit's filters and dequeue its assets to prevent
         * any interference.
         */
        add_action( 'wp', function () {
            remove_filter( 'get_search_form',         'commercekit_ajax_search_form', 99 );
            remove_filter( 'get_product_search_form',  'commercekit_ajax_search_form', 99 );
        }, 20 );

        add_action( 'wp_enqueue_scripts', function () {
            wp_dequeue_style( 'commercekit-ajax-search-css' );
            wp_dequeue_script( 'commercekit-ajax-search' );
        }, 20 );
    }

}
