<?php
/**
 * Page Builder Class
 * Handles creation of default pages with Elementor layouts
 */

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

class GGM_Commerce_Page_Builder {

    /**
     * Check whether Elementor is active and available.
     *
     * @return bool
     */
    public static function is_elementor_active() {
        return defined( 'ELEMENTOR_VERSION' ) || class_exists( '\Elementor\Plugin' );
    }

    /**
     * Register hooks that detect Elementor being activated or deactivated
     * so existing Goose Commerce pages can be converted to the right format.
     */
    public static function register_builder_switch_hooks() {
        // Fires when ANY plugin is activated.
        add_action( 'activated_plugin', array( __CLASS__, 'on_plugin_activated' ) );
        // Fires when ANY plugin is deactivated.
        add_action( 'deactivated_plugin', array( __CLASS__, 'on_plugin_deactivated' ) );
    }

    /**
     * When a plugin is activated, check if it is Elementor and convert pages.
     *
     * @param string $plugin Plugin basename (e.g. elementor/elementor.php).
     */
    public static function on_plugin_activated( $plugin ) {
        if ( strpos( $plugin, 'elementor' ) === false ) {
            return;
        }
        // Elementor just became active — convert pages FROM blocks TO Elementor.
        self::convert_pages_to_elementor();
    }

    /**
     * When a plugin is deactivated, check if it is Elementor and convert pages.
     *
     * @param string $plugin Plugin basename.
     */
    public static function on_plugin_deactivated( $plugin ) {
        if ( strpos( $plugin, 'elementor' ) === false ) {
            return;
        }
        // Elementor just became inactive — convert pages FROM Elementor TO blocks.
        self::convert_pages_to_blocks();
    }

    /**
     * Convert all Goose Commerce pages from block content to Elementor layouts.
     */
    public static function convert_pages_to_elementor() {
        $pages = self::get_page_definitions();

        foreach ( $pages as $slug => $page_data ) {
            $page_id = get_option( $page_data['option'] );
            if ( ! $page_id || get_post_status( $page_id ) !== 'publish' ) {
                continue;
            }

            // Add Elementor layout data.
            self::add_elementor_layout( $page_id, $page_data['layout'] );

            // Clear post_content so Elementor takes over rendering.
            wp_update_post( array(
                'ID'           => $page_id,
                'post_content' => '',
            ) );

            // Track the active builder for this page.
            update_post_meta( $page_id, '_ggmc_page_builder', 'elementor' );
        }
    }

    /**
     * Convert all Goose Commerce pages from Elementor to block content.
     */
    public static function convert_pages_to_blocks() {
        $pages = self::get_page_definitions();

        foreach ( $pages as $slug => $page_data ) {
            $page_id = get_option( $page_data['option'] );
            if ( ! $page_id || get_post_status( $page_id ) !== 'publish' ) {
                continue;
            }

            // Set block content.
            $block_content = self::get_block_content( $page_data['layout'] );
            wp_update_post( array(
                'ID'           => $page_id,
                'post_content' => $block_content,
            ) );

            // Remove Elementor metadata so the block editor takes over.
            delete_post_meta( $page_id, '_elementor_edit_mode' );
            delete_post_meta( $page_id, '_elementor_data' );
            delete_post_meta( $page_id, '_elementor_css' );

            // Track the active builder for this page.
            update_post_meta( $page_id, '_ggmc_page_builder', 'blocks' );
        }
    }

    /**
     * Get the page definitions array (shared between create and convert).
     *
     * @return array
     */
    public static function get_page_definitions() {
        return array(
            'shop' => array(
                'title' => 'Shop',
                'option' => 'ggm_commerce_shop_page_id',
                'layout' => 'shop'
            ),
            'cart' => array(
                'title' => 'Cart',
                'option' => 'ggm_commerce_cart_page_id',
                'layout' => 'cart'
            ),
            'checkout' => array(
                'title' => 'Checkout',
                'option' => 'ggm_commerce_checkout_page_id',
                'layout' => 'checkout'
            ),
            'my-account' => array(
                'title' => 'My Account',
                'option' => 'ggm_commerce_account_page_id',
                'layout' => 'account'
            ),
            'product-details' => array(
                'title' => 'Product Details',
                'option' => 'ggm_commerce_product_details_page_id',
                'layout' => 'product-details'
            ),
            'product-category' => array(
                'title' => 'Product Category',
                'option' => 'ggm_commerce_category_archive_page_id',
                'layout' => 'category-archive'
            ),
            'product-tag' => array(
                'title' => 'Product Tag',
                'option' => 'ggm_commerce_tag_archive_page_id',
                'layout' => 'tag-archive'
            ),
            'wishlist' => array(
                'title' => 'Wishlist',
                'option' => 'ggm_commerce_wishlist_page_id',
                'layout' => 'wishlist'
            ),
            'product-comparison' => array(
                'title' => 'Product Comparison',
                'option' => 'ggm_commerce_comparison_page_id',
                'layout' => 'product-comparison'
            ),
            'thank-you' => array(
                'title' => 'Order Confirmation',
                'option' => 'ggm_commerce_thank_you_page_id',
                'layout' => 'thank-you'
            )
        );
    }

    /**
     * Create all default pages — auto-detects whether to use
     * Elementor layouts or Gutenberg block content.
     */
    public static function create_default_pages() {
        $pages = self::get_page_definitions();

        foreach ( $pages as $slug => $page_data ) {
            self::create_page( $slug, $page_data );
        }

        // Create Elementor popup templates only if Elementor Pro is active (popups are Pro-only).
        if ( class_exists( '\ElementorPro\Plugin' ) ) {
            self::create_popup_templates();
        }
    }

    /**
     * Create default Elementor popup templates
     */
    private static function create_popup_templates() {
        self::create_address_edit_popup();

        // Only create Quick View popup if the premium feature is activated
        if (class_exists('GGM_Commerce_Quick_View') && GGM_Commerce_Quick_View::is_activated()) {
            self::create_quick_view_popup();
        }
    }

    /**
     * Create Quick View popup template
     * Only called when Quick View premium feature is activated
     */
    public static function create_quick_view_popup() {
        $option_name = 'ggm_commerce_quick_view_popup_id';
        $popup_id = get_option($option_name);
        $current_version = '2.1'; // v2.1: Use Product Details Link widget for View Full Details link

        // Check if popup already exists and is properly configured
        if ($popup_id && get_post_status($popup_id) === 'publish') {
            $popup_version = get_post_meta($popup_id, '_ggmc_popup_version', true);
            if ($popup_version === $current_version) {
                return; // Popup exists and is up to date
            }
            // Delete and recreate if version is outdated
            wp_delete_post($popup_id, true);
        }

        // Create popup template
        $popup_id = wp_insert_post(array(
            'post_title' => 'GGM Commerce - Quick View Popup',
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'elementor_library',
            'comment_status' => 'closed',
            'ping_status' => 'closed',
            'tax_input' => array(
                'elementor_library_type' => array('popup')
            )
        ));

        if ($popup_id && !is_wp_error($popup_id)) {
            // Set taxonomy term for popup
            wp_set_object_terms($popup_id, 'popup', 'elementor_library_type');

            // Set as popup template type
            update_post_meta($popup_id, '_elementor_template_type', 'popup');
            update_post_meta($popup_id, '_elementor_edit_mode', 'builder');
            update_post_meta($popup_id, '_elementor_version', '3.16.0');

            // Set popup settings - wide popup for product display
            $popup_settings = [
                'popup_width' => [
                    'unit' => 'px',
                    'size' => 900
                ],
                'popup_height' => [
                    'unit' => 'auto'
                ],
                'prevent_scroll' => 'yes',
                'avoid_multiple_popups' => 'yes',
                'entrance_animation' => 'fadeIn',
                'exit_animation' => 'fadeOut',
                'entrance_animation_duration' => [
                    'unit' => 'px',
                    'size' => 0.3
                ],
                // Manual trigger only via JavaScript
                'triggers' => [],
                'timing' => [],
                'close_button' => 'yes',
                'close_button_position' => 'inside',
            ];
            update_post_meta($popup_id, '_elementor_page_settings', $popup_settings);

            // Get popup layout data
            $popup_data = self::get_quick_view_popup_data();
            update_post_meta($popup_id, '_elementor_data', wp_slash($popup_data));

            // Mark for CSS regeneration
            update_post_meta($popup_id, '_elementor_css', array());
            update_post_meta($popup_id, '_elementor_controls_usage', array());

            // Save popup version
            update_post_meta($popup_id, '_ggmc_popup_version', $current_version);

            // Save popup ID
            update_option($option_name, $popup_id);
        }
    }

    /**
     * Get Quick View popup layout data
     * Two-column layout: Product Image (left) + Product Info (right)
     * Professional styling applied following STYLING-ARCHITECTURE.md
     */
    private static function get_quick_view_popup_data() {
        // Design system values for professional styling
        $colors = [
            'primary' => '#2563eb',
            'primary_dark' => '#1d4ed8',
            'text_primary' => '#0f172a',
            'text_secondary' => '#475569',
            'text_muted' => '#64748b',
            'border' => '#e2e8f0',
            'success' => '#059669',
        ];

        $font_family = "'Poppins', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif";

        $layout = [
            // Main container - flex row
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'full',
                    'flex_direction' => 'row',
                    'flex_wrap' => 'wrap',
                    'gap' => [
                        'unit' => 'px',
                        'size' => 30
                    ],
                    'padding' => [
                        'unit' => 'px',
                        'top' => '30',
                        'right' => '30',
                        'bottom' => '30',
                        'left' => '30',
                        'isLinked' => true
                    ]
                ],
                'elements' => [
                    // Left column - Product Image (40%)
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'content_width' => 'full',
                            'width' => [
                                'unit' => '%',
                                'size' => 40
                            ],
                            'width_tablet' => [
                                'unit' => '%',
                                'size' => 100
                            ]
                        ],
                        'elements' => [
                            // Product Image (single main image)
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-image',
                                'settings' => [
                                    'image_size' => 'large',
                                    'image_border_radius' => [
                                        'unit' => 'px',
                                        'top' => '8',
                                        'right' => '8',
                                        'bottom' => '8',
                                        'left' => '8',
                                        'isLinked' => true
                                    ]
                                ]
                            ]
                        ]
                    ],
                    // Right column - Product Info (57%)
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'content_width' => 'full',
                            'width' => [
                                'unit' => '%',
                                'size' => 57
                            ],
                            'width_tablet' => [
                                'unit' => '%',
                                'size' => 100
                            ],
                            'flex_direction' => 'column',
                            'gap' => [
                                'unit' => 'px',
                                'size' => 12
                            ]
                        ],
                        'elements' => [
                            // Product Name - Professional styling
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-name',
                                'settings' => [
                                    'html_tag' => 'h2',
                                    'text_color' => $colors['text_primary'],
                                    'typography_typography' => 'custom',
                                    'typography_font_family' => $font_family,
                                    'typography_font_size' => ['size' => '24', 'unit' => 'px'],
                                    'typography_font_weight' => '700',
                                    'typography_line_height' => ['size' => '1.3', 'unit' => 'em'],
                                    'margin' => [
                                        'top' => '0', 'right' => '0', 'bottom' => '8', 'left' => '0',
                                        'unit' => 'px', 'isLinked' => false
                                    ]
                                ]
                            ],
                            // Product Price - Professional styling
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-price',
                                'settings' => [
                                    'price_color' => $colors['text_primary'],
                                    'typography_typography' => 'custom',
                                    'typography_font_family' => $font_family,
                                    'typography_font_size' => ['size' => '22', 'unit' => 'px'],
                                    'typography_font_weight' => '600',
                                    'sale_price_color' => $colors['success'],
                                    'original_price_color' => $colors['text_muted'],
                                    'margin' => [
                                        'top' => '0', 'right' => '0', 'bottom' => '12', 'left' => '0',
                                        'unit' => 'px', 'isLinked' => false
                                    ]
                                ]
                            ],
                            // Product Stock - Professional styling
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-stock',
                                'settings' => [
                                    'prefix' => 'Availability: ',
                                    'in_stock_color' => $colors['success'],
                                    'out_of_stock_color' => '#dc2626',
                                    'typography_typography' => 'custom',
                                    'typography_font_family' => $font_family,
                                    'typography_font_size' => ['size' => '14', 'unit' => 'px'],
                                    'typography_font_weight' => '500',
                                    'margin' => [
                                        'top' => '0', 'right' => '0', 'bottom' => '12', 'left' => '0',
                                        'unit' => 'px', 'isLinked' => false
                                    ]
                                ]
                            ],
                            // Product Short Description - Professional styling
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-description',
                                'settings' => [
                                    'description_type' => 'short',
                                    'show_read_more' => '',
                                    'text_color' => $colors['text_secondary'],
                                    'typography_typography' => 'custom',
                                    'typography_font_family' => $font_family,
                                    'typography_font_size' => ['size' => '14', 'unit' => 'px'],
                                    'typography_font_weight' => '400',
                                    'typography_line_height' => ['size' => '1.6', 'unit' => 'em'],
                                    'margin' => [
                                        'top' => '0', 'right' => '0', 'bottom' => '16', 'left' => '0',
                                        'unit' => 'px', 'isLinked' => false
                                    ]
                                ]
                            ],
                            // Add to Cart - Professional styling
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-add-to-cart',
                                'settings' => [
                                    'show_quantity' => 'yes',
                                    'button_background_background' => 'classic',
                                    'button_background_color' => $colors['primary'],
                                    'button_color' => '#FFFFFF',
                                    'button_typography_typography' => 'custom',
                                    'button_typography_font_family' => $font_family,
                                    'button_typography_font_size' => ['size' => '15', 'unit' => 'px'],
                                    'button_typography_font_weight' => '600',
                                    'button_padding' => [
                                        'top' => '12', 'right' => '24', 'bottom' => '12', 'left' => '24',
                                        'unit' => 'px', 'isLinked' => false
                                    ],
                                    'button_border_border' => 'solid',
                                    'button_border_width' => [
                                        'top' => '2', 'right' => '2', 'bottom' => '2', 'left' => '2',
                                        'unit' => 'px', 'isLinked' => true
                                    ],
                                    'button_border_color' => $colors['primary'],
                                    'button_border_radius' => [
                                        'top' => '6', 'right' => '6', 'bottom' => '6', 'left' => '6',
                                        'unit' => 'px', 'isLinked' => true
                                    ],
                                    'button_hover_background_background' => 'classic',
                                    'button_hover_background_color' => $colors['primary_dark'],
                                    'button_hover_border_color' => $colors['primary_dark'],
                                    'button_margin' => [
                                        'top' => '8', 'right' => '0', 'bottom' => '16', 'left' => '0',
                                        'unit' => 'px', 'isLinked' => false
                                    ]
                                ]
                            ],
                            // View Full Details Link - Using GGMC Product Details Link widget
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-details-link',
                                'settings' => [
                                    'link_text' => 'View Full Details →',
                                    'link_style' => 'text',
                                    'close_popup' => 'yes',
                                    'align' => 'left',
                                    'link_color' => $colors['primary'],
                                    'link_hover_color' => $colors['primary_dark'],
                                    'link_typography_typography' => 'custom',
                                    'link_typography_font_family' => $font_family,
                                    'link_typography_font_size' => ['size' => '14', 'unit' => 'px'],
                                    'link_typography_font_weight' => '500',
                                    'link_margin' => [
                                        'top' => '8', 'right' => '0', 'bottom' => '0', 'left' => '0',
                                        'unit' => 'px', 'isLinked' => false
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Create address edit/add popup template
     */
    private static function create_address_edit_popup() {
        $option_name = 'ggm_commerce_address_popup_id';
        $popup_id = get_option($option_name);
        $current_version = '2.0'; // Increment this when popup structure changes (now using custom widget)

        // Check if popup already exists and has proper settings
        if ($popup_id && get_post_status($popup_id) === 'publish') {
            // Check version and settings
            $settings = get_post_meta($popup_id, '_elementor_page_settings', true);
            $popup_version = get_post_meta($popup_id, '_ggmc_popup_version', true);

            // If version matches and settings are valid, skip recreation
            if (!empty($settings) && isset($settings['popup_width']) && $popup_version === $current_version) {
                return; // Popup is properly configured and up to date
            }
            // Delete and recreate if settings are missing or version is outdated
            wp_delete_post($popup_id, true);
        }

        // Create popup template
        $popup_id = wp_insert_post(array(
            'post_title' => 'GGM Commerce - Address Edit Popup',
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'elementor_library',
            'comment_status' => 'closed',
            'ping_status' => 'closed',
            'tax_input' => array(
                'elementor_library_type' => array('popup')
            )
        ));

        if ($popup_id && !is_wp_error($popup_id)) {
            // Set taxonomy term for popup (Elementor uses this to filter)
            wp_set_object_terms($popup_id, 'popup', 'elementor_library_type');

            // Set as popup template type
            update_post_meta($popup_id, '_elementor_template_type', 'popup');
            update_post_meta($popup_id, '_elementor_edit_mode', 'builder');
            update_post_meta($popup_id, '_elementor_version', '3.16.0');

            // Set popup settings with display conditions
            $popup_settings = [
                'popup_width' => [
                    'unit' => 'px',
                    'size' => 600
                ],
                'popup_height' => [
                    'unit' => 'auto'
                ],
                'prevent_scroll' => 'yes',
                'avoid_multiple_popups' => 'yes',
                'entrance_animation' => 'fadeIn',
                'exit_animation' => 'fadeOut',
                'entrance_animation_duration' => [
                    'unit' => 'px',
                    'size' => 0.6
                ],
                // Critical: Set triggers to none (manual trigger only via JavaScript)
                'triggers' => [],
                'timing' => [],
                // Note: Display conditions are handled programmatically via add_popup_to_location()
                // in the init_popup_hooks() method, but we keep this as a fallback
                'advanced_rules' => [
                    [
                        'type' => 'include',
                        'name' => 'general',
                        'sub_name' => 'entire_site'
                    ]
                ]
            ];
            update_post_meta($popup_id, '_elementor_page_settings', $popup_settings);

            // Get popup layout data - already JSON encoded
            $popup_data = self::get_address_popup_data();

            // Save as plain text, not serialized (Elementor expects JSON string)
            update_post_meta($popup_id, '_elementor_data', wp_slash($popup_data));

            // Mark as Elementor CSS needs regeneration
            update_post_meta($popup_id, '_elementor_css', array());
            update_post_meta($popup_id, '_elementor_controls_usage', array());

            // Save popup version for future checks
            update_post_meta($popup_id, '_ggmc_popup_version', $current_version);

            // Save popup ID
            update_option($option_name, $popup_id);
        }
    }

    /**
     * Create Product Comparison page
     * Called when the product-comparison premium component is activated.
     */
    public static function create_comparison_page() {
        $page_data = array(
            'title' => 'Product Comparison',
            'option' => 'ggm_commerce_comparison_page_id',
            'layout' => 'product-comparison'
        );

        self::create_page('product-comparison', $page_data);
    }

    /**
     * Initialize popup registration hooks
     * This should be called on plugin initialization to register popups to locations
     */
    public static function init_popup_hooks() {
        // Register popup on account page
        add_action('wp', array(__CLASS__, 'register_address_popup'));
    }

    /**
     * Register address popup to Elementor Pro location programmatically
     * This eliminates the need for manual display condition configuration
     */
    public static function register_address_popup() {
        // Check if Elementor Pro is active and the Popup module exists
        if (!class_exists('\ElementorPro\Modules\Popup\Module')) {
            return;
        }

        // Get popup ID
        $popup_id = get_option('ggm_commerce_address_popup_id');
        if (!$popup_id) {
            return;
        }

        // Get account page ID
        $account_page_id = get_option('ggm_commerce_account_page_id');

        // Register popup on account page
        if ($account_page_id && is_page($account_page_id)) {
            \ElementorPro\Modules\Popup\Module::add_popup_to_location($popup_id);
        }
    }

    /**
     * Page layout versions - increment when layout structure changes
     */
    private static $page_versions = [
        'product-details' => '2.1', // v2.1: Fixed container widths to 48% to account for gap
        'category-archive' => '2.0', // v2.0: Embedded widgets directly
        'tag-archive' => '2.0', // v2.0: Embedded widgets directly
    ];

    /**
     * Regenerate a specific page layout
     * Used when page layout version changes and existing pages need updating
     *
     * @param string $page_type The page type (e.g., 'product-details', 'category-archive')
     * @return bool True if regenerated, false if page not found
     */
    public static function regenerate_page_layout($page_type) {
        $option_map = [
            'product-details' => 'ggm_commerce_product_details_page_id',
            'category-archive' => 'ggm_commerce_category_archive_page_id',
            'tag-archive' => 'ggm_commerce_tag_archive_page_id',
            'shop' => 'ggm_commerce_shop_page_id',
            'cart' => 'ggm_commerce_cart_page_id',
            'checkout' => 'ggm_commerce_checkout_page_id',
            'account' => 'ggm_commerce_account_page_id',
            'wishlist' => 'ggm_commerce_wishlist_page_id',
            'product-comparison' => 'ggm_commerce_comparison_page_id',
            'thank-you' => 'ggm_commerce_thank_you_page_id',
        ];

        if (!isset($option_map[$page_type])) {
            return false;
        }

        $page_id = get_option($option_map[$page_type]);
        if (!$page_id || get_post_status($page_id) !== 'publish') {
            return false;
        }

        // Get layout type from page type
        $layout_type = $page_type;
        if ($page_type === 'account') {
            $layout_type = 'account';
        }

        // Regenerate the layout using the active builder
        if ( self::is_elementor_active() ) {
            self::add_elementor_layout($page_id, $layout_type);
            update_post_meta($page_id, '_ggmc_page_builder', 'elementor');
        } else {
            wp_update_post(array(
                'ID'           => $page_id,
                'post_content' => self::get_block_content($layout_type),
            ));
            update_post_meta($page_id, '_ggmc_page_builder', 'blocks');
        }

        // Update version
        if (isset(self::$page_versions[$page_type])) {
            update_post_meta($page_id, '_ggmc_page_version', self::$page_versions[$page_type]);
        }

        // Clear Elementor CSS cache for this page
        delete_post_meta($page_id, '_elementor_css');

        return true;
    }

    /**
     * Check and upgrade page layouts if needed
     * Called during plugin updates or manually
     */
    public static function check_and_upgrade_pages() {
        foreach (self::$page_versions as $page_type => $current_version) {
            $option_map = [
                'product-details' => 'ggm_commerce_product_details_page_id',
                'category-archive' => 'ggm_commerce_category_archive_page_id',
                'tag-archive' => 'ggm_commerce_tag_archive_page_id',
            ];

            if (!isset($option_map[$page_type])) {
                continue;
            }

            $page_id = get_option($option_map[$page_type]);
            if (!$page_id || get_post_status($page_id) !== 'publish') {
                continue;
            }

            $stored_version = get_post_meta($page_id, '_ggmc_page_version', true);
            if ($stored_version !== $current_version) {
                self::regenerate_page_layout($page_type);
            }
        }
    }

    /**
     * Create a single page with Elementor layout
     */
    private static function create_page($slug, $page_data) {
        $use_elementor = self::is_elementor_active();

        // Check if page ID is already stored
        $page_id = get_option($page_data['option']);

        // Check if page exists and is published
        if ($page_id && get_post_status($page_id) === 'publish') {
            // Check if page needs layout upgrade
            $page_type = $page_data['layout'];
            if ($use_elementor && isset(self::$page_versions[$page_type])) {
                $stored_version = get_post_meta($page_id, '_ggmc_page_version', true);
                if ($stored_version !== self::$page_versions[$page_type]) {
                    self::add_elementor_layout($page_id, $page_type);
                    update_post_meta($page_id, '_ggmc_page_version', self::$page_versions[$page_type]);
                    delete_post_meta($page_id, '_elementor_css');
                }
            }
            return; // Page already exists
        }

        // Check if a page with this slug already exists
        $existing_page = get_page_by_path($slug);

        if ($existing_page && $existing_page->post_status === 'publish') {
            update_option($page_data['option'], $existing_page->ID);
            if ($use_elementor) {
                self::add_elementor_layout($existing_page->ID, $page_data['layout']);
                update_post_meta($existing_page->ID, '_ggmc_page_builder', 'elementor');
            } else {
                wp_update_post(array(
                    'ID'           => $existing_page->ID,
                    'post_content' => self::get_block_content($page_data['layout']),
                ));
                update_post_meta($existing_page->ID, '_ggmc_page_builder', 'blocks');
            }
            return;
        }

        // Create new page
        $post_content = $use_elementor ? '' : self::get_block_content($page_data['layout']);

        $page_id = wp_insert_post(array(
            'post_title'    => $page_data['title'],
            'post_content'  => $post_content,
            'post_status'   => 'publish',
            'post_type'     => 'page',
            'post_name'     => $slug,
            'comment_status' => 'closed',
            'ping_status'   => 'closed'
        ));

        if ($page_id && !is_wp_error($page_id)) {
            update_option($page_data['option'], $page_id);
            if ($use_elementor) {
                self::add_elementor_layout($page_id, $page_data['layout']);
                update_post_meta($page_id, '_ggmc_page_builder', 'elementor');
            } else {
                update_post_meta($page_id, '_ggmc_page_builder', 'blocks');
            }
        }
    }

    /**
     * Add Elementor layout to a page
     */
    private static function add_elementor_layout($page_id, $layout_type) {
        // Enable Elementor for this page
        update_post_meta($page_id, '_elementor_edit_mode', 'builder');
        update_post_meta($page_id, '_elementor_template_type', 'wp-page');
        update_post_meta($page_id, '_elementor_version', '3.16.0');
        update_post_meta($page_id, '_elementor_page_settings', array());

        // Get the layout data based on type
        $elementor_data = self::get_layout_data($layout_type);

        // Save Elementor data
        update_post_meta($page_id, '_elementor_data', $elementor_data);
    }

    /**
     * Get Elementor layout data based on page type
     */
    private static function get_layout_data($layout_type) {
        switch ($layout_type) {
            case 'shop':
                return self::get_shop_layout();
            case 'cart':
                return self::get_cart_layout();
            case 'checkout':
                return self::get_checkout_layout();
            case 'account':
                return self::get_account_layout();
            case 'product-details':
                return self::get_product_details_layout();
            case 'category-archive':
                return self::get_category_archive_layout();
            case 'tag-archive':
                return self::get_tag_archive_layout();
            case 'wishlist':
                return self::get_wishlist_layout();
            case 'product-comparison':
                return self::get_product_comparison_layout();
            case 'thank-you':
                return self::get_thank_you_layout();
            default:
                return '[]';
        }
    }

    /**
     * Shop page layout - Filter sidebar + Product grid
     */
    private static function get_shop_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                    'flex_direction' => 'row',
                    'flex_wrap' => 'wrap',
                    'gap' => [
                        'unit' => 'px',
                        'size' => 20
                    ]
                ],
                'elements' => [
                    // Left sidebar - Filter (23% width)
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'width' => [
                                'unit' => '%',
                                'size' => 23
                            ],
                            'width_tablet' => [
                                'unit' => '%',
                                'size' => 100
                            ],
                            'content_width' => 'full'
                        ],
                        'elements' => [
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-filter',
                                'settings' => []
                            ]
                        ]
                    ],
                    // Right side - Product grid
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'width' => [
                                'unit' => '%',
                                'size' => 75
                            ],
                            'width_tablet' => [
                                'unit' => '%',
                                'size' => 100
                            ],
                            'content_width' => 'full'
                        ],
                        'elements' => [
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-grid',
                                'settings' => [
                                    'columns' => 3,
                                    'columns_tablet' => 2,
                                    'columns_mobile' => 1,
                                    'posts_per_page' => 12
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Cart page layout - Cart display widget
     */
    private static function get_cart_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                ],
                'elements' => [
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-cart-display',
                        'settings' => []
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Checkout page layout - Checkout widget
     */
    private static function get_checkout_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                ],
                'elements' => [
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-checkout',
                        'settings' => []
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * My Account page layout - Customer account widget
     */
    private static function get_account_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                ],
                'elements' => [
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-customer-account',
                        'settings' => [
                            'show_login' => 'yes',
                            'show_register' => 'yes'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Address edit popup layout - Now uses custom widget for full styling control
     */
    private static function get_address_popup_data() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'full',
                    'padding' => [
                        'unit' => 'px',
                        'top' => '30',
                        'right' => '30',
                        'bottom' => '30',
                        'left' => '30'
                    ]
                ],
                'elements' => [
                    // Use custom Address Form widget for full Elementor styling control
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-address-form',
                        'settings' => [
                            'form_title' => 'Edit Address',
                            'show_address_label' => 'yes',
                            'show_company' => 'yes'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * OLD popup layout using HTML blocks - kept for reference, can be deleted later
     */
    private static function get_address_popup_data_OLD() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'full',
                    'padding' => [
                        'unit' => 'px',
                        'top' => '30',
                        'right' => '30',
                        'bottom' => '30',
                        'left' => '30'
                    ]
                ],
                'elements' => [
                    // Heading with address type indicator
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<h3 id="modal-title" style="margin: 0 0 10px 0;">Edit Address</h3><p id="address-type-display" style="margin: 0 0 20px 0; color: #666; font-size: 14px;"></p>'
                        ]
                    ],
                    // Hidden fields and Address Label
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<input type="hidden" id="address_id"><input type="hidden" id="address_type"><div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Address Label</label><input type="text" id="address_label" placeholder="e.g., Home, Office" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                        ]
                    ],
                    // Name Fields
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'content_width' => 'full',
                            'flex_direction' => 'row',
                            'flex_gap' => ['size' => 15]
                        ],
                        'elements' => [
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'html',
                                'settings' => [
                                    'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">First Name</label><input type="text" id="first_name" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                                ]
                            ],
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'html',
                                'settings' => [
                                    'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Last Name</label><input type="text" id="last_name" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                                ]
                            ]
                        ]
                    ],
                    // Company
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Company</label><input type="text" id="company" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                        ]
                    ],
                    // Address Lines
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Address Line 1 <span style="color: red;">*</span></label><input type="text" id="address_1" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                        ]
                    ],
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Address Line 2</label><input type="text" id="address_2" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                        ]
                    ],
                    // City, State, Postcode
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'content_width' => 'full',
                            'flex_direction' => 'row',
                            'flex_gap' => ['size' => 15]
                        ],
                        'elements' => [
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'html',
                                'settings' => [
                                    'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">City <span style="color: red;">*</span></label><input type="text" id="city" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                                ]
                            ],
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'html',
                                'settings' => [
                                    'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">State <span style="color: red;">*</span></label><input type="text" id="state" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                                ]
                            ],
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'html',
                                'settings' => [
                                    'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Postcode <span style="color: red;">*</span></label><input type="text" id="postcode" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                                ]
                            ]
                        ]
                    ],
                    // Country
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Country <span style="color: red;">*</span></label><select id="country" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"><option value="">Select Country</option><option value="US">United States</option><option value="CA">Canada</option><option value="GB">United Kingdom</option><option value="AU">Australia</option><option value="DE">Germany</option><option value="FR">France</option><option value="IT">Italy</option><option value="ES">Spain</option><option value="NL">Netherlands</option><option value="BE">Belgium</option><option value="CH">Switzerland</option><option value="AT">Austria</option><option value="SE">Sweden</option><option value="NO">Norway</option><option value="DK">Denmark</option><option value="FI">Finland</option><option value="JP">Japan</option><option value="KR">South Korea</option><option value="SG">Singapore</option><option value="HK">Hong Kong</option><option value="NZ">New Zealand</option><option value="MX">Mexico</option><option value="BR">Brazil</option><option value="AR">Argentina</option><option value="CL">Chile</option><option value="IN">India</option><option value="CN">China</option><option value="RU">Russia</option><option value="ZA">South Africa</option><option value="EG">Egypt</option><option value="NG">Nigeria</option><option value="KE">Kenya</option><option value="MA">Morocco</option><option value="TN">Tunisia</option><option value="GH">Ghana</option><option value="UG">Uganda</option><option value="TZ">Tanzania</option><option value="ZW">Zimbabwe</option><option value="BW">Botswana</option><option value="ZM">Zambia</option><option value="MW">Malawi</option><option value="MZ">Mozambique</option><option value="AO">Angola</option><option value="NA">Namibia</option><option value="SZ">Eswatini</option><option value="LS">Lesotho</option></select></div>'
                        ]
                    ],
                    // Phone
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<div style="margin-bottom: 20px;"><label style="display: block; margin-bottom: 8px; font-weight: 500;">Phone</label><input type="tel" id="phone" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>'
                        ]
                    ],
                    // Default checkbox
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<div style="margin-bottom: 20px;"><label style="display: flex; align-items: center; gap: 8px;"><input type="checkbox" id="is_default"> Set as default address</label></div>'
                        ]
                    ],
                    // Buttons
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'html',
                        'settings' => [
                            'html' => '<div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;"><button type="button" id="btn-cancel-address" style="padding: 12px 24px; background: #f0f0f0; color: #333; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: 500;">Cancel</button><button type="button" id="btn-save-address" style="padding: 12px 24px; background: #0073aa; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: 500;">Save Address</button></div>'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Product Details page layout
     * Layout: Main boxed container with flex row direction
     * - Left: Product Gallery widget
     * - Right: Container with product info widgets stacked vertically
     */
    private static function get_product_details_layout() {
        $layout = [
            // Main container - boxed, flex row direction
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                    'flex_direction' => 'row',
                    'flex_wrap' => 'wrap',
                    'gap' => [
                        'unit' => 'px',
                        'size' => 40
                    ],
                    'padding' => [
                        'unit' => 'px',
                        'top' => '40',
                        'right' => '20',
                        'bottom' => '40',
                        'left' => '20'
                    ]
                ],
                'elements' => [
                    // Left side - Product Gallery container (48% to account for gap)
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'content_width' => 'full',
                            'width' => [
                                'unit' => '%',
                                'size' => 48
                            ],
                            'width_tablet' => [
                                'unit' => '%',
                                'size' => 100
                            ]
                        ],
                        'elements' => [
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-gallery',
                                'settings' => [
                                    'gallery_layout' => 'standard',
                                    'enable_lightbox' => 'yes',
                                    'enable_zoom' => 'yes'
                                ]
                            ]
                        ]
                    ],
                    // Right side - Container with product info (flex column, 48% to account for gap)
                    [
                        'id' => self::generate_id(),
                        'elType' => 'container',
                        'settings' => [
                            'content_width' => 'full',
                            'width' => [
                                'unit' => '%',
                                'size' => 48
                            ],
                            'width_tablet' => [
                                'unit' => '%',
                                'size' => 100
                            ],
                            'flex_direction' => 'column',
                            'gap' => [
                                'unit' => 'px',
                                'size' => 16
                            ]
                        ],
                        'elements' => [
                            // Product Name
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-name',
                                'settings' => [
                                    'html_tag' => 'h1'
                                ]
                            ],
                            // Product Price
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-price',
                                'settings' => []
                            ],
                            // Product Stock
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-stock',
                                'settings' => [
                                    'prefix' => 'In Stock: '
                                ]
                            ],
                            // Short Description
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-description',
                                'settings' => [
                                    'description_type' => 'short'
                                ]
                            ],
                            // Add to Cart
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-add-to-cart',
                                'settings' => [
                                    'show_quantity' => 'yes',
                                    'button_text' => 'Add to Cart'
                                ]
                            ],
                            // Full Description
                            [
                                'id' => self::generate_id(),
                                'elType' => 'widget',
                                'widgetType' => 'ggmc-product-description',
                                'settings' => [
                                    'description_type' => 'full'
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Category archive page layout
     * Layout: Category header + Product grid filtered by category
     */
    private static function get_category_archive_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                    'flex_direction' => 'column',
                    'gap' => [
                        'unit' => 'px',
                        'size' => 30
                    ],
                    'padding' => [
                        'unit' => 'px',
                        'top' => '40',
                        'right' => '20',
                        'bottom' => '40',
                        'left' => '20'
                    ]
                ],
                'elements' => [
                    // Category Header Widget
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-taxonomy-header',
                        'settings' => [
                            'taxonomy_type' => 'category',
                            'show_image' => 'yes',
                            'show_description' => 'yes',
                            'show_product_count' => 'yes'
                        ]
                    ],
                    // Product Grid filtered by current category
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-product-grid',
                        'settings' => [
                            'columns' => 4,
                            'columns_tablet' => 2,
                            'columns_mobile' => 1,
                            'posts_per_page' => 12,
                            'filter_by_current_taxonomy' => 'yes'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Tag archive page layout
     * Layout: Tag header + Product grid filtered by tag
     */
    private static function get_tag_archive_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                    'flex_direction' => 'column',
                    'gap' => [
                        'unit' => 'px',
                        'size' => 30
                    ],
                    'padding' => [
                        'unit' => 'px',
                        'top' => '40',
                        'right' => '20',
                        'bottom' => '40',
                        'left' => '20'
                    ]
                ],
                'elements' => [
                    // Tag Header Widget
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-taxonomy-header',
                        'settings' => [
                            'taxonomy_type' => 'tag',
                            'show_description' => 'yes',
                            'show_product_count' => 'yes'
                        ]
                    ],
                    // Product Grid filtered by current tag
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-product-grid',
                        'settings' => [
                            'columns' => 4,
                            'columns_tablet' => 2,
                            'columns_mobile' => 1,
                            'posts_per_page' => 12,
                            'filter_by_current_taxonomy' => 'yes'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Wishlist page layout - Wishlist widget
     */
    private static function get_wishlist_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                    'padding' => [
                        'unit' => 'px',
                        'top' => '40',
                        'right' => '20',
                        'bottom' => '40',
                        'left' => '20',
                        'isLinked' => false
                    ]
                ],
                'elements' => [
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-wishlist',
                        'settings' => [
                            'title' => 'My Wishlist',
                            'show_title' => 'yes',
                            'layout' => 'table',
                            'show_remove_button' => 'yes',
                            'show_add_to_cart' => 'yes',
                            'show_clear_all' => 'yes',
                            'show_image' => 'yes',
                            'show_price' => 'yes',
                            'show_stock_status' => 'yes',
                            'empty_message' => 'Your wishlist is empty. Browse our products and add items to your wishlist!'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Product Comparison page layout - Product Comparison widget
     */
    private static function get_product_comparison_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                    'padding' => [
                        'unit' => 'px',
                        'top' => '40',
                        'right' => '20',
                        'bottom' => '40',
                        'left' => '20',
                        'isLinked' => false
                    ]
                ],
                'elements' => [
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-product-comparison',
                        'settings' => [
                            'title' => 'Product Comparison',
                            'show_title' => 'yes',
                            'show_remove_button' => 'yes',
                            'show_clear_all' => 'yes',
                            'show_add_products_cta' => 'yes',
                            'add_products_text' => 'Browse Products',
                            'show_image' => 'yes',
                            'show_name' => 'yes',
                            'show_price' => 'yes',
                            'show_stock' => 'yes',
                            'show_sku' => 'yes',
                            'show_description' => 'yes',
                            'show_categories' => 'yes',
                            'show_rating' => 'yes',
                            'show_add_to_cart' => 'yes',
                            'sticky_first_column' => 'yes',
                            'empty_message' => 'No products selected for comparison. Browse our products and click the Compare button to add items!'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Thank You / Order Confirmation page layout
     * Layout: Centered container with Order Confirmation widget
     */
    private static function get_thank_you_layout() {
        $layout = [
            [
                'id' => self::generate_id(),
                'elType' => 'container',
                'settings' => [
                    'content_width' => 'boxed',
                    'flex_direction' => 'column',
                    'flex_align_items' => 'center',
                    'padding' => [
                        'unit' => 'px',
                        'top' => '40',
                        'right' => '20',
                        'bottom' => '40',
                        'left' => '20',
                        'isLinked' => false
                    ]
                ],
                'elements' => [
                    [
                        'id' => self::generate_id(),
                        'elType' => 'widget',
                        'widgetType' => 'ggmc-order-confirmation',
                        'settings' => [
                            'success_title' => 'Thank You For Your Order!',
                            'success_message' => 'Your order has been received and is being processed. You will receive an email confirmation shortly.',
                            'show_order_number' => 'yes',
                            'show_order_date' => 'yes',
                            'show_order_items' => 'yes',
                            'show_totals' => 'yes',
                            'show_billing_address' => 'yes',
                            'show_shipping_address' => 'yes',
                            'show_payment_method' => 'yes',
                            'show_continue_shopping' => 'yes',
                            'continue_shopping_text' => 'Continue Shopping'
                        ]
                    ]
                ]
            ]
        ];

        return wp_json_encode($layout);
    }

    /**
     * Generate unique Elementor element ID
     */
    private static function generate_id() {
        return dechex(wp_rand(0x10000000, 0x1fffffff));
    }

    // ─── Gutenberg block content generators ──────────────────────────

    /**
     * Get Gutenberg block markup for a given layout type.
     *
     * @param string $layout_type Layout key matching Elementor layout names.
     * @return string Block markup (serialised Gutenberg comments).
     */
    public static function get_block_content( $layout_type ) {
        switch ( $layout_type ) {
            case 'shop':
                return self::get_shop_block_content();
            case 'cart':
                return self::get_cart_block_content();
            case 'checkout':
                return self::get_checkout_block_content();
            case 'account':
                return self::get_account_block_content();
            case 'product-details':
                return self::get_product_details_block_content();
            case 'category-archive':
                return self::get_category_archive_block_content();
            case 'tag-archive':
                return self::get_tag_archive_block_content();
            case 'wishlist':
                return self::get_wishlist_block_content();
            case 'product-comparison':
                return self::get_product_comparison_block_content();
            case 'thank-you':
                return self::get_thank_you_block_content();
            default:
                return '';
        }
    }

    /**
     * Shop page — filter sidebar + product grid in a columns layout.
     */
    private static function get_shop_block_content() {
        return '<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column {"width":"25%"} -->
<div class="wp-block-column" style="flex-basis:25%"><!-- wp:ggmc/product-filter /--></div>
<!-- /wp:column -->

<!-- wp:column {"width":"75%"} -->
<div class="wp-block-column" style="flex-basis:75%"><!-- wp:ggmc/product-grid {"productsPerPage":12,"columns":3} /--></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->';
    }

    /**
     * Cart page — cart display block.
     */
    private static function get_cart_block_content() {
        return '<!-- wp:ggmc/cart-display /-->';
    }

    /**
     * Checkout page — checkout block.
     */
    private static function get_checkout_block_content() {
        return '<!-- wp:ggmc/checkout /-->';
    }

    /**
     * My Account page — customer account block.
     */
    private static function get_account_block_content() {
        return '<!-- wp:ggmc/customer-account {"showLogin":"yes","showRegister":"yes"} /-->';
    }

    /**
     * Product Details page — gallery left, info right in columns.
     */
    private static function get_product_details_block_content() {
        return '<!-- wp:columns -->
<div class="wp-block-columns"><!-- wp:column {"width":"50%"} -->
<div class="wp-block-column" style="flex-basis:50%"><!-- wp:ggmc/product-gallery /--></div>
<!-- /wp:column -->

<!-- wp:column {"width":"50%"} -->
<div class="wp-block-column" style="flex-basis:50%"><!-- wp:ggmc/product-name {"htmlTag":"h1"} /-->

<!-- wp:ggmc/product-price /-->

<!-- wp:ggmc/product-stock /-->

<!-- wp:ggmc/product-description {"descriptionType":"short"} /-->

<!-- wp:ggmc/add-to-cart {"showQuantity":"yes"} /-->

<!-- wp:ggmc/product-description {"descriptionType":"full"} /--></div>
<!-- /wp:column --></div>
<!-- /wp:columns -->';
    }

    /**
     * Category archive page — taxonomy header + filtered product grid.
     */
    private static function get_category_archive_block_content() {
        return '<!-- wp:ggmc/taxonomy-header {"taxonomyType":"category","showImage":"yes","showDescription":"yes","showProductCount":"yes"} /-->

<!-- wp:ggmc/product-grid {"productsPerPage":12,"columns":4,"filterByCurrentTaxonomy":"yes"} /-->';
    }

    /**
     * Tag archive page — taxonomy header + filtered product grid.
     */
    private static function get_tag_archive_block_content() {
        return '<!-- wp:ggmc/taxonomy-header {"taxonomyType":"tag","showDescription":"yes","showProductCount":"yes"} /-->

<!-- wp:ggmc/product-grid {"productsPerPage":12,"columns":4,"filterByCurrentTaxonomy":"yes"} /-->';
    }

    /**
     * Wishlist page — wishlist block.
     */
    private static function get_wishlist_block_content() {
        return '<!-- wp:ggmc/wishlist {"title":"My Wishlist","showTitle":"yes","layout":"table","showRemoveButton":"yes","showAddToCart":"yes","showClearAll":"yes","showImage":"yes","showPrice":"yes","showStockStatus":"yes","emptyMessage":"Your wishlist is empty. Browse our products and add items to your wishlist!"} /-->';
    }

    /**
     * Product Comparison page — comparison block.
     */
    private static function get_product_comparison_block_content() {
        return '<!-- wp:ggmc/product-comparison {"title":"Product Comparison","showTitle":"yes","showRemoveButton":"yes","showClearAll":"yes","showImage":"yes","showName":"yes","showPrice":"yes","showStock":"yes","showSku":"yes","showDescription":"yes","showCategories":"yes","showRating":"yes","showAddToCart":"yes","emptyMessage":"No products selected for comparison. Browse our products and click the Compare button to add items!"} /-->';
    }

    /**
     * Order Confirmation / Thank-you page.
     */
    private static function get_thank_you_block_content() {
        return '<!-- wp:ggmc/order-confirmation {"successTitle":"Thank You For Your Order!","successMessage":"Your order has been received and is being processed. You will receive an email confirmation shortly.","showOrderNumber":"yes","showOrderDate":"yes","showOrderItems":"yes","showTotals":"yes","showBillingAddress":"yes","showShippingAddress":"yes","showPaymentMethod":"yes","showContinueShopping":"yes","continueShoppingText":"Continue Shopping"} /-->';
    }
}
