<?php
// If this file is called directly, abort.
if (! defined('ABSPATH')) {
    exit;
}

class GGM_Commerce_Elementor_Widgets
{

    private static $instance = null;

    public static function get_instance()
    {
        if (! self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        // Register scripts VERY early so Elementor can find them
        add_action('wp_enqueue_scripts', [$this, 'register_scripts'], 5);

        add_action('elementor/elements/categories_registered', [$this, 'add_widget_category']);
        add_action('elementor/widgets/widgets_registered', [$this, 'register_widgets']);
        add_action('elementor/editor/after_enqueue_styles', [$this, 'ggm_commerce_reorder_widget_category']);
    }

    /**
     * This function now correctly registers our frontend handler script.
     */
    public function register_scripts()
    {

        $plugin_root_file = dirname(__DIR__) . '/goose-commerce.php';
        $plugin_root_url  = plugin_dir_url($plugin_root_file);


        // Register styles
        wp_register_style(
            'ggmc-widgets',
            $plugin_root_url . 'assets/css/widgets.css',
            [],
            '1.0.0'
        );
        
        // Enqueue widget styles on frontend
        wp_enqueue_style('ggmc-widgets');

        wp_register_script(
            'ggmc-gallery-handler', // The new, unique handle for our script.
            $plugin_root_url . 'assets/js/gallery-widget.js',
            ['elementor-frontend', 'jquery'], // It depends on Elementor's main script.
            '1.4.0',
            true
        );

        wp_register_script(
            'ggmc-product-carousel',
            $plugin_root_url . 'assets/js/product-carousel.js',
            ['elementor-frontend', 'jquery'],
            '1.0.0',
            true
        );

        wp_register_script(
            'ggmc-image-grid',
            $plugin_root_url . 'assets/js/image-grid-lightbox.js',
            [],
            '1.0.0',
            true
        );

        wp_register_script(
            'ggmc-cart',
            $plugin_root_url . 'assets/js/cart.js',
            ['jquery'],
            '1.0.0',
            true
        );

        wp_register_script(
            'ggmc-product-filter',
            $plugin_root_url . 'assets/js/product-filter.js',
            ['jquery'],
            '1.0.0',
            true
        );

        // Register the widget-specific filter script
        $filter_script_url = $plugin_root_url . 'assets/js/widget-product-filter.js';

        wp_register_script(
            'ggmc-widget-product-filter',
            $filter_script_url,
            ['jquery'],
            '1.0.6',
            true
        );


        // Register unified product display handler for Grid, List, and Table
        wp_register_script(
            'ggmc-product-display-handler',
            $plugin_root_url . 'assets/js/product-display-handler.js',
            ['jquery'],
            '1.0.6',
            true
        );

        // Keep product-grid for backwards compatibility (alias to display handler)
        wp_register_script(
            'ggmc-product-grid',
            $plugin_root_url . 'assets/js/product-display-handler.js',
            ['jquery'],
            '1.0.6',
            true
        );

        // Register product list and table scripts (alias to display handler)
        wp_register_script(
            'ggmc-product-list',
            $plugin_root_url . 'assets/js/product-display-handler.js',
            ['jquery'],
            '1.0.6',
            true
        );

        wp_register_script(
            'ggmc-product-table',
            $plugin_root_url . 'assets/js/product-display-handler.js',
            ['jquery'],
            '1.0.6',
            true
        );

        // Register wishlist script
        wp_register_script(
            'ggmc-wishlist',
            $plugin_root_url . 'assets/js/wishlist.js',
            ['jquery'],
            '1.0.0',
            true
        );

        // Register Quick View script
        wp_register_script(
            'ggmc-quick-view',
            $plugin_root_url . 'assets/js/quick-view.js',
            ['jquery'],
            '1.0.0',
            true
        );

        // Register Product Comparison script
        wp_register_script(
            'ggmc-product-comparison',
            $plugin_root_url . 'assets/js/product-comparison.js',
            ['jquery'],
            '1.0.0',
            true
        );

        // Register Variations script and styles
        wp_register_script(
            'ggmc-variations',
            $plugin_root_url . 'assets/js/variations.js',
            ['jquery'],
            '2.0.1',
            true
        );

        wp_register_style(
            'ggmc-variations',
            $plugin_root_url . 'assets/css/variations.css',
            [],
            '2.0.0'
        );

        // Register Downloads styles
        wp_register_style(
            'ggmc-downloads',
            $plugin_root_url . 'assets/css/downloads.css',
            [],
            '1.0.0'
        );

        // ENQUEUE scripts on frontend so localization works
        if (!is_admin()) {
            wp_enqueue_script('ggmc-cart');
            wp_enqueue_script('ggmc-widget-product-filter');
            wp_enqueue_script('ggmc-product-display-handler');

            // Enqueue wishlist script only if feature is activated
            if ( class_exists( 'GGM_Commerce_License' ) && \GGM_Commerce_License::instance()->is_widget_activated( 'wishlist' ) ) {
                wp_enqueue_script('ggmc-wishlist');
            }

            // Enqueue Quick View script only if feature is activated
            if ( class_exists( 'GGM_Commerce_Quick_View' ) && \GGM_Commerce_Quick_View::is_activated() ) {
                wp_enqueue_script('ggmc-quick-view');
                wp_enqueue_style('dashicons'); // For close button icon

                // Localize Quick View script
                wp_localize_script('ggmc-quick-view', 'ggmCommerceQuickView', [
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('ggm_commerce_quick_view_nonce'),
                ]);
            }

            // Enqueue Variations script and styles only if feature is activated
            if ( class_exists( 'GGM_Commerce_Variations' ) && \GGM_Commerce_Variations::is_activated() ) {
                wp_enqueue_script('ggmc-variations');
                wp_enqueue_style('ggmc-variations');

                // Localize Variations script
                wp_localize_script('ggmc-variations', 'ggmCommerceVariations', [
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('ggmc_nonce'),
                    'i18n' => [
                        // translators: %s: attribute name (e.g., Color, Size).
                        'choose' => __('Choose %s', 'ggm-commerce'),
                        'out_of_stock' => __('Out of stock', 'ggm-commerce'),
                        'unavailable' => __('Unavailable', 'ggm-commerce'),
                        'select_options' => __('Please select all options', 'ggm-commerce'),
                    ],
                ]);
            }

            // Enqueue Downloads styles only if feature is activated
            if ( class_exists( 'GGM_Commerce_Downloads' ) && \GGM_Commerce_Downloads::is_activated() ) {
                wp_enqueue_style('ggmc-downloads');
            }

            // Enqueue Product Comparison script only if feature is activated
            if ( class_exists( 'GGM_Commerce_Product_Comparison' ) && \GGM_Commerce_Product_Comparison::is_activated() ) {
                wp_enqueue_script('ggmc-product-comparison');

                // Get comparison page URL
                $compare_page_id = get_option('ggm_commerce_comparison_page_id');
                $compare_page_url = $compare_page_id ? get_permalink($compare_page_id) : home_url('/product-comparison/');

                // Check if floating bar is enabled (default: yes)
                // Handle various stored formats: '1', '0', 1, 0, true, false
                // IMPORTANT: wp_localize_script converts true->'' and false->'', so we must pass '1' or '0' strings
                $widget_controls = get_option('ggm_commerce_widget_controls', array());
                $show_floating_bar_raw = isset($widget_controls['show_floating_bar']) ? $widget_controls['show_floating_bar'] : '1';
                $show_floating_bar = in_array($show_floating_bar_raw, array('1', 1, true, 'true'), true) ? '1' : '0';

                // Get notification settings for product comparison
                $notifications_config = array(
                    'enabled'  => isset($widget_controls['notifications_enabled']) ? $widget_controls['notifications_enabled'] : '1',
                    'position' => isset($widget_controls['notifications_position']) ? $widget_controls['notifications_position'] : 'top-right',
                    'duration' => isset($widget_controls['notifications_duration']) ? intval($widget_controls['notifications_duration']) : 3000,
                );

                // Localize Product Comparison script
                wp_localize_script('ggmc-product-comparison', 'ggmCommerceCompare', [
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('ggm_commerce_compare_nonce'),
                    'max_products' => GGM_Commerce_Product_Comparison::get_max_products(),
                    'compare_page_url' => $compare_page_url,
                    'show_floating_bar' => $show_floating_bar,
                    'notifications' => $notifications_config,
                    'i18n' => [
                        'of' => __('of', 'ggm-commerce'),
                        'products_selected' => __('products selected', 'ggm-commerce'),
                        'compare_now' => __('Compare Now', 'ggm-commerce'),
                        'clear_all' => __('Clear All', 'ggm-commerce'),
                        'add_to_compare' => !empty($widget_controls['msg_added_to_compare'])
                            ? $widget_controls['msg_added_to_compare']
                            : __('Add to comparison', 'ggm-commerce'),
                        'remove_from_compare' => !empty($widget_controls['msg_removed_from_compare'])
                            ? $widget_controls['msg_removed_from_compare']
                            : __('Remove from comparison', 'ggm-commerce'),
                        'max_reached' => !empty($widget_controls['msg_max_compare'])
                            ? $widget_controls['msg_max_compare']
                            : __('Maximum of {max} products can be compared', 'ggm-commerce'),
                        'need_at_least_two' => __('Select at least 2 products to compare', 'ggm-commerce'),
                        'error_occurred' => !empty($widget_controls['msg_error'])
                            ? $widget_controls['msg_error']
                            : __('An error occurred. Please try again.', 'ggm-commerce'),
                    ],
                ]);
            }
        }

        // Localize cart script with page URLs from options
        $cart_page_id = get_option('ggm_commerce_cart_page_id');
        $checkout_page_id = get_option('ggm_commerce_checkout_page_id');

        $cart_url = $cart_page_id ? get_permalink($cart_page_id) : home_url('/cart/');
        $checkout_url = $checkout_page_id ? get_permalink($checkout_page_id) : home_url('/checkout/');

        wp_localize_script('ggmc-cart', 'ggm_commerce_ajax', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ggm_commerce_cart_nonce'),
            'cart_url' => $cart_url,
            'checkout_url' => $checkout_url,
            'i18n' => [
                'confirm_remove' => __('Are you sure you want to remove this item from your cart?', 'ggm-commerce'),
                'error_occurred' => __('An error occurred. Please try again.', 'ggm-commerce'),
                'added_to_cart' => __('Added to cart', 'ggm-commerce'),
                'removed_from_cart' => __('Removed from cart', 'ggm-commerce'),
                'cart_updated' => __('Cart updated', 'ggm-commerce'),
            ],
        ]);

        // Localize widget filter script
        wp_localize_script('ggmc-widget-product-filter', 'ggm_commerce_ajax', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ggm_commerce_nonce'),
            'i18n' => [
                'config_error' => __('Configuration error. Please refresh the page.', 'ggm-commerce'),
                'filter_error' => __('Error filtering products. Please try again.', 'ggm-commerce'),
            ],
        ]);

    }

    public function add_widget_category($elements_manager)
    {
        $elements_manager->add_category(
            'ggmc-widgets',
            ['title' => 'Goose Commerce', 'icon' => 'fa fa-plug']
        );
    }

    public function register_widgets($widgets_manager)
    {
        // Widget registration is handled by class-elementor.php
        // This method is kept for compatibility but does nothing
    }

    public function ggm_commerce_reorder_widget_category()
    {
        // Check if widget prioritization is enabled (defaults to enabled)
        $widget_controls = get_option('ggm_commerce_widget_controls', array());
        $widgets_prioritized = isset($widget_controls['widgets_prioritized']) ? $widget_controls['widgets_prioritized'] : '1';

        // Only output the CSS if prioritization is enabled
        if ($widgets_prioritized !== '1') {
            return;
        }
?>
        <style>
            #elementor-panel-categories {
                display: flex;
                flex-direction: column;
            }

            #elementor-panel-category-ggmc-widgets {
                order: -1;
            }
        </style>
<?php
    }
}
GGM_Commerce_Elementor_Widgets::get_instance();
