<?php
/**
 * Goose Commerce Admin Class
 * Handles all WordPress admin interface functionality
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

class GGM_Commerce_Admin {

    public function __construct() {
        add_action('admin_menu', array($this, 'admin_menu'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_init', array($this, 'set_admin_page_titles_early'), 1);
        add_action('admin_init', array($this, 'handle_product_duplicate_redirect'), 5);
        add_filter('admin_title', array($this, 'fix_admin_page_titles'), 10, 2);
        add_action('admin_head', array($this, 'hide_submenu_items'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        
        // AJAX handlers for default styles
        add_action('wp_ajax_ggm_commerce_apply_all_defaults', array($this, 'ajax_apply_all_defaults'));
        add_action('wp_ajax_ggm_commerce_remove_all_defaults', array($this, 'ajax_remove_all_defaults'));

        // AJAX handler for floating bar toggle
        add_action('wp_ajax_ggm_commerce_update_floating_bar', array($this, 'ajax_update_floating_bar'));

        // AJAX handler for widget prioritization toggle
        add_action('wp_ajax_ggm_commerce_update_widgets_prioritized', array($this, 'ajax_update_widgets_prioritized'));

        // AJAX handlers for address settings
        add_action('wp_ajax_ggm_commerce_toggle_multiple_billing', array($this, 'ajax_toggle_multiple_billing'));
        add_action('wp_ajax_ggm_commerce_toggle_multiple_shipping', array($this, 'ajax_toggle_multiple_shipping'));

        // AJAX handler for MCP authentication toggle
        add_action('wp_ajax_ggm_mcp_toggle_auth', array($this, 'ajax_toggle_mcp_auth'));

        // AJAX handlers for MCP API key management
        add_action('wp_ajax_ggm_mcp_generate_api_key', array($this, 'ajax_generate_mcp_api_key'));
        add_action('wp_ajax_ggm_mcp_revoke_api_key', array($this, 'ajax_revoke_mcp_api_key'));
        add_action('wp_ajax_ggm_mcp_toggle_api_key', array($this, 'ajax_toggle_mcp_api_key'));

        // AJAX handler for clearing all carts
        add_action('wp_ajax_ggm_clear_all_carts', array($this, 'ajax_clear_all_carts'));

        // AJAX handlers for clearing wishlists and comparisons
        add_action('wp_ajax_ggm_clear_all_wishlists', array($this, 'ajax_clear_all_wishlists'));
        add_action('wp_ajax_ggm_clear_all_comparisons', array($this, 'ajax_clear_all_comparisons'));

        // AJAX handlers for kit stock management
        add_action('wp_ajax_ggmc_create_kit_stock', array($this, 'ajax_create_kit_stock'));
        add_action('wp_ajax_ggmc_breakdown_kit_stock', array($this, 'ajax_breakdown_kit_stock'));

        // AJAX handlers for payment gateway settings
        add_action('wp_ajax_ggm_commerce_save_stripe_settings', array($this, 'ajax_save_stripe_settings'));
        add_action('wp_ajax_ggm_commerce_save_paypal_settings', array($this, 'ajax_save_paypal_settings'));

        // AJAX handler for setting default category
        add_action('wp_ajax_ggmc_set_default_category', array($this, 'ajax_set_default_category'));

        // AJAX handler for icon picker SVG upload
        add_action('wp_ajax_ggmc_upload_svg_icon', array($this, 'ajax_upload_svg_icon'));

        // AJAX handler for getting component images (kit/build gallery population)
        add_action('wp_ajax_ggmc_get_component_images', array($this, 'ajax_get_component_images'));

        // AJAX handler for generating variations
        add_action('wp_ajax_ggmc_generate_variations', array($this, 'ajax_generate_variations'));

        // AJAX handler for deleting a product variation
        add_action('wp_ajax_ggmc_delete_product_variation', array($this, 'ajax_delete_product_variation'));

        // AJAX handler for auto-generating variation SKUs
        add_action('wp_ajax_ggmc_autogenerate_variation_skus', array($this, 'ajax_autogenerate_variation_skus'));

        // AJAX handler for getting variation details (for edit modal)
        add_action('wp_ajax_ggmc_get_variation_details', array($this, 'ajax_get_variation_details'));

        // AJAX handler for updating variation details
        add_action('wp_ajax_ggmc_update_variation', array($this, 'ajax_update_variation'));

        // AJAX handlers for Independent mode option management
        add_action('wp_ajax_ggmc_remove_independent_option', array($this, 'ajax_remove_independent_option'));
        add_action('wp_ajax_ggmc_add_independent_option', array($this, 'ajax_add_independent_option'));
        add_action('wp_ajax_ggmc_add_all_missing_options', array($this, 'ajax_add_all_missing_options'));

        // AJAX handlers for Widget Controls styling settings
        add_action('wp_ajax_ggm_commerce_save_compare_bar_styles', array($this, 'ajax_save_compare_bar_styles'));
        add_action('wp_ajax_ggm_commerce_save_notification_settings', array($this, 'ajax_save_notification_settings'));
        add_action('wp_ajax_ggm_commerce_save_notification_messages', array($this, 'ajax_save_notification_messages'));
        add_action('wp_ajax_ggm_commerce_save_wishlist_settings', array($this, 'ajax_save_wishlist_settings'));
        add_action('wp_ajax_ggm_commerce_update_powered_by', array($this, 'ajax_update_powered_by'));

        // AJAX handlers for import/export
        add_action('wp_ajax_ggmc_export_products', array($this, 'ajax_export_products'));
        add_action('wp_ajax_ggmc_export_json', array($this, 'ajax_export_json'));
        add_action('wp_ajax_ggmc_export_image_package', array($this, 'ajax_export_image_package'));
        add_action('wp_ajax_ggmc_download_template', array($this, 'ajax_download_template'));
        add_action('wp_ajax_ggmc_upload_import_file', array($this, 'ajax_upload_import_file'));
        add_action('wp_ajax_ggmc_process_import', array($this, 'ajax_process_import'));
        add_action('wp_ajax_ggmc_get_import_progress', array($this, 'ajax_get_import_progress'));
        add_action('wp_ajax_ggmc_upload_json_import', array($this, 'ajax_upload_json_import'));
        add_action('wp_ajax_ggmc_process_json_import', array($this, 'ajax_process_json_import'));

        // AJAX handlers for background import
        add_action('wp_ajax_ggmc_start_background_import', array($this, 'ajax_start_background_import'));
        add_action('wp_ajax_ggmc_get_background_import_status', array($this, 'ajax_get_background_import_status'));
        add_action('wp_ajax_ggmc_cancel_background_import', array($this, 'ajax_cancel_background_import'));

        // AJAX handlers for import reports
        add_action('wp_ajax_ggmc_get_import_reports', array($this, 'ajax_get_import_reports'));
        add_action('wp_ajax_ggmc_delete_import_report', array($this, 'ajax_delete_import_report'));
        add_action('wp_ajax_ggmc_delete_all_import_reports', array($this, 'ajax_delete_all_import_reports'));

        // AJAX handlers for bulk actions
        add_action('wp_ajax_ggmc_bulk_products_action', array($this, 'ajax_bulk_products_action'));
        add_action('wp_ajax_ggmc_bulk_categories_action', array($this, 'ajax_bulk_categories_action'));
        add_action('wp_ajax_ggmc_bulk_tags_action', array($this, 'ajax_bulk_tags_action'));
        add_action('wp_ajax_ggmc_bulk_attributes_action', array($this, 'ajax_bulk_attributes_action'));
        add_action('wp_ajax_ggmc_bulk_variations_action', array($this, 'ajax_bulk_variations_action'));

        // AJAX handler for attribute filterable toggle
        add_action('wp_ajax_ggmc_toggle_attribute_filterable', array($this, 'ajax_toggle_attribute_filterable'));

        // AJAX handlers for taxonomy/attribute/variation import/export
        add_action('wp_ajax_ggmc_export_categories', array($this, 'ajax_export_categories'));
        add_action('wp_ajax_ggmc_export_tags', array($this, 'ajax_export_tags'));
        add_action('wp_ajax_ggmc_export_attribute_groups', array($this, 'ajax_export_attribute_groups'));
        add_action('wp_ajax_ggmc_export_attributes', array($this, 'ajax_export_attributes'));
        add_action('wp_ajax_ggmc_export_variation_types', array($this, 'ajax_export_variation_types'));
        add_action('wp_ajax_ggmc_download_taxonomy_template', array($this, 'ajax_download_taxonomy_template'));
        add_action('wp_ajax_ggmc_import_taxonomy_init', array($this, 'ajax_import_taxonomy_init'));
        add_action('wp_ajax_ggmc_import_taxonomy_batch', array($this, 'ajax_import_taxonomy_batch'));
        add_action('wp_ajax_ggmc_import_attributes_init', array($this, 'ajax_import_attributes_init'));
        add_action('wp_ajax_ggmc_import_attributes_batch', array($this, 'ajax_import_attributes_batch'));
        add_action('wp_ajax_ggmc_import_variation_types_init', array($this, 'ajax_import_variation_types_init'));
        add_action('wp_ajax_ggmc_import_variation_types_batch', array($this, 'ajax_import_variation_types_batch'));

        // Admin notice for data cleanup warning on plugins page
        add_action('admin_notices', array($this, 'show_cleanup_warning_on_plugins_page'));
    }

    /**
     * Render a branded page title with the Goose icon.
     */
    public static function page_title( $title ) {
        $icon_url = plugins_url( 'assets/images/Icon-white.svg', dirname( __FILE__ ) );
        printf(
            '<h1 class="wp-heading-inline ggmc-page-title"><img src="%s" alt=""> %s</h1>',
            esc_url( $icon_url ),
            esc_html( $title )
        );
    }

    /**
     * Check if default styles are globally enabled
     */
    public static function are_defaults_enabled() {
        // Check if widget files have defaults enabled
        return self::check_widget_defaults_status();
    }
    
    /**
     * Enable or disable default styles globally 
     */
    public static function set_defaults_enabled($enabled) {
        if ($enabled) {
            return self::enable_widget_defaults();
        } else {
            return self::disable_widget_defaults();
        }
    }
    
    /**
     * Check if widget files currently have defaults enabled
     */
    private static function check_widget_defaults_status() {
        $widget_file = plugin_dir_path(dirname(__FILE__)) . 'widgets/tags/widget-product-name.php';
        if (!file_exists($widget_file)) {
            return false;
        }
        
        $content = file_get_contents($widget_file);
        
        // Check for proper default values (not empty strings)
        $has_text_color = strpos($content, "'default' => '#1F2937'") !== false;
        $has_hover_color = strpos($content, "'default' => '#2563eb'") !== false;
        
        // Consider defaults enabled if we have the proper color values
        $defaults_enabled = $has_text_color && $has_hover_color;
        
        
        return $defaults_enabled;
    }
    
    /**
     * Enable defaults in all widget files
     */
    private static function enable_widget_defaults() {
        $widgets_updated = 0;
        
        // Check current status first
        $current_status = self::check_widget_defaults_status();
        
        if ($current_status) {
            return true; // Already enabled, consider it successful
        }
        
        // Define the widget files and their replacement patterns
        $widget_files = [
            'widgets/tags/widget-product-name.php' => [
                // Use a two-step approach: first replace all empty defaults to temp values, then to final values
            ],
        ];
        
        foreach ($widget_files as $file_path => $replacements) {
            $full_path = plugin_dir_path(dirname(__FILE__)) . $file_path;
            if (file_exists($full_path)) {
                $content = file_get_contents($full_path);
                $original_content = $content;
                $updated = false;
                
                // Step 1: Replace text_color empty default
                $text_color_pattern = "'text_color',\n            [\n                'label' => __('Text Color', 'ggm-commerce'),\n                'type' => \\Elementor\\Controls_Manager::COLOR,\n                'default' => '',";
                $text_color_replacement = "'text_color',\n            [\n                'label' => __('Text Color', 'ggm-commerce'),\n                'type' => \\Elementor\\Controls_Manager::COLOR,\n                'default' => '#1F2937',";
                
                if (strpos($content, $text_color_pattern) !== false) {
                    $content = str_replace($text_color_pattern, $text_color_replacement, $content);
                    $updated = true;
                } else {
                    // Try simpler pattern - need to ensure correct order: text_color first (gets #1F2937)
                    $simple_pattern = "'default' => '',";
                    $count_before = substr_count($content, $simple_pattern);
                    if ($count_before > 0) {
                        // Replace first occurrence with text_color value
                        $content = preg_replace("/'default' => '',/", "'default' => '#1F2937',", $content, 1);
                        $updated = true;
                    } else {
                    }
                }
                
                // Step 2: Replace hover_color empty default
                $hover_color_pattern = "'hover_color',\n            [\n                'label' => __('Hover Color', 'ggm-commerce'),\n                'type' => \\Elementor\\Controls_Manager::COLOR,\n                'default' => '',";
                $hover_color_replacement = "'hover_color',\n            [\n                'label' => __('Hover Color', 'ggm-commerce'),\n                'type' => \\Elementor\\Controls_Manager::COLOR,\n                'default' => '#2563eb',";
                
                if (strpos($content, $hover_color_pattern) !== false) {
                    $content = str_replace($hover_color_pattern, $hover_color_replacement, $content);
                    $updated = true;
                } else {
                    // Replace remaining empty defaults with hover_color value (#2563eb)
                    $count_after = substr_count($content, "'default' => '',");
                    if ($count_after > 0) {
                        // Replace the remaining empty default (should be hover_color)
                        $content = preg_replace("/'default' => '',/", "'default' => '#2563eb',", $content, 1);
                        $updated = true;
                    } else {
                    }
                }
                
                // Step 3: The margin should be handled by the has_default_styling() method
                // No file modification needed - it checks for '#1F2937' to determine if defaults are enabled
                
                if ($updated) {
                    file_put_contents($full_path, $content);
                    $widgets_updated++;
                } else {
                }
            } else {
            }
        }
        
        // Clear PHP opcache if available
        if (function_exists('opcache_invalidate')) {
            foreach ($widget_files as $file_path => $replacements) {
                $full_path = plugin_dir_path(dirname(__FILE__)) . $file_path;
                opcache_invalidate($full_path, true);
            }
        }
        
        return $widgets_updated > 0;
    }
    
    /**
     * Disable defaults in all widget files
     */
    private static function disable_widget_defaults() {
        $widgets_updated = 0;
        
        // Define the widget files and their removal replacements
        $widget_files = [
            'widgets/tags/widget-product-name.php' => [
                // Text color removal
                "'default' => '#1F2937'," => "'default' => '',",
                // Hover color removal
                "'default' => '#2563eb'," => "'default' => '',",
            ],
        ];
        
        foreach ($widget_files as $file_path => $replacements) {
            $full_path = plugin_dir_path(dirname(__FILE__)) . $file_path;
            if (file_exists($full_path)) {
                $content = file_get_contents($full_path);
                $updated = false;
                
                foreach ($replacements as $search => $replace) {
                    if (strpos($content, $search) !== false) {
                        $content = str_replace($search, $replace, $content);
                        $updated = true;
                    } else {
                    }
                }
                
                if ($updated) {
                    file_put_contents($full_path, $content);
                    $widgets_updated++;
                } else {
                }
            } else {
            }
        }
        
        // Clear PHP opcache if available
        if (function_exists('opcache_invalidate')) {
            foreach ($widget_files as $file_path => $replacements) {
                $full_path = plugin_dir_path(dirname(__FILE__)) . $file_path;
                opcache_invalidate($full_path, true);
            }
        }
        
        return $widgets_updated > 0;
    }

    /**
     * Set admin page titles early to avoid null warnings.
     * This runs on admin_init before admin-header.php processes the title.
     */
    public function set_admin_page_titles_early() {
        global $title;

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page parameter for routing
        if (!isset($_GET['page'])) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page parameter for routing
        $page = sanitize_key($_GET['page']);

        // Set title for hidden pages that don't have a menu parent
        switch ($page) {
            case 'ggmc-add-product':
                $title = 'Add Product';
                break;

            case 'ggmc-edit-product':
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading id parameter for display
                if (isset($_GET['id'])) {
                    global $wpdb;
                    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading id parameter for display
                    $product_id = intval($_GET['id']);
                    $products_table = $wpdb->prefix . 'ggmc_products';
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name
                    $product = $wpdb->get_row($wpdb->prepare("SELECT name FROM $products_table WHERE id = %d", $product_id));
                    $product_name = ($product && !empty($product->name)) ? $product->name : 'Unknown Product';
                    $title = 'Edit Product: ' . $product_name;
                } else {
                    $title = 'Edit Product';
                }
                break;
        }
    }

    /**
     * Fix admin page titles for hidden submenu pages
     */
    public function fix_admin_page_titles($admin_title, $page_title) {
        global $title;

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initialization timing check not form processing
        if (!isset($_GET['page'])) {
            return $admin_title;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initialization timing check not form processing
        switch ($_GET['page']) {
            case 'ggmc-add-product':
                $title = 'Add Product';
                return 'Add Product ' . $admin_title;

            case 'ggmc-edit-product':
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initialization timing check not form processing
                if (isset($_GET['id'])) {
                    global $wpdb;
                    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initialization timing check not form processing
                    $product_id = intval($_GET['id']);
                    $products_table = $wpdb->prefix . 'ggmc_products';
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
                    $product = $wpdb->get_row($wpdb->prepare("SELECT name FROM $products_table WHERE id = %d", $product_id));
                    $product_name = ($product && !empty($product->name)) ? $product->name : 'Unknown Product';
                    $title = 'Edit Product: ' . $product_name;
                    return 'Edit Product: ' . $product_name . ' ' . $admin_title;
                } else {
                    $title = 'Edit Product';
                    return 'Edit Product ' . $admin_title;
                }
                break;
        }

        return $admin_title;
    }
    
    /**
     * Settings page implementation with tabs
     */
    public function settings_page() {
        // Set proper page title for WordPress
        global $title;
        $title = 'Goose Commerce Settings';

        // Get current tab - sanitize and whitelist for security
        // Use roles system to determine allowed tabs if custom roles are enabled
        if (class_exists('GGM_Commerce_Roles') && GGM_Commerce_Roles::is_enabled()) {
            $allowed_tabs = GGM_Commerce_Roles::get_allowed_settings_tabs();
        } else {
            // Default behavior - admins see all tabs
            $allowed_tabs = ['business', 'tax', 'shipping', 'currency', 'catalog', 'email', 'pages', 'widget-controls', 'address-settings', 'ai-integration', 'payment', 'subscriptions', 'checkout-fields', 'premium-components', 'google-merchant', 'transaction-export', 'legal'];

            // Test Data and User Roles tabs are admin-only
            if (current_user_can('manage_options')) {
                $allowed_tabs[] = 'test-data';
                $allowed_tabs[] = 'user-roles';
            }
        }

        $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'business';

        // Ensure user can access this tab
        if (!in_array($active_tab, $allowed_tabs, true)) {
            // Find first allowed tab
            $active_tab = !empty($allowed_tabs) ? $allowed_tabs[0] : 'business';
        }
        ?>
        <div class="wrap">
            <?php self::page_title( 'Goose Commerce Settings' ); ?>

            <?php
            // Define tab groups for sidebar navigation
            $tab_groups = [
                'Store' => [
                    'business'  => 'Business',
                    'tax'       => 'Tax',
                    'shipping'  => 'Shipping',
                    'currency'  => 'Units &amp; Currency',
                ],
                'Content' => [
                    'email'           => 'Email',
                    'pages'           => 'Pages',
                    'widget-controls' => 'Widget Controls',
                    'legal'           => 'Legal / Compliance',
                ],
                'Features' => [
                    'address-settings' => 'Address Settings',
                    'ai-integration'   => 'AI Integration',
                    'checkout-fields'  => 'Checkout Fields',
                    'payment'          => 'Payment',
                    'subscriptions'    => 'Subscriptions',
                ],
                'Integrations' => [
                    'premium-components' => 'Premium Components',
                    'google-merchant'    => 'Google Merchant',
                    'transaction-export' => 'Transaction Export',
                ],
                'Advanced' => [
                    'test-data'  => 'Test Data',
                    'user-roles' => 'User Roles',
                ],
            ];
            ?>

            <!-- Settings Layout: Sidebar + Content -->
            <div class="ggmc-settings-wrap">
                <nav class="ggmc-settings-sidebar">
                    <?php foreach ( $tab_groups as $group_label => $group_tabs ) :
                        // Filter to only allowed tabs in this group
                        $visible_tabs = array_intersect_key( $group_tabs, array_flip( $allowed_tabs ) );
                        if ( empty( $visible_tabs ) ) continue;
                    ?>
                        <div class="ggmc-settings-nav-group">
                            <h3><?php echo esc_html( $group_label ); ?></h3>
                            <?php foreach ( $visible_tabs as $tab_slug => $tab_label ) : ?>
                                <a href="?page=ggmc-settings&tab=<?php echo esc_attr( $tab_slug ); ?>"
                                   class="ggmc-settings-nav-item <?php echo $active_tab === $tab_slug ? 'active' : ''; ?>">
                                    <?php echo esc_html( $tab_label ); ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endforeach; ?>
                </nav>

                <div class="ggmc-settings-content">

            <?php if ($active_tab == 'business') : ?>
                <!-- Business Settings Tab -->
                <div class="card">
                    <form method="post" action="options.php">
                        <?php
                        settings_fields('ggm_commerce_business_group');
                        do_settings_sections('ggmc-business-settings');
                        submit_button();
                        ?>
                    </form>
                </div>

                <!-- Data Cleanup Settings -->
                <div class="card" style="margin-top: 20px; border-left: 4px solid #dc3232;">
                    <h2 style="display: flex; align-items: center; gap: 8px;">
                        <span class="dashicons dashicons-trash" style="color: #dc3232;"></span>
                        <?php esc_html_e( 'Data Cleanup on Plugin Removal', 'ggm-commerce' ); ?>
                    </h2>
                    <p class="description"><?php esc_html_e( 'Choose what happens to your data when this plugin is deleted from WordPress.', 'ggm-commerce' ); ?></p>

                    <form method="post" action="options.php">
                        <?php settings_fields( 'ggm_commerce_cleanup_group' ); ?>
                        <?php $cleanup_setting = get_option( 'ggm_commerce_cleanup_on_uninstall', 'keep' ); ?>

                        <table class="form-table">
                            <tr>
                                <th scope="row"><?php esc_html_e( 'When plugin is deleted', 'ggm-commerce' ); ?></th>
                                <td>
                                    <fieldset>
                                        <label style="display: block; margin-bottom: 15px; padding: 12px; background: #e6f4f3; border: 1px solid #c3d8e6; border-radius: 4px;">
                                            <input type="radio" name="ggm_commerce_cleanup_on_uninstall" value="keep" <?php checked( $cleanup_setting, 'keep' ); ?>>
                                            <strong><?php esc_html_e( 'Keep all data', 'ggm-commerce' ); ?></strong>
                                            <span style="color: #0F766E; font-size: 11px; margin-left: 8px;"><?php esc_html_e( '(Recommended)', 'ggm-commerce' ); ?></span>
                                            <p class="description" style="margin: 8px 0 0 24px;">
                                                <?php esc_html_e( 'Your products, orders, customers, and all settings will remain in the database. This is useful if you plan to reinstall the plugin later or are temporarily deactivating it.', 'ggm-commerce' ); ?>
                                            </p>
                                        </label>

                                        <label style="display: block; padding: 12px; background: #fcf0f1; border: 1px solid #d63638; border-radius: 4px;">
                                            <input type="radio" name="ggm_commerce_cleanup_on_uninstall" value="remove" <?php checked( $cleanup_setting, 'remove' ); ?>>
                                            <strong style="color: #d63638;"><?php esc_html_e( 'Remove all data', 'ggm-commerce' ); ?></strong>
                                            <p class="description" style="margin: 8px 0 0 24px; color: #8a2424;">
                                                <span class="dashicons dashicons-warning" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                                <strong><?php esc_html_e( 'WARNING:', 'ggm-commerce' ); ?></strong>
                                                <?php esc_html_e( 'All products, orders, customers, settings, and database tables will be PERMANENTLY DELETED when the plugin is removed from WordPress. This action cannot be undone.', 'ggm-commerce' ); ?>
                                            </p>
                                        </label>
                                    </fieldset>
                                </td>
                            </tr>
                        </table>
                        <?php submit_button( __( 'Save Cleanup Setting', 'ggm-commerce' ) ); ?>
                    </form>
                </div>

            <?php elseif ($active_tab == 'tax') : ?>
                <!-- Tax Settings Tab -->
                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <div class="card">
                    <form method="post" action="options.php">
                        <?php
                        settings_fields('ggm_commerce_tax_group');
                        do_settings_sections('ggmc-tax-settings');
                        submit_button();
                        ?>
                    </form>
                </div>

                <!-- Tax Rates Management -->
                <div class="card" style="margin-top: 20px;">
                    <h2>Tax Rates</h2>
                    <p class="description">Manage your tax rates. Each product can be assigned a specific tax rate. The default rate is used for new products.</p>

                    <?php
                    $tax = ggm_commerce_tax();
                    $tax_rates = $tax->get_all_tax_rates();
                    $tax_label = $tax->get_label();
                    ?>

                    <table class="wp-list-table widefat fixed striped" id="tax-rates-table">
                        <thead>
                            <tr>
                                <th style="width: 35%;">Name</th>
                                <th style="width: 20%;">Rate (%)</th>
                                <th style="width: 15%;">Default</th>
                                <th style="width: 30%;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($tax_rates)) : ?>
                                <?php foreach ($tax_rates as $rate) : ?>
                                <tr data-rate-id="<?php echo esc_attr($rate->id); ?>">
                                    <td>
                                        <input type="text" class="rate-name" value="<?php echo esc_attr($rate->name); ?>" style="width: 100%;">
                                    </td>
                                    <td>
                                        <input type="number" class="rate-percentage" value="<?php echo esc_attr($rate->rate); ?>" step="0.01" min="0" max="100" style="width: 100px;">
                                    </td>
                                    <td>
                                        <input type="radio" name="default_rate" class="rate-default" value="<?php echo esc_attr($rate->id); ?>" <?php checked($rate->is_default, 1); ?>>
                                    </td>
                                    <td>
                                        <button type="button" class="button button-small save-rate">Save</button>
                                        <?php if (!$rate->is_default) : ?>
                                        <button type="button" class="button button-small button-link-delete delete-rate">Delete</button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else : ?>
                                <tr>
                                    <td colspan="4">No tax rates found. Add one below.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>

                    <h3 style="margin-top: 20px;">Add New Tax Rate</h3>
                    <table class="form-table">
                        <tr>
                            <th><label for="new_rate_name">Name</label></th>
                            <td>
                                <input type="text" id="new_rate_name" placeholder="e.g., Reduced Rate" style="width: 200px;">
                            </td>
                        </tr>
                        <tr>
                            <th><label for="new_rate_percentage">Rate (%)</label></th>
                            <td>
                                <input type="number" id="new_rate_percentage" placeholder="5.00" step="0.01" min="0" max="100" style="width: 100px;">
                            </td>
                        </tr>
                        <tr>
                            <th><label for="new_rate_description">Description</label></th>
                            <td>
                                <input type="text" id="new_rate_description" placeholder="Optional description" style="width: 300px;">
                            </td>
                        </tr>
                    </table>
                    <p>
                        <button type="button" class="button button-primary" id="add-tax-rate">Add Tax Rate</button>
                    </p>

                    <div id="tax-rate-status" style="margin-top: 10px;"></div>
                </div>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>Understanding Tax Settings</h4>
                        <ul>
                            <li><strong>Tax Display:</strong> Choose whether to show prices including or excluding tax on the frontend.</li>
                            <li><strong>Tax Label:</strong> The text shown next to tax amounts (e.g., "VAT", "GST", "Tax").</li>
                            <li><strong>Tax Rates:</strong> Create multiple tax rates for different product types (standard, reduced, zero-rated).</li>
                        </ul>

                        <h4>How Tax Rates Work</h4>
                        <ul>
                            <li>The <strong>default rate</strong> is automatically applied to new products.</li>
                            <li>You can assign a different tax rate to individual products when editing them.</li>
                            <li>Deleting a tax rate will cause affected products to fall back to the default rate.</li>
                        </ul>

                        <h4>Common Tax Rates</h4>
                        <div class="ggmc-help-table">
                            <table>
                                <tr><td><strong>UK VAT</strong></td><td>20% / 5% / 0%</td></tr>
                                <tr><td><strong>EU VAT</strong></td><td>17-27%</td></tr>
                                <tr><td><strong>US Sales Tax</strong></td><td>0-10%</td></tr>
                                <tr><td><strong>Australia GST</strong></td><td>10%</td></tr>
                            </table>
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->


                <script>
                jQuery(document).ready(function($) {
                    var nonce = '<?php echo esc_js(wp_create_nonce('ggm_commerce_tax_rate_nonce')); ?>';
                    var statusDiv = $('#tax-rate-status');

                    // Save rate
                    $(document).on('click', '.save-rate', function() {
                        var row = $(this).closest('tr');
                        var rateId = row.data('rate-id');
                        var name = row.find('.rate-name').val();
                        var rate = row.find('.rate-percentage').val();
                        var isDefault = row.find('.rate-default').is(':checked') ? 1 : 0;
                        var button = $(this);

                        button.prop('disabled', true).text('Saving...');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_update_tax_rate',
                                nonce: nonce,
                                rate_id: rateId,
                                name: name,
                                rate: rate,
                                is_default: isDefault
                            },
                            success: function(response) {
                                if (response.success) {
                                    statusDiv.html('<div class="notice notice-success inline"><p>' + response.data.message + '</p></div>');
                                    if (isDefault) {
                                        // Uncheck other defaults visually
                                        $('input.rate-default').not(row.find('.rate-default')).prop('checked', false);
                                    }
                                } else {
                                    statusDiv.html('<div class="notice notice-error inline"><p>' + response.data.message + '</p></div>');
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error inline"><p>Failed to save. Please try again.</p></div>');
                            },
                            complete: function() {
                                button.prop('disabled', false).text('Save');
                            }
                        });
                    });

                    // Delete rate
                    $(document).on('click', '.delete-rate', function() {
                        if (!confirm('Are you sure you want to delete this tax rate? Products using it will fall back to the default rate.')) {
                            return;
                        }

                        var row = $(this).closest('tr');
                        var rateId = row.data('rate-id');
                        var button = $(this);

                        button.prop('disabled', true).text('Deleting...');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_delete_tax_rate',
                                nonce: nonce,
                                rate_id: rateId
                            },
                            success: function(response) {
                                if (response.success) {
                                    row.fadeOut(300, function() { $(this).remove(); });
                                    statusDiv.html('<div class="notice notice-success inline"><p>' + response.data.message + '</p></div>');
                                } else {
                                    statusDiv.html('<div class="notice notice-error inline"><p>' + response.data.message + '</p></div>');
                                    button.prop('disabled', false).text('Delete');
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error inline"><p>Failed to delete. Please try again.</p></div>');
                                button.prop('disabled', false).text('Delete');
                            }
                        });
                    });

                    // Add new rate
                    $('#add-tax-rate').on('click', function() {
                        var name = $('#new_rate_name').val().trim();
                        var rate = $('#new_rate_percentage').val();
                        var description = $('#new_rate_description').val().trim();
                        var button = $(this);

                        if (!name) {
                            statusDiv.html('<div class="notice notice-error inline"><p>Please enter a name for the tax rate.</p></div>');
                            return;
                        }

                        if (!rate || isNaN(rate)) {
                            statusDiv.html('<div class="notice notice-error inline"><p>Please enter a valid rate percentage.</p></div>');
                            return;
                        }

                        button.prop('disabled', true).text('Adding...');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_add_tax_rate',
                                nonce: nonce,
                                name: name,
                                rate: rate,
                                description: description
                            },
                            success: function(response) {
                                if (response.success) {
                                    statusDiv.html('<div class="notice notice-success inline"><p>' + response.data.message + '</p></div>');
                                    // Reload page to show new rate
                                    location.reload();
                                } else {
                                    statusDiv.html('<div class="notice notice-error inline"><p>' + response.data.message + '</p></div>');
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error inline"><p>Failed to add. Please try again.</p></div>');
                            },
                            complete: function() {
                                button.prop('disabled', false).text('Add Tax Rate');
                            }
                        });
                    });
                });
                </script>

            <?php elseif ($active_tab == 'shipping') : ?>
                <!-- Shipping Settings Tab -->
                <?php
                // Check if shipping premium feature is activated
                $shipping_premium_active = false;
                if (function_exists('ggm_commerce_license')) {
                    $license = ggm_commerce_license();
                    $shipping_premium_active = $license->is_widget_activated('shipping');
                }
                ?>
                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <!-- Basic Shipping Settings (always visible) -->
                <?php if (!$shipping_premium_active) : ?>
                <div class="card">
                    <form method="post" action="options.php">
                        <?php
                        settings_fields('ggm_commerce_basic_shipping_group');
                        do_settings_sections('ggmc-basic-shipping-settings');
                        submit_button();
                        ?>
                    </form>
                </div>
                <?php endif; ?>

                <!-- Premium Shipping Settings -->
                <div class="card" <?php echo !$shipping_premium_active ? 'style="margin-top: 20px;"' : ''; ?>>
                    <form method="post" action="options.php">
                        <?php
                        settings_fields('ggm_commerce_shipping_group');
                        do_settings_sections('ggmc-shipping-settings');
                        if ($shipping_premium_active) {
                            submit_button();
                        }
                        ?>
                    </form>
                </div>

                <?php if ($shipping_premium_active) : ?>
                <!-- Shipping Zones Management -->
                <div class="card" style="margin-top: 20px;">
                    <h2>Shipping Zones</h2>
                    <p class="description">Create zones for different geographic regions. Each zone can have multiple shipping methods with their own rates.</p>

                    <?php
                    $shipping = ggm_commerce_shipping();
                    $zones = $shipping->get_all_zones(false);
                    $shipping_label = $shipping->get_label();

                    // Handle zone actions
                    if (isset($_POST['ggmc_shipping_action']) && check_admin_referer('ggmc_shipping_zones')) {
                        $action = sanitize_text_field(wp_unslash($_POST['ggmc_shipping_action']));

                        if ($action === 'create_zone') {
                            $zone_data = [
                                'name' => isset($_POST['zone_name']) ? sanitize_text_field(wp_unslash($_POST['zone_name'])) : '',
                                'description' => isset($_POST['zone_description']) ? sanitize_textarea_field(wp_unslash($_POST['zone_description'])) : '',
                                'countries' => isset($_POST['zone_countries']) ? array_map('sanitize_text_field', wp_unslash($_POST['zone_countries'])) : [],
                                'is_default' => isset($_POST['zone_is_default']) ? 1 : 0,
                                'status' => 'active',
                            ];
                            $result = $shipping->create_zone($zone_data);
                            if ($result) {
                                echo '<div class="notice notice-success inline"><p>Shipping zone created successfully.</p></div>';
                                $zones = $shipping->get_all_zones(false);
                            } else {
                                echo '<div class="notice notice-error inline"><p>Failed to create shipping zone.</p></div>';
                            }
                        } elseif ($action === 'delete_zone') {
                            $zone_id = isset($_POST['zone_id']) ? intval(wp_unslash($_POST['zone_id'])) : 0;
                            if ($zone_id > 0) {
                                $result = $shipping->delete_zone($zone_id);
                                if ($result) {
                                    echo '<div class="notice notice-success inline"><p>Shipping zone deleted.</p></div>';
                                    $zones = $shipping->get_all_zones(false);
                                }
                            }
                        } elseif ($action === 'create_method') {
                            $zone_id = isset($_POST['zone_id']) ? intval(wp_unslash($_POST['zone_id'])) : 0;
                            $method_data = [
                                'name' => isset($_POST['method_name']) ? sanitize_text_field(wp_unslash($_POST['method_name'])) : '',
                                'method_type' => isset($_POST['method_type']) ? sanitize_text_field(wp_unslash($_POST['method_type'])) : 'flat_rate',
                                'cost' => isset($_POST['method_cost']) ? floatval(wp_unslash($_POST['method_cost'])) : 0,
                                'free_threshold' => isset($_POST['method_free_threshold']) ? floatval(wp_unslash($_POST['method_free_threshold'])) : null,
                                'is_taxable' => isset($_POST['method_is_taxable']) ? 1 : 0,
                                'status' => 'active',
                            ];
                            if ($zone_id > 0) {
                                $result = $shipping->create_method($zone_id, $method_data);
                                if ($result) {
                                    echo '<div class="notice notice-success inline"><p>Shipping method added.</p></div>';
                                    $zones = $shipping->get_all_zones(false);
                                }
                            }
                        } elseif ($action === 'delete_method') {
                            $method_id = isset($_POST['method_id']) ? intval(wp_unslash($_POST['method_id'])) : 0;
                            if ($method_id > 0) {
                                $result = $shipping->delete_method($method_id);
                                if ($result) {
                                    echo '<div class="notice notice-success inline"><p>Shipping method deleted.</p></div>';
                                    $zones = $shipping->get_all_zones(false);
                                }
                            }
                        } elseif ($action === 'update_method') {
                            $method_id = isset($_POST['method_id']) ? intval(wp_unslash($_POST['method_id'])) : 0;
                            $method_data = [
                                'name' => isset($_POST['method_name']) ? sanitize_text_field(wp_unslash($_POST['method_name'])) : '',
                                'cost' => isset($_POST['method_cost']) ? floatval(wp_unslash($_POST['method_cost'])) : 0,
                                'free_threshold' => isset($_POST['method_free_threshold']) ? floatval(wp_unslash($_POST['method_free_threshold'])) : null,
                                'is_taxable' => isset($_POST['method_is_taxable']) ? 1 : 0,
                                'status' => isset($_POST['method_status']) ? sanitize_text_field(wp_unslash($_POST['method_status'])) : 'active',
                            ];
                            if ($method_id > 0) {
                                $result = $shipping->update_method($method_id, $method_data);
                                if ($result) {
                                    echo '<div class="notice notice-success inline"><p>Shipping method updated.</p></div>';
                                    $zones = $shipping->get_all_zones(false);
                                }
                            }
                        }
                    }

                    $countries = ggm_commerce_get_countries();
                    $currency_options = get_option('ggm_commerce_currency_options', array());
                    $currency_symbol = isset($currency_options['symbol']) ? $currency_options['symbol'] : '£';
                    ?>

                    <!-- Zones List -->
                    <div id="shipping-zones-list">
                        <?php if (!empty($zones)) : ?>
                            <?php foreach ($zones as $zone) : ?>
                                <div class="ggmc-shipping-zone" style="border: 1px solid #ddd; border-radius: 4px; margin-bottom: 15px; background: #fff;">
                                    <div class="zone-header" style="padding: 15px; background: #f9f9f9; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;">
                                        <div>
                                            <strong style="font-size: 14px;"><?php echo esc_html($zone->name); ?></strong>
                                            <?php if ($zone->is_default) : ?>
                                                <span class="ggmc-badge" style="background: #0F766E; color: white; padding: 2px 8px; border-radius: 3px; font-size: 11px; margin-left: 10px;">Default</span>
                                            <?php endif; ?>
                                            <?php if ($zone->status !== 'active') : ?>
                                                <span class="ggmc-badge" style="background: #999; color: white; padding: 2px 8px; border-radius: 3px; font-size: 11px; margin-left: 5px;">Inactive</span>
                                            <?php endif; ?>
                                            <?php
                                            $zone_countries = is_array($zone->countries) ? $zone->countries : (json_decode($zone->countries, true) ?: []);
                                            if (!empty($zone_countries)) :
                                                $country_names = array_map(function($code) use ($countries) {
                                                    return isset($countries[$code]) ? $countries[$code] : $code;
                                                }, array_slice($zone_countries, 0, 3));
                                                $more = count($zone_countries) - 3;
                                            ?>
                                                <span class="description" style="margin-left: 10px;"><?php echo esc_html(implode(', ', $country_names)); ?><?php echo $more > 0 ? esc_html(' +' . $more . ' more') : ''; ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <form method="post" style="display:inline;" onsubmit="return confirm('Delete this zone and all its methods?');">
                                            <?php wp_nonce_field('ggmc_shipping_zones'); ?>
                                            <input type="hidden" name="ggmc_shipping_action" value="delete_zone">
                                            <input type="hidden" name="zone_id" value="<?php echo esc_attr($zone->id); ?>">
                                            <button type="submit" class="button button-small button-link-delete">Delete Zone</button>
                                        </form>
                                    </div>

                                    <div class="zone-methods" style="padding: 15px;">
                                        <?php
                                        $methods = $shipping->get_zone_methods($zone->id, false);
                                        ?>
                                        <table class="wp-list-table widefat fixed striped" style="margin-bottom: 15px;">
                                            <thead>
                                                <tr>
                                                    <th style="width: 25%;">Method Name</th>
                                                    <th style="width: 15%;">Type</th>
                                                    <th style="width: 15%;">Cost</th>
                                                    <th style="width: 15%;">Free Over</th>
                                                    <th style="width: 10%;">Taxable</th>
                                                    <th style="width: 10%;">Status</th>
                                                    <th style="width: 10%;">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (!empty($methods)) : ?>
                                                    <?php foreach ($methods as $method) : ?>
                                                    <tr>
                                                        <td><strong><?php echo esc_html($method->name); ?></strong></td>
                                                        <td>
                                                            <?php
                                                            $type_labels = [
                                                                'flat_rate' => 'Flat Rate',
                                                                'free_shipping' => 'Free Shipping',
                                                                'weight_based' => 'Weight Based',
                                                                'carrier_api' => 'Carrier API',
                                                            ];
                                                            echo esc_html($type_labels[$method->method_type] ?? $method->method_type);
                                                            ?>
                                                        </td>
                                                        <td><?php echo esc_html($method->method_type === 'free_shipping' ? '—' : $currency_symbol . number_format((float)$method->cost, 2)); ?></td>
                                                        <td><?php echo $method->free_threshold > 0 ? esc_html($currency_symbol . number_format((float)$method->free_threshold, 2)) : '—'; ?></td>
                                                        <td><?php echo $method->is_taxable ? 'Yes' : 'No'; ?></td>
                                                        <td><span style="color: <?php echo $method->status === 'active' ? '#46b450' : '#999'; ?>;"><?php echo esc_html(ucfirst($method->status)); ?></span></td>
                                                        <td>
                                                            <button type="button" class="button button-small ggmc-edit-method-btn"
                                                                data-method-id="<?php echo esc_attr($method->id); ?>"
                                                                data-method-name="<?php echo esc_attr($method->name); ?>"
                                                                data-method-type="<?php echo esc_attr($method->method_type); ?>"
                                                                data-method-cost="<?php echo esc_attr($method->cost); ?>"
                                                                data-method-free-threshold="<?php echo esc_attr($method->free_threshold); ?>"
                                                                data-method-is-taxable="<?php echo esc_attr($method->is_taxable); ?>"
                                                                data-method-status="<?php echo esc_attr($method->status); ?>">Edit</button>
                                                            <form method="post" style="display:inline;" onsubmit="return confirm('Delete this shipping method?');">
                                                                <?php wp_nonce_field('ggmc_shipping_zones'); ?>
                                                                <input type="hidden" name="ggmc_shipping_action" value="delete_method">
                                                                <input type="hidden" name="method_id" value="<?php echo esc_attr($method->id); ?>">
                                                                <button type="submit" class="button button-small button-link-delete">Delete</button>
                                                            </form>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else : ?>
                                                    <tr>
                                                        <td colspan="7" style="text-align: center; color: #666;">No shipping methods. Add one below.</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>

                                        <!-- Add Method Form -->
                                        <form method="post" class="ggmc-add-method-form" style="background: #f9f9f9; padding: 15px; border-radius: 4px;">
                                            <?php wp_nonce_field('ggmc_shipping_zones'); ?>
                                            <input type="hidden" name="ggmc_shipping_action" value="create_method">
                                            <input type="hidden" name="zone_id" value="<?php echo esc_attr($zone->id); ?>">

                                            <div style="display: flex; gap: 10px; flex-wrap: wrap; align-items: flex-end;">
                                                <div>
                                                    <label style="display: block; margin-bottom: 3px; font-weight: 500;">Method Name</label>
                                                    <input type="text" name="method_name" required placeholder="e.g. Standard Delivery" style="width: 180px;">
                                                </div>
                                                <div>
                                                    <label style="display: block; margin-bottom: 3px; font-weight: 500;">Type</label>
                                                    <select name="method_type" style="width: 140px;">
                                                        <option value="flat_rate">Flat Rate</option>
                                                        <option value="free_shipping">Free Shipping</option>
                                                        <option value="weight_based">Weight Based</option>
                                                    </select>
                                                </div>
                                                <div>
                                                    <label style="display: block; margin-bottom: 3px; font-weight: 500;">Cost</label>
                                                    <input type="number" name="method_cost" step="0.01" min="0" placeholder="0.00" style="width: 100px;">
                                                </div>
                                                <div>
                                                    <label style="display: block; margin-bottom: 3px; font-weight: 500;">Free Over</label>
                                                    <input type="number" name="method_free_threshold" step="0.01" min="0" placeholder="Optional" style="width: 100px;">
                                                </div>
                                                <div>
                                                    <label style="display: block; margin-bottom: 3px;">
                                                        <input type="checkbox" name="method_is_taxable" value="1"> Taxable
                                                    </label>
                                                </div>
                                                <div>
                                                    <button type="submit" class="button button-primary">Add Method</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php else : ?>
                            <p style="text-align: center; color: #666; padding: 20px;">No shipping zones defined. Create your first zone below.</p>
                        <?php endif; ?>
                    </div>

                    <!-- Add Zone Form -->
                    <div class="ggmc-add-zone-form" style="margin-top: 20px; padding: 20px; background: #f9f9f9; border-radius: 4px;">
                        <h3 style="margin-top: 0;">Add New Shipping Zone</h3>
                        <form method="post">
                            <?php wp_nonce_field('ggmc_shipping_zones'); ?>
                            <input type="hidden" name="ggmc_shipping_action" value="create_zone">

                            <table class="form-table">
                                <tr>
                                    <th scope="row"><label for="zone_name">Zone Name</label></th>
                                    <td>
                                        <input type="text" name="zone_name" id="zone_name" class="regular-text" required placeholder="e.g. United Kingdom, Europe, Rest of World">
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label for="zone_description">Description</label></th>
                                    <td>
                                        <textarea name="zone_description" id="zone_description" rows="2" class="large-text" placeholder="Optional description"></textarea>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row"><label>Countries</label></th>
                                    <td>
                                        <select name="zone_countries[]" multiple style="width: 100%; max-width: 400px; height: 200px;">
                                            <?php foreach ($countries as $code => $name) : ?>
                                                <option value="<?php echo esc_attr($code); ?>"><?php echo esc_html($name); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">Hold Ctrl/Cmd to select multiple countries. Leave empty to match all countries not covered by other zones.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">Default Zone</th>
                                    <td>
                                        <label>
                                            <input type="checkbox" name="zone_is_default" value="1">
                                            Set as default zone (used when no other zones match)
                                        </label>
                                    </td>
                                </tr>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary">Create Shipping Zone</button>
                            </p>
                        </form>
                    </div>

                    <!-- Edit Method Modal -->
                    <div id="ggmc-edit-method-modal" class="ggmc-modal" style="display: none;">
                        <div class="ggmc-modal-backdrop"></div>
                        <div class="ggmc-modal-content" style="max-width: 500px;">
                            <div class="ggmc-modal-header">
                                <h3 style="margin: 0;">Edit Shipping Method</h3>
                                <button type="button" class="ggmc-modal-close">&times;</button>
                            </div>
                            <form method="post" id="ggmc-edit-method-form">
                                <?php wp_nonce_field('ggmc_shipping_zones'); ?>
                                <input type="hidden" name="ggmc_shipping_action" value="update_method">
                                <input type="hidden" name="method_id" id="edit-method-id" value="">

                                <div class="ggmc-modal-body">
                                    <table class="form-table" style="margin: 0;">
                                        <tr>
                                            <th scope="row"><label for="edit-method-name">Method Name</label></th>
                                            <td><input type="text" name="method_name" id="edit-method-name" class="regular-text" required></td>
                                        </tr>
                                        <tr>
                                            <th scope="row"><label>Type</label></th>
                                            <td>
                                                <span id="edit-method-type-display" style="font-weight: 500;"></span>
                                                <p class="description">Method type cannot be changed after creation.</p>
                                            </td>
                                        </tr>
                                        <tr id="edit-cost-row">
                                            <th scope="row"><label for="edit-method-cost">Cost (<?php echo esc_html($currency_symbol); ?>)</label></th>
                                            <td><input type="number" name="method_cost" id="edit-method-cost" step="0.01" min="0" class="small-text"></td>
                                        </tr>
                                        <tr>
                                            <th scope="row"><label for="edit-method-free-threshold">Free Over (<?php echo esc_html($currency_symbol); ?>)</label></th>
                                            <td>
                                                <input type="number" name="method_free_threshold" id="edit-method-free-threshold" step="0.01" min="0" class="small-text">
                                                <p class="description">Orders over this amount get free shipping. Leave empty to disable.</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Taxable</th>
                                            <td>
                                                <label>
                                                    <input type="checkbox" name="method_is_taxable" id="edit-method-is-taxable" value="1">
                                                    Include shipping in tax calculations
                                                </label>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row"><label for="edit-method-status">Status</label></th>
                                            <td>
                                                <select name="method_status" id="edit-method-status">
                                                    <option value="active">Active</option>
                                                    <option value="inactive">Inactive</option>
                                                </select>
                                            </td>
                                        </tr>
                                    </table>
                                </div>

                                <div class="ggmc-modal-footer">
                                    <button type="button" class="button ggmc-modal-cancel">Cancel</button>
                                    <button type="submit" class="button button-primary">Save Changes</button>
                                </div>
                            </form>
                        </div>
                    </div>


                    <script>
                    jQuery(document).ready(function($) {
                        var $modal = $('#ggmc-edit-method-modal');
                        var typeLabels = {
                            'flat_rate': 'Flat Rate',
                            'free_shipping': 'Free Shipping',
                            'weight_based': 'Weight Based',
                            'carrier_api': 'Carrier API'
                        };

                        // Open modal when Edit button clicked
                        $('.ggmc-edit-method-btn').on('click', function() {
                            var $btn = $(this);
                            var methodType = $btn.data('method-type');

                            // Populate form
                            $('#edit-method-id').val($btn.data('method-id'));
                            $('#edit-method-name').val($btn.data('method-name'));
                            $('#edit-method-type-display').text(typeLabels[methodType] || methodType);
                            $('#edit-method-cost').val($btn.data('method-cost') || '');
                            $('#edit-method-free-threshold').val($btn.data('method-free-threshold') || '');
                            $('#edit-method-is-taxable').prop('checked', $btn.data('method-is-taxable') == 1);
                            $('#edit-method-status').val($btn.data('method-status'));

                            // Hide cost field for free shipping methods
                            if (methodType === 'free_shipping') {
                                $('#edit-cost-row').hide();
                            } else {
                                $('#edit-cost-row').show();
                            }

                            $modal.fadeIn(200);
                        });

                        // Close modal
                        function closeModal() {
                            $modal.fadeOut(200);
                        }

                        $('.ggmc-modal-close, .ggmc-modal-cancel, .ggmc-modal-backdrop').on('click', closeModal);

                        // Close on Escape key
                        $(document).on('keydown', function(e) {
                            if (e.key === 'Escape' && $modal.is(':visible')) {
                                closeModal();
                            }
                        });

                        // Prevent backdrop click from closing when clicking modal content
                        $('.ggmc-modal-content').on('click', function(e) {
                            e.stopPropagation();
                        });
                    });
                    </script>
                </div>
                <?php endif; ?>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>Basic Shipping</h4>
                        <ul>
                            <li><strong>Flat Rate:</strong> Single shipping cost for all orders</li>
                            <li><strong>Free Threshold:</strong> Orders over this amount get free shipping</li>
                            <li>Basic shipping is always available</li>
                        </ul>

                        <?php if ($shipping_premium_active) : ?>
                        <h4>Shipping Zones (Premium)</h4>
                        <ul>
                            <li><strong>Zone:</strong> A geographic region (country, state, postcode range)</li>
                            <li><strong>Method:</strong> Shipping option within a zone (Standard, Express, etc.)</li>
                            <li><strong>Priority:</strong> More specific zones match first (UK before Europe)</li>
                            <li><strong>Default Zone:</strong> Catches all addresses not matched elsewhere</li>
                        </ul>

                        <h4>Method Types</h4>
                        <ul>
                            <li><strong>Flat Rate:</strong> Fixed cost regardless of order</li>
                            <li><strong>Free Shipping:</strong> No cost (or free over threshold)</li>
                            <li><strong>Weight Based:</strong> Cost varies by total weight</li>
                        </ul>

                        <h4>Tips</h4>
                        <ul>
                            <li>Create specific zones first (UK), then broader zones (Europe, World)</li>
                            <li>Use "Free Over" to encourage larger orders</li>
                            <li>Enable taxable for methods if shipping should include tax</li>
                        </ul>
                        <?php else : ?>
                        <div class="ggmc-help-tip">
                            <span class="dashicons dashicons-lock"></span>
                            <strong>Want more?</strong> Activate the "Advanced Shipping" premium widget for shipping zones, weight-based rates, and multiple methods.
                        </div>
                        <?php endif; ?>
                    </div>
                </div><!-- .ggmc-settings-layout -->

            <?php elseif ($active_tab == 'currency') : ?>
                <!-- Units & Currency Settings Tab -->
                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <div class="card">
                    <form method="post" action="options.php">
                        <?php
                        settings_fields('ggm_commerce_currency_group');
                        do_settings_sections('ggmc-currency-settings');
                        submit_button();
                        ?>
                    </form>
                </div>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>Currency Settings</h4>
                        <ul>
                            <li><strong>Currency Code:</strong> 3-letter ISO code (EUR, USD, GBP)</li>
                            <li><strong>Currency Symbol:</strong> Symbol displayed with prices (€, $, £)</li>
                            <li><strong>Symbol Position:</strong> Before or after the amount</li>
                            <li><strong>Decimal Places:</strong> Number of decimals (typically 2)</li>
                        </ul>

                        <h4>Number Formatting</h4>
                        <ul>
                            <li><strong>Thousand Separator:</strong> e.g., 1,000 or 1.000</li>
                            <li><strong>Decimal Separator:</strong> e.g., 10.99 or 10,99</li>
                        </ul>

                        <h4>Common Formats</h4>
                        <div class="ggmc-help-table">
                            <table>
                                <tr><td><strong>US/UK</strong></td><td>$1,234.56</td></tr>
                                <tr><td><strong>Europe</strong></td><td>1.234,56 €</td></tr>
                                <tr><td><strong>Switzerland</strong></td><td>CHF 1'234.56</td></tr>
                            </table>
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->

            <?php elseif ($active_tab == 'email') : ?>
                <!-- Email Settings Tab -->
                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <div class="card">
                    <h2><?php esc_html_e( 'Email Sender Settings', 'ggm-commerce' ); ?></h2>
                    <form method="post" action="options.php">
                        <?php
                        settings_fields('ggm_commerce_email_group');
                        do_settings_sections('ggmc-email-settings');
                        submit_button();
                        ?>
                    </form>
                </div>

                <!-- Email Templates Management -->
                <div class="card" style="margin-top: 20px;">
                    <?php
                    if ( function_exists( 'ggm_commerce_email_admin' ) ) {
                        ggm_commerce_email_admin()->render_email_templates_ui();
                    }
                    ?>
                </div>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>Email Sender Settings</h4>
                        <ul>
                            <li><strong>From Name:</strong> Sender name shown in emails</li>
                            <li><strong>From Email:</strong> Reply-to address for customers</li>
                            <li><strong>Admin Email:</strong> Where order alerts are sent</li>
                        </ul>

                        <h4>Email Templates</h4>
                        <ul>
                            <li><strong>Enable/Disable:</strong> Toggle each email type on or off</li>
                            <li><strong>Configure:</strong> Customize subject, heading, and content</li>
                            <li><strong>Placeholders:</strong> Use {order_number}, {customer_name}, etc.</li>
                            <li><strong>Preview:</strong> See how your email will look</li>
                            <li><strong>Test:</strong> Send a test email to verify delivery</li>
                        </ul>

                        <div class="ggmc-help-tip">
                            <span class="dashicons dashicons-lightbulb"></span>
                            <strong>Tip:</strong> Use an SMTP plugin (WP Mail SMTP, FluentSMTP) for better email deliverability.
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->

            <?php elseif ($active_tab == 'pages') : ?>
                <!-- Pages Tab -->
                <?php
                // Handle page recreation
                if (isset($_POST['ggmc_recreate_pages']) && check_admin_referer('ggmc_pages_settings', 'ggmc_pages_nonce')) {
                    GGM_Commerce_Page_Builder::create_default_pages();
                    echo '<div class="notice notice-success"><p>Missing pages and templates have been recreated!</p></div>';
                }

                // Handle convert pages to current builder
                if (isset($_POST['ggmc_convert_pages']) && check_admin_referer('ggmc_pages_settings', 'ggmc_pages_nonce')) {
                    if ( GGM_Commerce_Page_Builder::is_elementor_active() ) {
                        GGM_Commerce_Page_Builder::convert_pages_to_elementor();
                        echo '<div class="notice notice-success"><p>All pages have been converted to Elementor layouts.</p></div>';
                    } else {
                        GGM_Commerce_Page_Builder::convert_pages_to_blocks();
                        echo '<div class="notice notice-success"><p>All pages have been converted to Gutenberg blocks.</p></div>';
                    }
                }

                // Handle OpenGraph settings save
                if (isset($_POST['ggmc_save_opengraph']) && check_admin_referer('ggmc_pages_settings', 'ggmc_pages_nonce')) {
                    $opengraph_enabled = isset($_POST['opengraph_enabled']) ? 1 : 0;
                    update_option('ggm_commerce_opengraph_enabled', $opengraph_enabled);
                    echo '<div class="notice notice-success"><p>OpenGraph settings saved!</p></div>';
                }

                // Handle save pages
                if (isset($_POST['ggmc_save_pages']) && check_admin_referer('ggmc_pages_settings', 'ggmc_pages_nonce')) {
                    update_option('ggm_commerce_shop_page_id', isset($_POST['shop_page']) ? intval(wp_unslash($_POST['shop_page'])) : 0);
                    update_option('ggm_commerce_cart_page_id', isset($_POST['cart_page']) ? intval(wp_unslash($_POST['cart_page'])) : 0);
                    update_option('ggm_commerce_checkout_page_id', isset($_POST['checkout_page']) ? intval(wp_unslash($_POST['checkout_page'])) : 0);
                    update_option('ggm_commerce_account_page_id', isset($_POST['account_page']) ? intval(wp_unslash($_POST['account_page'])) : 0);
                    update_option('ggm_commerce_product_details_page_id', isset($_POST['product_details_page']) ? intval(wp_unslash($_POST['product_details_page'])) : 0);
                    update_option('ggm_commerce_category_archive_page_id', isset($_POST['category_archive_page']) ? intval(wp_unslash($_POST['category_archive_page'])) : 0);
                    update_option('ggm_commerce_tag_archive_page_id', isset($_POST['tag_archive_page']) ? intval(wp_unslash($_POST['tag_archive_page'])) : 0);
                    update_option('ggm_commerce_wishlist_page_id', isset($_POST['wishlist_page']) ? intval(wp_unslash($_POST['wishlist_page'])) : 0);
                    update_option('ggm_commerce_comparison_page_id', isset($_POST['comparison_page']) ? intval(wp_unslash($_POST['comparison_page'])) : 0);
                    update_option('ggm_commerce_thank_you_page_id', isset($_POST['thank_you_page']) ? intval(wp_unslash($_POST['thank_you_page'])) : 0);
                    // Flush rewrite rules when taxonomy pages change
                    flush_rewrite_rules();
                    echo '<div class="notice notice-success"><p>Page settings saved!</p></div>';
                }

                $shop_page_id = get_option('ggm_commerce_shop_page_id');
                $cart_page_id = get_option('ggm_commerce_cart_page_id');
                $checkout_page_id = get_option('ggm_commerce_checkout_page_id');
                $account_page_id = get_option('ggm_commerce_account_page_id');
                $product_details_page_id = get_option('ggm_commerce_product_details_page_id');
                $category_archive_page_id = get_option('ggm_commerce_category_archive_page_id');
                $tag_archive_page_id = get_option('ggm_commerce_tag_archive_page_id');
                $wishlist_page_id = get_option('ggm_commerce_wishlist_page_id');
                $comparison_page_id = get_option('ggm_commerce_comparison_page_id');
                $thank_you_page_id = get_option('ggm_commerce_thank_you_page_id');
                $quick_view_popup_id = get_option('ggm_commerce_quick_view_popup_id');

                // Check if Quick View is activated
                $quick_view_activated = class_exists('GGM_Commerce_Quick_View') && \GGM_Commerce_Quick_View::is_activated();

                // Get all pages
                $pages = get_pages();

                // Check which pages/templates are missing
                $missing_items = [];
                if (!$shop_page_id || get_post_status($shop_page_id) !== 'publish') $missing_items[] = 'Shop page';
                if (!$cart_page_id || get_post_status($cart_page_id) !== 'publish') $missing_items[] = 'Cart page';
                if (!$checkout_page_id || get_post_status($checkout_page_id) !== 'publish') $missing_items[] = 'Checkout page';
                if (!$account_page_id || get_post_status($account_page_id) !== 'publish') $missing_items[] = 'My Account page';
                if (!$product_details_page_id || get_post_status($product_details_page_id) !== 'publish') $missing_items[] = 'Product Details page';
                if (!$category_archive_page_id || get_post_status($category_archive_page_id) !== 'publish') $missing_items[] = 'Category Archive page';
                if (!$tag_archive_page_id || get_post_status($tag_archive_page_id) !== 'publish') $missing_items[] = 'Tag Archive page';
                if (!$wishlist_page_id || get_post_status($wishlist_page_id) !== 'publish') $missing_items[] = 'Wishlist page';
                if (!$thank_you_page_id || get_post_status($thank_you_page_id) !== 'publish') $missing_items[] = 'Thank You page';
                // Only check Quick View popup if feature is activated
                if ($quick_view_activated && (!$quick_view_popup_id || get_post_status($quick_view_popup_id) !== 'publish')) $missing_items[] = 'Quick View Popup Template';

                // Get OpenGraph setting
                $opengraph_enabled = get_option('ggm_commerce_opengraph_enabled', 0);
                ?>

                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <!-- Page Recreation Section -->
                <div class="card">
                    <h2>Page Status</h2>
                    <?php if (!empty($missing_items)) : ?>
                        <div class="notice notice-warning inline" style="margin: 10px 0;">
                            <p><strong>Missing items detected:</strong></p>
                            <ul style="margin: 5px 0 10px 20px;">
                                <?php foreach ($missing_items as $item) : ?>
                                    <li>• <?php echo esc_html($item); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <form method="post" style="margin-top: 10px;">
                            <?php wp_nonce_field('ggmc_pages_settings', 'ggmc_pages_nonce'); ?>
                            <p class="description">Click the button below to recreate any missing pages and templates.</p>
                            <p class="submit" style="margin-top: 10px;">
                                <input type="submit" name="ggmc_recreate_pages" class="button button-secondary" value="Recreate Missing Pages &amp; Templates">
                            </p>
                        </form>
                    <?php else : ?>
                        <p style="color: #00a32a;"><strong>✓ All pages and templates are properly configured.</strong></p>
                    <?php endif; ?>
                </div>

                <div class="card" style="margin-top: 20px;">
                    <h2>Page Builder</h2>
                    <?php
                    $current_builder = GGM_Commerce_Page_Builder::is_elementor_active() ? 'Elementor' : 'Gutenberg (Block Editor)';
                    // Check what builder the pages are currently using
                    $sample_page_id = get_option('ggm_commerce_shop_page_id');
                    $page_builder_meta = $sample_page_id ? get_post_meta($sample_page_id, '_ggmc_page_builder', true) : '';
                    $pages_using = $page_builder_meta === 'elementor' ? 'Elementor' : ($page_builder_meta === 'blocks' ? 'Gutenberg' : 'Unknown');
                    ?>
                    <p>Active page builder: <strong><?php echo esc_html($current_builder); ?></strong></p>
                    <?php if ($page_builder_meta && (($page_builder_meta === 'elementor' && !GGM_Commerce_Page_Builder::is_elementor_active()) || ($page_builder_meta === 'blocks' && GGM_Commerce_Page_Builder::is_elementor_active()))) : ?>
                        <div class="notice notice-warning inline" style="margin: 10px 0;">
                            <p>Your pages are currently using <strong><?php echo esc_html($pages_using); ?></strong> but the active builder is <strong><?php echo esc_html($current_builder); ?></strong>. Convert your pages to match.</p>
                        </div>
                    <?php endif; ?>
                    <form method="post" style="margin-top: 10px;">
                        <?php wp_nonce_field('ggmc_pages_settings', 'ggmc_pages_nonce'); ?>
                        <p class="submit" style="margin-top: 0;">
                            <input type="submit" name="ggmc_convert_pages" class="button button-primary" value="Convert Pages to <?php echo esc_attr($current_builder); ?>">
                        </p>
                    </form>
                </div>

                <div class="card" style="margin-top: 20px;">
                    <h2>Page Assignments</h2>
                    <p>Configure which pages are used for core Goose Commerce functionality.</p>

                    <form method="post">
                        <?php wp_nonce_field('ggmc_pages_settings', 'ggmc_pages_nonce'); ?>

                        <table class="form-table">
                            <tr>
                                <th scope="row">Shop Page</th>
                                <td>
                                    <select name="shop_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($shop_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($shop_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($shop_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($shop_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Cart Page</th>
                                <td>
                                    <select name="cart_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($cart_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($cart_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($cart_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($cart_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Checkout Page</th>
                                <td>
                                    <select name="checkout_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($checkout_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($checkout_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($checkout_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($checkout_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">My Account Page</th>
                                <td>
                                    <select name="account_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($account_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($account_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($account_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($account_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Product Details Page</th>
                                <td>
                                    <select name="product_details_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($product_details_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($product_details_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($product_details_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($product_details_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                    <p class="description" style="margin-top: 5px;">
                                        This page is used as the single product view. Edit the page in Elementor to customize the layout.
                                    </p>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Category Archive Page</th>
                                <td>
                                    <select name="category_archive_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($category_archive_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($category_archive_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($category_archive_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($category_archive_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                    <p class="description" style="margin-top: 5px;">
                                        Displays products filtered by category. URLs: <code>/product-category/{category-slug}/</code>
                                    </p>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Tag Archive Page</th>
                                <td>
                                    <select name="tag_archive_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($tag_archive_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($tag_archive_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($tag_archive_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($tag_archive_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                    <p class="description" style="margin-top: 5px;">
                                        Displays products filtered by tag. URLs: <code>/product-tag/{tag-slug}/</code>
                                    </p>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Wishlist Page</th>
                                <td>
                                    <select name="wishlist_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($wishlist_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($wishlist_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($wishlist_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($wishlist_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                    <p class="description" style="margin-top: 5px;">
                                        Displays saved wishlist items. Requires Wishlist premium feature activation.
                                    </p>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Comparison Page</th>
                                <td>
                                    <select name="comparison_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($comparison_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($comparison_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($comparison_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($comparison_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                    <p class="description" style="margin-top: 5px;">
                                        Side-by-side product comparison page. Requires Product Comparison premium feature activation.
                                    </p>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Thank You Page</th>
                                <td>
                                    <select name="thank_you_page" class="regular-text">
                                        <option value="">-- Select Page --</option>
                                        <?php foreach ($pages as $page) : ?>
                                            <option value="<?php echo esc_attr($page->ID); ?>" <?php selected($thank_you_page_id, $page->ID); ?>>
                                                <?php echo esc_html($page->post_title); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if ($thank_you_page_id) : ?>
                                        <p class="description">
                                            Current: <a href="<?php echo esc_url(get_permalink($thank_you_page_id)); ?>" target="_blank">
                                                <?php echo esc_html(get_the_title($thank_you_page_id)); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>
                                    <p class="description" style="margin-top: 5px;">
                                        Order confirmation page shown after successful checkout. Ideal for analytics tracking.
                                    </p>
                                </td>
                            </tr>
                        </table>

                        <p class="submit">
                            <input type="submit" name="ggmc_save_pages" class="button button-primary" value="Save Page Settings">
                        </p>
                    </form>
                </div>

                <?php if ($quick_view_activated) : ?>
                <div class="card" style="margin-top: 20px;">
                    <h2>Premium Templates & Popups</h2>
                    <p>Configure templates and popups for premium features.</p>

                    <table class="form-table">
                        <tr>
                            <th scope="row">Quick View Popup</th>
                            <td>
                                <?php if ($quick_view_popup_id && get_post_status($quick_view_popup_id) === 'publish') : ?>
                                    <p style="color: #00a32a; margin-bottom: 10px;">
                                        <strong>✓ Template configured:</strong>
                                        <a href="<?php echo esc_url(admin_url('post.php?post=' . $quick_view_popup_id . '&action=elementor')); ?>" target="_blank">
                                            <?php echo esc_html(get_the_title($quick_view_popup_id)); ?>
                                        </a>
                                    </p>
                                    <a href="<?php echo esc_url(admin_url('post.php?post=' . $quick_view_popup_id . '&action=elementor')); ?>" class="button button-secondary" target="_blank">
                                        Edit Quick View Template
                                    </a>
                                <?php else : ?>
                                    <p style="color: #d63638; margin-bottom: 10px;">
                                        <strong>⚠️ Template missing.</strong> Use "Recreate Missing Pages & Templates" above to create it.
                                    </p>
                                <?php endif; ?>
                                <p class="description" style="margin-top: 10px;">
                                    This Elementor template is displayed when customers click the Quick View button on products.
                                    Design it using Goose Commerce product widgets (Name, Price, Gallery, Add to Cart, etc.).
                                </p>
                            </td>
                        </tr>
                    </table>
                </div>
                <?php endif; ?>

                <div class="card" style="margin-top: 20px;">
                    <h2>Product URL Format</h2>
                    <p>Choose how product detail page URLs are formatted.</p>

                    <?php
                    // Handle URL format save
                    if (isset($_POST['ggmc_save_url_format']) && check_admin_referer('ggmc_pages_settings', 'ggmc_pages_nonce')) {
                        $url_format = isset($_POST['ggmc_url_format']) ? sanitize_text_field(wp_unslash($_POST['ggmc_url_format'])) : 'slug';
                        update_option('ggm_commerce_url_format', $url_format);
                        if ($url_format === 'slug') {
                            flush_rewrite_rules();
                        }
                        echo '<div class="notice notice-success inline" style="margin: 10px 0;"><p>URL format saved successfully.</p></div>';
                    }

                    // Handle flush rewrite rules
                    if (isset($_POST['ggmc_flush_rewrite_rules']) && check_admin_referer('ggmc_pages_settings', 'ggmc_pages_nonce')) {
                        flush_rewrite_rules();
                        echo '<div class="notice notice-success inline" style="margin: 10px 0;"><p>Rewrite rules flushed successfully. Friendly URLs should now work.</p></div>';
                    }

                    $current_url_format = get_option('ggm_commerce_url_format', 'slug');
                    ?>

                    <form method="post" style="margin-top: 10px;">
                        <?php wp_nonce_field('ggmc_pages_settings', 'ggmc_pages_nonce'); ?>
                        <table class="form-table">
                            <tr>
                                <th scope="row">URL Format</th>
                                <td>
                                    <fieldset>
                                        <label style="display: block; margin-bottom: 10px;">
                                            <input type="radio" name="ggmc_url_format" value="slug" <?php checked($current_url_format, 'slug'); ?>>
                                            <strong>Friendly URLs (Slug)</strong><br>
                                            <code style="margin-left: 24px;">/product-details/iphone-15-pro-max/</code>
                                            <span class="description" style="display: block; margin-left: 24px; color: #666;">SEO-friendly URLs using the product slug. Recommended.</span>
                                        </label>
                                        <label style="display: block;">
                                            <input type="radio" name="ggmc_url_format" value="id" <?php checked($current_url_format, 'id'); ?>>
                                            <strong>ID-based URLs</strong><br>
                                            <code style="margin-left: 24px;">/product-details/?id=148</code>
                                            <span class="description" style="display: block; margin-left: 24px; color: #666;">Traditional query string format using the product ID.</span>
                                        </label>
                                    </fieldset>
                                </td>
                            </tr>
                        </table>
                        <p class="submit" style="margin: 0;">
                            <input type="submit" name="ggmc_save_url_format" class="button button-primary" value="Save URL Format">
                        </p>
                    </form>

                    <hr style="margin: 20px 0;">

                    <h3>Troubleshooting Friendly URLs</h3>

                    <?php
                    global $wpdb;
                    // Handle regenerate slugs
                    if (isset($_POST['ggmc_regenerate_slugs']) && check_admin_referer('ggmc_pages_settings', 'ggmc_pages_nonce')) {
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $products_without_slugs = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}ggmc_products WHERE slug = '' OR slug IS NULL");
                        $count = 0;
                        if (!empty($products_without_slugs)) {
                            foreach ($products_without_slugs as $product) {
                                $slug = GGM_Commerce_Database::generate_unique_slug($product->name, $product->id);
                                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                $wpdb->update(
                                    "{$wpdb->prefix}ggmc_products",
                                    ['slug' => $slug],
                                    ['id' => $product->id]
                                );
                                $count++;
                            }
                        }
                        if ($count > 0) {
                            echo '<div class="notice notice-success inline" style="margin: 10px 0;"><p>Generated slugs for ' . esc_html($count) . ' product(s).</p></div>';
                        } else {
                            echo '<div class="notice notice-info inline" style="margin: 10px 0;"><p>All products already have slugs.</p></div>';
                        }
                    }

                    // Check how many products are missing slugs
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $missing_slugs = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_products WHERE slug = '' OR slug IS NULL");
                    ?>

                    <?php if ($missing_slugs > 0) : ?>
                    <div class="notice notice-warning inline" style="margin: 10px 0;">
                        <p><strong><?php echo esc_html($missing_slugs); ?> product(s)</strong> are missing URL slugs. Friendly URLs won't work for these products until slugs are generated.</p>
                    </div>
                    <?php endif; ?>

                    <p>If products are showing ID-based URLs instead of friendly slugs, regenerate the slugs:</p>
                    <form method="post" style="margin-top: 10px;">
                        <?php wp_nonce_field('ggmc_pages_settings', 'ggmc_pages_nonce'); ?>
                        <p class="submit" style="margin: 0;">
                            <input type="submit" name="ggmc_regenerate_slugs" class="button button-secondary" value="Regenerate Missing Slugs">
                        </p>
                    </form>

                    <p style="margin-top: 15px;">If friendly URLs are still not working, try flushing the rewrite rules:</p>
                    <form method="post" style="margin-top: 10px;">
                        <?php wp_nonce_field('ggmc_pages_settings', 'ggmc_pages_nonce'); ?>
                        <p class="submit" style="margin: 0;">
                            <input type="submit" name="ggmc_flush_rewrite_rules" class="button button-secondary" value="Flush Rewrite Rules">
                        </p>
                    </form>
                    <p class="description" style="margin-top: 10px;">
                        <strong>Note:</strong> You may also need to visit <a href="<?php echo esc_url(admin_url('options-permalink.php')); ?>">Settings → Permalinks</a> and click "Save Changes" to refresh WordPress's URL routing.
                    </p>
                </div>

                <!-- OpenGraph Settings -->
                <div class="card" style="margin-top: 20px;">
                    <h2>OpenGraph Meta Tags</h2>
                    <p>Control whether Goose Commerce outputs OpenGraph meta tags for product pages and archives.</p>

                    <form method="post" style="margin-top: 15px;">
                        <?php wp_nonce_field('ggmc_pages_settings', 'ggmc_pages_nonce'); ?>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="opengraph_enabled">Enable OpenGraph Tags</label>
                                </th>
                                <td>
                                    <label class="ggmc-toggle-switch">
                                        <input type="checkbox" id="opengraph_enabled" name="opengraph_enabled" value="1" <?php checked($opengraph_enabled, 1); ?>>
                                        <span class="ggmc-toggle-slider"></span>
                                    </label>
                                    <p class="description" style="margin-top: 10px;">
                                        When enabled, Goose Commerce will output <code>og:title</code>, <code>og:description</code>, <code>og:image</code>, and <code>og:url</code> meta tags for product pages.
                                    </p>
                                </td>
                            </tr>
                        </table>
                        <p class="submit" style="margin: 0;">
                            <input type="submit" name="ggmc_save_opengraph" class="button button-primary" value="Save OpenGraph Settings">
                        </p>
                    </form>
                </div>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>Page Assignments</h4>
                        <p>Assign WordPress pages to handle core e-commerce functionality like the shop, cart, and checkout.</p>

                        <h4>URL Format</h4>
                        <ul>
                            <li><strong>Friendly URLs:</strong> SEO-optimized URLs using product slugs</li>
                            <li><strong>ID-based URLs:</strong> Traditional query parameter format</li>
                        </ul>

                        <h4>OpenGraph Tags</h4>
                        <p>OpenGraph meta tags control how your products appear when shared on social media platforms like Facebook, LinkedIn, and X (Twitter).</p>

                        <h4>When to Enable OpenGraph</h4>
                        <ul>
                            <li><strong>Enable</strong> if you're not using another SEO plugin (like Yoast, Rank Math, or All in One SEO) that already handles OpenGraph tags</li>
                            <li><strong>Disable</strong> if another plugin is managing your meta tags to avoid duplicate/conflicting tags</li>
                        </ul>

                        <h4>What Gets Output</h4>
                        <p>On product pages, Goose Commerce will output:</p>
                        <ul>
                            <li><code>og:title</code> - Product name</li>
                            <li><code>og:description</code> - Product description</li>
                            <li><code>og:image</code> - Product featured image</li>
                            <li><code>og:url</code> - Product page URL</li>
                            <li><code>og:type</code> - "product"</li>
                        </ul>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->

            <?php elseif ($active_tab == 'ai-integration') : ?>
                <!-- AI Integration Tab -->
                <?php
                global $wpdb;
                $auth_disabled = get_option('ggm_mcp_disable_auth', false);
                $site_url = get_site_url();
                $mcp_endpoint = rest_url('mcp/v1/mcp');
                $health_endpoint = rest_url('mcp/v1/health');

                // Load MCP auth class and get API keys
                require_once plugin_dir_path(__FILE__) . 'mcp/class-mcp-auth.php';
                $mcp_auth = new GGM_Commerce_MCP_Auth();
                $api_keys = $mcp_auth->get_all_api_keys();
                ?>

                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <div class="card">
                    <h2><?php esc_html_e('Model Context Protocol (MCP) Settings', 'ggm-commerce'); ?></h2>
                    <p><?php esc_html_e('Enable AI assistants like Claude to interact with your e-commerce store through the Model Context Protocol.', 'ggm-commerce'); ?></p>

                    <!-- Authentication Toggle -->
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="mcp-auth-toggle"><?php esc_html_e('MCP Authentication', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <label class="mcp-toggle-switch">
                                    <input type="checkbox" id="mcp-auth-toggle" <?php echo $auth_disabled ? '' : 'checked'; ?>>
                                    <span class="mcp-slider"></span>
                                </label>
                                <p class="description">
                                    <?php if (!$auth_disabled): ?>
                                        <span style="color: #00a32a;"><strong><?php esc_html_e('Enabled:', 'ggm-commerce'); ?></strong> <?php esc_html_e('Requests require API keys (recommended for security)', 'ggm-commerce'); ?></span>
                                    <?php else: ?>
                                        <span style="color: #d63638;"><strong><?php esc_html_e('Disabled:', 'ggm-commerce'); ?></strong> <?php esc_html_e('No authentication required - use only for local development!', 'ggm-commerce'); ?></span>
                                    <?php endif; ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('MCP Endpoint', 'ggm-commerce'); ?></th>
                            <td>
                                <code style="background: #f0f0f1; padding: 5px 10px; display: inline-block;"><?php echo esc_html($mcp_endpoint); ?></code>
                                <button type="button" class="button button-small" onclick="navigator.clipboard.writeText('<?php echo esc_js($mcp_endpoint); ?>'); this.textContent='Copied!'; setTimeout(() => this.textContent='Copy', 2000);"><?php esc_html_e('Copy', 'ggm-commerce'); ?></button>
                                <p class="description"><?php esc_html_e('Use this URL to connect AI assistants to your store', 'ggm-commerce'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Health Check', 'ggm-commerce'); ?></th>
                            <td>
                                <code style="background: #f0f0f1; padding: 5px 10px; display: inline-block;"><?php echo esc_html($health_endpoint); ?></code>
                                <a href="<?php echo esc_url($health_endpoint); ?>" target="_blank" class="button button-small"><?php esc_html_e('Test', 'ggm-commerce'); ?></a>
                            </td>
                        </tr>
                    </table>

                    <div id="mcp-status-message" style="margin: 15px 0;"></div>
                </div>

                <!-- Generate New API Key -->
                <div class="card" style="margin-top: 20px;">
                    <h2><?php esc_html_e('Generate New API Key', 'ggm-commerce'); ?></h2>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="mcp-key-name"><?php esc_html_e('API Key Name', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="mcp-key-name" class="regular-text" placeholder="<?php esc_attr_e('e.g., Claude Desktop, Production API', 'ggm-commerce'); ?>">
                                <p class="description"><?php esc_html_e('A descriptive name to identify this API key', 'ggm-commerce'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="mcp-key-expiration"><?php esc_html_e('Expiration', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <select id="mcp-key-expiration">
                                    <option value="30"><?php esc_html_e('30 days', 'ggm-commerce'); ?></option>
                                    <option value="90"><?php esc_html_e('90 days', 'ggm-commerce'); ?></option>
                                    <option value="365" selected><?php esc_html_e('1 year', 'ggm-commerce'); ?></option>
                                    <option value="730"><?php esc_html_e('2 years', 'ggm-commerce'); ?></option>
                                    <option value="0"><?php esc_html_e('Never expires', 'ggm-commerce'); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e('When this API key should expire', 'ggm-commerce'); ?></p>
                            </td>
                        </tr>
                    </table>

                    <p>
                        <button type="button" id="mcp-generate-key" class="button button-primary"><?php esc_html_e('Generate API Key', 'ggm-commerce'); ?></button>
                    </p>

                    <!-- New Key Display (hidden by default) -->
                    <div id="mcp-new-key-display" style="display: none; margin-top: 20px; padding: 20px; background: #d4edda; border: 1px solid #28a745; border-radius: 4px;">
                        <h3 style="margin-top: 0; color: #155724;"><?php esc_html_e('New API Key Generated!', 'ggm-commerce'); ?></h3>
                        <p style="color: #856404; background: #fff3cd; padding: 10px; border-radius: 4px; margin-bottom: 15px;">
                            <strong><?php esc_html_e('Important:', 'ggm-commerce'); ?></strong> <?php esc_html_e('Copy this key now - it will not be shown again!', 'ggm-commerce'); ?>
                            <br><span id="mcp-key-countdown" style="font-weight: 600;"></span>
                        </p>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <code id="mcp-new-key-value" style="flex: 1; background: #fff; padding: 10px; font-size: 14px; word-break: break-all;"></code>
                            <button type="button" class="button" id="mcp-copy-key-btn"><?php esc_html_e('Copy', 'ggm-commerce'); ?></button>
                        </div>
                    </div>

                    <div id="mcp-generate-status" style="margin-top: 15px;"></div>
                </div>

                <!-- Existing API Keys -->
                <div class="card" style="margin-top: 20px;">
                    <h2><?php esc_html_e('Active API Keys', 'ggm-commerce'); ?></h2>

                    <?php if (empty($api_keys)): ?>
                        <p><?php esc_html_e('No API keys have been generated yet.', 'ggm-commerce'); ?></p>
                    <?php else: ?>
                        <table class="wp-list-table widefat fixed striped" id="mcp-api-keys-table">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Name', 'ggm-commerce'); ?></th>
                                    <th><?php esc_html_e('Key Preview', 'ggm-commerce'); ?></th>
                                    <th><?php esc_html_e('Created', 'ggm-commerce'); ?></th>
                                    <th><?php esc_html_e('Expires', 'ggm-commerce'); ?></th>
                                    <th><?php esc_html_e('Status', 'ggm-commerce'); ?></th>
                                    <th><?php esc_html_e('Requests', 'ggm-commerce'); ?></th>
                                    <th><?php esc_html_e('Last Used', 'ggm-commerce'); ?></th>
                                    <th><?php esc_html_e('Actions', 'ggm-commerce'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($api_keys as $key_info): ?>
                                    <tr data-key-hash="<?php echo esc_attr($key_info['full_key_hash']); ?>">
                                        <td><strong><?php echo esc_html($key_info['name']); ?></strong></td>
                                        <td><code><?php echo esc_html($key_info['key_preview']); ?></code></td>
                                        <td><?php echo esc_html(gmdate('Y-m-d', $key_info['created'])); ?></td>
                                        <td>
                                            <?php
                                            if ($key_info['expires']) {
                                                $is_expired = time() > $key_info['expires'];
                                                $style = $is_expired ? 'color: #d63638;' : '';
                                                echo '<span style="' . esc_attr($style) . '">' . esc_html(gmdate('Y-m-d', $key_info['expires'])) . '</span>';
                                                if ($is_expired) {
                                                    echo ' <em>(' . esc_html__('Expired', 'ggm-commerce') . ')</em>';
                                                }
                                            } else {
                                                esc_html_e('Never', 'ggm-commerce');
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <span class="mcp-status-badge mcp-status-<?php echo esc_attr($key_info['status']); ?>">
                                                <?php echo esc_html(ucfirst($key_info['status'])); ?>
                                            </span>
                                        </td>
                                        <td><?php echo esc_html(number_format($key_info['request_count'])); ?></td>
                                        <td>
                                            <?php
                                            if ($key_info['last_used']) {
                                                echo esc_html(gmdate('Y-m-d H:i', $key_info['last_used']));
                                            } else {
                                                esc_html_e('Never', 'ggm-commerce');
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <button type="button" class="button button-small mcp-toggle-key-btn"
                                                    data-key-hash="<?php echo esc_attr($key_info['full_key_hash']); ?>"
                                                    data-current-status="<?php echo esc_attr($key_info['status']); ?>">
                                                <?php echo $key_info['status'] === 'active' ? esc_html__('Disable', 'ggm-commerce') : esc_html__('Enable', 'ggm-commerce'); ?>
                                            </button>
                                            <button type="button" class="button button-small button-link-delete mcp-revoke-key-btn"
                                                    data-key-hash="<?php echo esc_attr($key_info['full_key_hash']); ?>"
                                                    data-key-name="<?php echo esc_attr($key_info['name']); ?>">
                                                <?php esc_html_e('Revoke', 'ggm-commerce'); ?>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>

                <!-- Usage Information -->
                <div class="card" style="margin-top: 20px;">
                    <h2><?php esc_html_e('Available MCP Capabilities', 'ggm-commerce'); ?></h2>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                        <div>
                            <h3>📚 Resources (Read Data)</h3>
                            <ul style="list-style: none; padding: 0;">
                                <li>• Product catalog</li>
                                <li>• Order information</li>
                                <li>• Customer data</li>
                                <li>• Inventory status</li>
                            </ul>
                        </div>
                        <div>
                            <h3>🔧 Tools (Actions)</h3>
                            <ul style="list-style: none; padding: 0;">
                                <li>• Search products</li>
                                <li>• Manage cart</li>
                                <li>• Create orders</li>
                                <li>• Update inventory</li>
                            </ul>
                        </div>
                        <div>
                            <h3>💬 AI Prompts</h3>
                            <ul style="list-style: none; padding: 0;">
                                <li>• Product recommendations</li>
                                <li>• Order summaries</li>
                                <li>• Inventory alerts</li>
                                <li>• Customer service</li>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- Documentation -->
                <div class="card" style="margin-top: 20px;">
                    <h2><?php esc_html_e('Quick Start Guide', 'ggm-commerce'); ?></h2>
                    <div style="background: #f9f9f9; padding: 15px; border-left: 4px solid #0F766E;">
                        <h4 style="margin-top: 0;"><?php esc_html_e('For Local AI Development (No Authentication):', 'ggm-commerce'); ?></h4>
                        <ol style="margin: 10px 0;">
                            <li><?php esc_html_e('Toggle authentication OFF above', 'ggm-commerce'); ?></li>
                            <li><?php esc_html_e('Use the MCP endpoint URL with your local AI', 'ggm-commerce'); ?></li>
                            <li><?php esc_html_e('No API key needed!', 'ggm-commerce'); ?></li>
                        </ol>

                        <h4><?php esc_html_e('Example Request (No Auth):', 'ggm-commerce'); ?></h4>
                        <pre style="background: #fff; padding: 10px; border: 1px solid #ddd; overflow-x: auto;">curl -X POST <?php echo esc_html($mcp_endpoint); ?> \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"initialize","id":"1"}'</pre>
                    </div>

                    <div style="background: #f9f9f9; padding: 15px; border-left: 4px solid #00a32a; margin-top: 15px;">
                        <h4 style="margin-top: 0;"><?php esc_html_e('For Production (With Authentication):', 'ggm-commerce'); ?></h4>
                        <ol style="margin: 10px 0;">
                            <li><?php esc_html_e('Keep authentication ON (recommended)', 'ggm-commerce'); ?></li>
                            <li><?php esc_html_e('Generate an API key using the form above', 'ggm-commerce'); ?></li>
                            <li><?php esc_html_e('Copy and securely store the key', 'ggm-commerce'); ?></li>
                            <li><?php esc_html_e('Use the Bearer token in requests', 'ggm-commerce'); ?></li>
                        </ol>

                        <h4><?php esc_html_e('Example Request (With Auth):', 'ggm-commerce'); ?></h4>
                        <pre style="background: #fff; padding: 10px; border: 1px solid #ddd; overflow-x: auto;">curl -X POST <?php echo esc_html($mcp_endpoint); ?> \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"initialize","id":"1"}'</pre>
                    </div>
                </div>


                <script>
                jQuery(document).ready(function($) {
                    // MCP auth toggle
                    $('#mcp-auth-toggle').on('change', function() {
                        const isEnabled = $(this).is(':checked');
                        const statusDiv = $('#mcp-status-message');

                        if (!isEnabled) {
                            if (!confirm('⚠️ WARNING: Disabling authentication will allow ANYONE to access your store data via the MCP endpoint without an API key.\n\nThis should ONLY be used for local development with local AI assistants.\n\nAre you sure you want to disable authentication?')) {
                                $(this).prop('checked', true);
                                return;
                            }
                        }

                        statusDiv.html('<div class="notice notice-info inline"><p>Updating authentication setting...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_mcp_toggle_auth',
                                enable: isEnabled ? 'yes' : 'no',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_mcp_toggle_auth')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    const message = isEnabled
                                        ? '<div class="notice notice-success inline"><p><strong>✓ Authentication Enabled:</strong> MCP endpoint now requires API keys.</p></div>'
                                        : '<div class="notice notice-warning inline"><p><strong>⚠️ Authentication Disabled:</strong> MCP endpoint is now open (no API key required). Use only for local development!</p></div>';
                                    statusDiv.html(message);
                                    setTimeout(function() {
                                        window.location.reload();
                                    }, 2000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error inline"><p><strong>Error:</strong> Failed to update setting.</p></div>');
                                    $('#mcp-auth-toggle').prop('checked', !isEnabled);
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error inline"><p><strong>Error:</strong> Request failed. Please try again.</p></div>');
                                $('#mcp-auth-toggle').prop('checked', !isEnabled);
                            }
                        });
                    });

                    // Copy API Key button
                    $('#mcp-copy-key-btn').on('click', function() {
                        const keyValue = $('#mcp-new-key-value').text();
                        const btn = $(this);
                        navigator.clipboard.writeText(keyValue).then(function() {
                            btn.text('Copied!');
                            setTimeout(function() {
                                btn.text('Copy');
                            }, 2000);
                        });
                    });

                    // Generate API Key
                    $('#mcp-generate-key').on('click', function() {
                        const keyName = $('#mcp-key-name').val().trim();
                        const expiration = $('#mcp-key-expiration').val();
                        const statusDiv = $('#mcp-generate-status');
                        const newKeyDisplay = $('#mcp-new-key-display');
                        const btn = $(this);

                        if (!keyName) {
                            statusDiv.html('<div class="notice notice-error inline"><p>Please enter a name for the API key.</p></div>');
                            return;
                        }

                        btn.prop('disabled', true).text('Generating...');
                        statusDiv.html('<div class="notice notice-info inline"><p>Generating API key...</p></div>');
                        newKeyDisplay.hide();

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_mcp_generate_api_key',
                                key_name: keyName,
                                expires_in_days: expiration,
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_mcp_generate_key')); ?>'
                            },
                            success: function(response) {
                                btn.prop('disabled', false).text('Generate API Key');
                                if (response.success) {
                                    statusDiv.html('<div class="notice notice-success inline"><p>API key generated successfully!</p></div>');
                                    $('#mcp-new-key-value').text(response.data.api_key);
                                    newKeyDisplay.show();
                                    $('#mcp-key-name').val('');

                                    // Start countdown timer (30 seconds)
                                    let secondsLeft = 30;
                                    const countdownEl = $('#mcp-key-countdown');

                                    const updateCountdown = function() {
                                        if (secondsLeft > 0) {
                                            countdownEl.text('Page will refresh in ' + secondsLeft + ' second' + (secondsLeft !== 1 ? 's' : '') + '...');
                                            secondsLeft--;
                                        } else {
                                            window.location.reload();
                                        }
                                    };

                                    updateCountdown();
                                    window.mcpCountdownInterval = setInterval(updateCountdown, 1000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error inline"><p><strong>Error:</strong> ' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                }
                            },
                            error: function() {
                                btn.prop('disabled', false).text('Generate API Key');
                                statusDiv.html('<div class="notice notice-error inline"><p><strong>Error:</strong> Request failed. Please try again.</p></div>');
                            }
                        });
                    });

                    // Toggle API Key Status
                    $('.mcp-toggle-key-btn').on('click', function() {
                        const btn = $(this);
                        const keyHash = btn.data('key-hash');
                        const currentStatus = btn.data('current-status');
                        const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
                        const row = btn.closest('tr');

                        btn.prop('disabled', true);

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_mcp_toggle_api_key',
                                key_hash: keyHash,
                                new_status: newStatus,
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_mcp_toggle_key')); ?>'
                            },
                            success: function(response) {
                                btn.prop('disabled', false);
                                if (response.success) {
                                    btn.data('current-status', newStatus);
                                    btn.text(newStatus === 'active' ? 'Disable' : 'Enable');

                                    const badge = row.find('.mcp-status-badge');
                                    badge.removeClass('mcp-status-active mcp-status-inactive')
                                         .addClass('mcp-status-' + newStatus)
                                         .text(newStatus.charAt(0).toUpperCase() + newStatus.slice(1));
                                } else {
                                    alert('Error: ' + (response.data ? response.data.message : 'Unknown error'));
                                }
                            },
                            error: function() {
                                btn.prop('disabled', false);
                                alert('Request failed. Please try again.');
                            }
                        });
                    });

                    // Revoke API Key
                    $('.mcp-revoke-key-btn').on('click', function() {
                        const btn = $(this);
                        const keyHash = btn.data('key-hash');
                        const keyName = btn.data('key-name');
                        const row = btn.closest('tr');

                        if (!confirm('Are you sure you want to revoke the API key "' + keyName + '"?\n\nThis action cannot be undone.')) {
                            return;
                        }

                        btn.prop('disabled', true);

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_mcp_revoke_api_key',
                                key_hash: keyHash,
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_mcp_revoke_key')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    row.fadeOut(300, function() {
                                        $(this).remove();
                                        // Check if table is empty
                                        if ($('#mcp-api-keys-table tbody tr').length === 0) {
                                            window.location.reload();
                                        }
                                    });
                                } else {
                                    btn.prop('disabled', false);
                                    alert('Error: ' + (response.data ? response.data.message : 'Unknown error'));
                                }
                            },
                            error: function() {
                                btn.prop('disabled', false);
                                alert('Request failed. Please try again.');
                            }
                        });
                    });
                });
                </script>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>What is MCP?</h4>
                        <p>The Model Context Protocol allows AI assistants like Claude to interact with your store - managing products, orders, and more through natural conversations.</p>

                        <h4>Setup with Claude Desktop</h4>
                        <ol>
                            <li>Copy the MCP Endpoint URL</li>
                            <li>Add it as an MCP server in Claude</li>
                            <li>Configure authentication</li>
                            <li>Start chatting with your store!</li>
                        </ol>

                        <div class="ggmc-help-warning">
                            <span class="dashicons dashicons-warning"></span>
                            <strong>Important:</strong> Keep authentication enabled in production. Only disable for local development.
                        </div>

                        <div class="ggmc-help-links">
                            <h4>Quick Links</h4>
                            <ul>
                                <li><a href="https://claude.ai/download" target="_blank" rel="noopener"><span class="dashicons dashicons-external"></span> Download Claude Desktop</a></li>
                                <li><a href="https://modelcontextprotocol.io/docs" target="_blank" rel="noopener"><span class="dashicons dashicons-external"></span> MCP Documentation</a></li>
                            </ul>
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->

            <?php elseif ($active_tab == 'payment') : ?>
                <!-- Payment Settings Tab -->
                <?php
                $license = ggm_commerce_license();
                $stripe_activated = $license->is_widget_activated('stripe-gateway');
                $paypal_activated = $license->is_widget_activated('paypal-gateway');
                ?>

                <div class="ggmc-payment-layout">
                    <div class="ggmc-payment-settings">

                <!-- Security Best Practices Notice -->
                <div class="card" style="border-left: 4px solid #0F766E; margin-bottom: 20px;">
                    <h3 style="margin-top: 0;"><span class="dashicons dashicons-shield" style="margin-right: 8px;"></span>API Key Security</h3>
                    <p style="margin-bottom: 10px;">Your secret API keys are encrypted before storage and are never displayed in this form. Following <a href="https://docs.stripe.com/keys-best-practices" target="_blank" rel="noopener">Stripe's security best practices</a>:</p>
                    <ul style="margin: 0 0 10px 20px; list-style: disc;">
                        <li><strong>Keys are encrypted at rest</strong> using AES-256-CBC encryption</li>
                        <li><strong>Keys are never exposed</strong> in HTML source code or form values</li>
                        <li><strong>Rotate your keys regularly</strong> — create new keys periodically and update them here</li>
                        <li><strong>Use restricted keys</strong> when possible — create limited-scope keys in your payment provider dashboard</li>
                        <li><strong>Monitor your API logs</strong> — regularly check your Stripe/PayPal dashboards for unusual activity</li>
                    </ul>
                    <p style="margin: 0; font-size: 13px; color: #64748b;">
                        <span class="dashicons dashicons-info" style="font-size: 16px; width: 16px; height: 16px;"></span>
                        Never share your secret keys via email, chat, or support tickets. Your payment provider will never ask for them.
                    </p>
                </div>

                <?php if (!$stripe_activated && !$paypal_activated) : ?>
                    <!-- No Payment Gateways Activated -->
                    <div class="card">
                        <h2>Payment Gateways</h2>
                        <p>No payment gateways are currently activated.</p>
                        <p>To enable payment processing, go to the <a href="?page=ggmc-settings&tab=premium-components">Premium Components</a> tab and activate either <strong>Stripe Payment Gateway</strong> or <strong>PayPal Payment Gateway</strong>.</p>
                    </div>
                <?php else : ?>

                    <?php if ($stripe_activated) : ?>
                        <!-- Stripe Settings -->
                        <?php
                        $stripe_settings = get_option('ggm_commerce_gateway_stripe', array());
                        $stripe_enabled = isset($stripe_settings['enabled']) ? $stripe_settings['enabled'] : 'no';
                        $stripe_test_mode = isset($stripe_settings['test_mode']) ? $stripe_settings['test_mode'] : 'yes';
                        ?>
                        <div class="card" id="stripe-settings">
                            <h2><span class="dashicons dashicons-money-alt" style="margin-right: 8px;"></span>Stripe Payment Gateway</h2>
                            <form method="post" action="" id="stripe-settings-form">
                                <?php wp_nonce_field('ggm_commerce_stripe_settings', 'stripe_settings_nonce'); ?>
                                <input type="hidden" name="action" value="save_stripe_settings">

                                <table class="form-table">
                                    <tr>
                                        <th scope="row">Enable Stripe</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="stripe[enabled]" value="yes" <?php checked($stripe_enabled, 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable Stripe as a payment option at checkout.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Test Mode <button type="button" class="ggmc-info-btn" data-help="test-mode" title="Learn about Test Mode"><span class="dashicons dashicons-info-outline"></span></button></th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="stripe[test_mode]" value="yes" <?php checked($stripe_test_mode, 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable test mode to use Stripe test API keys.</p>
                                        </td>
                                    </tr>
                                </table>

                                <?php
                                // Check if secret keys are configured (for display purposes only)
                                $live_secret_configured = !empty($stripe_settings['live_secret_key']);
                                $test_secret_configured = !empty($stripe_settings['test_secret_key']);
                                $webhook_secret_configured = !empty($stripe_settings['webhook_secret']);
                                ?>

                                <h3>Live API Keys <button type="button" class="ggmc-info-btn" data-help="api-keys" title="Learn about API Keys"><span class="dashicons dashicons-info-outline"></span></button></h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row"><label for="stripe_live_publishable_key">Publishable Key</label></th>
                                        <td>
                                            <input type="text" id="stripe_live_publishable_key" name="stripe[live_publishable_key]"
                                                   value="<?php echo esc_attr($stripe_settings['live_publishable_key'] ?? ''); ?>"
                                                   class="regular-text" placeholder="pk_live_...">
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="stripe_live_secret_key">Secret Key</label></th>
                                        <td>
                                            <input type="password" id="stripe_live_secret_key" name="stripe[live_secret_key]"
                                                   value=""
                                                   class="regular-text" placeholder="<?php echo $live_secret_configured ? 'Key saved securely. Enter new key to replace.' : 'sk_live_...'; ?>">
                                            <?php if ($live_secret_configured) : ?>
                                                <span class="dashicons dashicons-yes-alt" style="color: #00a32a; margin-left: 5px;" title="Secret key is configured"></span>
                                            <?php endif; ?>
                                            <p class="description">
                                                <?php if ($live_secret_configured) : ?>
                                                    <strong>Key is saved.</strong> Leave blank to keep existing key, or enter a new key to replace it.
                                                <?php else : ?>
                                                    Enter your Stripe live secret key (starts with sk_live_).
                                                <?php endif; ?>
                                            </p>
                                        </td>
                                    </tr>
                                </table>

                                <h3>Test API Keys</h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row"><label for="stripe_test_publishable_key">Publishable Key</label></th>
                                        <td>
                                            <input type="text" id="stripe_test_publishable_key" name="stripe[test_publishable_key]"
                                                   value="<?php echo esc_attr($stripe_settings['test_publishable_key'] ?? ''); ?>"
                                                   class="regular-text" placeholder="pk_test_...">
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="stripe_test_secret_key">Secret Key</label></th>
                                        <td>
                                            <input type="password" id="stripe_test_secret_key" name="stripe[test_secret_key]"
                                                   value=""
                                                   class="regular-text" placeholder="<?php echo $test_secret_configured ? 'Key saved securely. Enter new key to replace.' : 'sk_test_...'; ?>">
                                            <?php if ($test_secret_configured) : ?>
                                                <span class="dashicons dashicons-yes-alt" style="color: #00a32a; margin-left: 5px;" title="Secret key is configured"></span>
                                            <?php endif; ?>
                                            <p class="description">
                                                <?php if ($test_secret_configured) : ?>
                                                    <strong>Key is saved.</strong> Leave blank to keep existing key, or enter a new key to replace it.
                                                <?php else : ?>
                                                    Enter your Stripe test secret key (starts with sk_test_).
                                                <?php endif; ?>
                                            </p>
                                        </td>
                                    </tr>
                                </table>

                                <!-- Test Mode Help Box -->
                                <div class="ggmc-info-box" style="background: #e6f4f3; border-left: 4px solid #0F766E; padding: 12px 16px; margin: 20px 0;">
                                    <h4 style="margin: 0 0 10px 0; color: #1E293B;">
                                        <span class="dashicons dashicons-info" style="color: #0F766E;"></span>
                                        Test Card Numbers
                                    </h4>
                                    <p style="margin: 0 0 10px 0; color: #50575e;">
                                        Use these test card numbers when testing Stripe in test mode:
                                    </p>
                                    <table style="margin: 0; border-collapse: collapse; font-size: 13px;">
                                        <tr>
                                            <td style="padding: 4px 15px 4px 0; color: #50575e;"><strong>Successful payment:</strong></td>
                                            <td><code style="background: #fff; padding: 2px 6px; border-radius: 3px;">4242 4242 4242 4242</code></td>
                                        </tr>
                                        <tr>
                                            <td style="padding: 4px 15px 4px 0; color: #50575e;"><strong>Requires authentication:</strong></td>
                                            <td><code style="background: #fff; padding: 2px 6px; border-radius: 3px;">4000 0025 0000 3155</code></td>
                                        </tr>
                                        <tr>
                                            <td style="padding: 4px 15px 4px 0; color: #50575e;"><strong>Declined card:</strong></td>
                                            <td><code style="background: #fff; padding: 2px 6px; border-radius: 3px;">4000 0000 0000 0002</code></td>
                                        </tr>
                                    </table>
                                    <p style="margin: 10px 0 0 0; color: #50575e; font-size: 12px;">
                                        Use any future expiry date, any 3-digit CVC, and any postal code.
                                        <a href="https://docs.stripe.com/testing#cards" target="_blank" rel="noopener">View all test cards</a>
                                    </p>
                                </div>

                                <h3>Webhook Configuration <button type="button" class="ggmc-info-btn" data-help="webhook" title="Learn about Webhooks"><span class="dashicons dashicons-info-outline"></span></button></h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row">Webhook URL</th>
                                        <td>
                                            <code style="background: #f0f0f1; padding: 5px 10px; display: inline-block;"><?php echo esc_html(rest_url('ggm-commerce/v1/webhooks/stripe')); ?></code>
                                            <button type="button" class="button button-small copy-url" data-url="<?php echo esc_attr(rest_url('ggm-commerce/v1/webhooks/stripe')); ?>">Copy</button>
                                            <p class="description">Add this URL in your <a href="https://dashboard.stripe.com/webhooks" target="_blank">Stripe Dashboard → Webhooks</a></p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="stripe_webhook_secret">Webhook Secret</label></th>
                                        <td>
                                            <input type="password" id="stripe_webhook_secret" name="stripe[webhook_secret]"
                                                   value=""
                                                   class="regular-text" placeholder="<?php echo $webhook_secret_configured ? 'Key saved securely. Enter new key to replace.' : 'whsec_...'; ?>">
                                            <?php if ($webhook_secret_configured) : ?>
                                                <span class="dashicons dashicons-yes-alt" style="color: #00a32a; margin-left: 5px;" title="Webhook secret is configured"></span>
                                            <?php endif; ?>
                                            <p class="description">
                                                <?php if ($webhook_secret_configured) : ?>
                                                    <strong>Key is saved.</strong> Leave blank to keep existing key, or enter a new key to replace it.
                                                <?php else : ?>
                                                    Get this from your Stripe webhook endpoint settings (starts with whsec_).
                                                <?php endif; ?>
                                            </p>
                                        </td>
                                    </tr>
                                </table>

                                <h3>Payment Methods <button type="button" class="ggmc-info-btn" data-help="payment-methods" title="Learn about Payment Methods"><span class="dashicons dashicons-info-outline"></span></button></h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row">Cards</th>
                                        <td>
                                            <label><input type="checkbox" checked disabled> Credit and Debit Cards</label>
                                            <p class="description">Card payments are always enabled.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Apple Pay</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="stripe[enable_apple_pay]" value="yes"
                                                    <?php checked($stripe_settings['enable_apple_pay'] ?? 'yes', 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable Apple Pay for supported devices.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Google Pay</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="stripe[enable_google_pay]" value="yes"
                                                    <?php checked($stripe_settings['enable_google_pay'] ?? 'yes', 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable Google Pay for supported devices.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Link</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="stripe[enable_link]" value="yes"
                                                    <?php checked($stripe_settings['enable_link'] ?? 'no', 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable Stripe Link for faster checkout with saved payment info.</p>
                                        </td>
                                    </tr>
                                </table>

                                <?php submit_button('Save Stripe Settings'); ?>
                            </form>
                        </div>
                    <?php endif; ?>

                    <?php if ($paypal_activated) : ?>
                        <!-- PayPal Settings -->
                        <?php
                        $paypal_settings = get_option('ggm_commerce_gateway_paypal', array());
                        $paypal_enabled = isset($paypal_settings['enabled']) ? $paypal_settings['enabled'] : 'no';
                        $paypal_test_mode = isset($paypal_settings['test_mode']) ? $paypal_settings['test_mode'] : 'yes';
                        ?>
                        <div class="card" style="margin-top: 20px;" id="paypal-settings">
                            <h2><span class="dashicons dashicons-money" style="margin-right: 8px;"></span>PayPal Payment Gateway</h2>
                            <form method="post" action="" id="paypal-settings-form">
                                <?php wp_nonce_field('ggm_commerce_paypal_settings', 'paypal_settings_nonce'); ?>
                                <input type="hidden" name="action" value="save_paypal_settings">

                                <table class="form-table">
                                    <tr>
                                        <th scope="row">Enable PayPal</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="paypal[enabled]" value="yes" <?php checked($paypal_enabled, 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable PayPal as a payment option at checkout.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Sandbox Mode <button type="button" class="ggmc-info-btn" data-help="test-mode" title="Learn about Sandbox Mode"><span class="dashicons dashicons-info-outline"></span></button></th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="paypal[test_mode]" value="yes" <?php checked($paypal_test_mode, 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable sandbox mode to use PayPal test credentials.</p>
                                        </td>
                                    </tr>
                                </table>

                                <?php
                                // Check if secret keys are configured (for display purposes only)
                                $paypal_live_secret_configured = !empty($paypal_settings['live_client_secret']);
                                $paypal_test_secret_configured = !empty($paypal_settings['test_client_secret']);
                                ?>

                                <h3>Live API Credentials <button type="button" class="ggmc-info-btn" data-help="paypal-credentials" title="Learn about PayPal Credentials"><span class="dashicons dashicons-info-outline"></span></button></h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row"><label for="paypal_live_client_id">Client ID</label></th>
                                        <td>
                                            <input type="text" id="paypal_live_client_id" name="paypal[live_client_id]"
                                                   value="<?php echo esc_attr($paypal_settings['live_client_id'] ?? ''); ?>"
                                                   class="regular-text">
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="paypal_live_client_secret">Client Secret</label></th>
                                        <td>
                                            <input type="password" id="paypal_live_client_secret" name="paypal[live_client_secret]"
                                                   value=""
                                                   class="regular-text" placeholder="<?php echo $paypal_live_secret_configured ? 'Key saved securely. Enter new key to replace.' : 'Enter client secret'; ?>">
                                            <?php if ($paypal_live_secret_configured) : ?>
                                                <span class="dashicons dashicons-yes-alt" style="color: #00a32a; margin-left: 5px;" title="Client secret is configured"></span>
                                            <?php endif; ?>
                                            <p class="description">
                                                <?php if ($paypal_live_secret_configured) : ?>
                                                    <strong>Key is saved.</strong> Leave blank to keep existing key, or enter a new key to replace it.
                                                <?php else : ?>
                                                    Enter your PayPal live client secret.
                                                <?php endif; ?>
                                            </p>
                                        </td>
                                    </tr>
                                </table>

                                <h3>Sandbox API Credentials</h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row"><label for="paypal_test_client_id">Client ID</label></th>
                                        <td>
                                            <input type="text" id="paypal_test_client_id" name="paypal[test_client_id]"
                                                   value="<?php echo esc_attr($paypal_settings['test_client_id'] ?? ''); ?>"
                                                   class="regular-text">
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="paypal_test_client_secret">Client Secret</label></th>
                                        <td>
                                            <input type="password" id="paypal_test_client_secret" name="paypal[test_client_secret]"
                                                   value=""
                                                   class="regular-text" placeholder="<?php echo $paypal_test_secret_configured ? 'Key saved securely. Enter new key to replace.' : 'Enter client secret'; ?>">
                                            <?php if ($paypal_test_secret_configured) : ?>
                                                <span class="dashicons dashicons-yes-alt" style="color: #00a32a; margin-left: 5px;" title="Client secret is configured"></span>
                                            <?php endif; ?>
                                            <p class="description">
                                                <?php if ($paypal_test_secret_configured) : ?>
                                                    <strong>Key is saved.</strong> Leave blank to keep existing key, or enter a new key to replace it.
                                                <?php else : ?>
                                                    Enter your PayPal sandbox client secret.
                                                <?php endif; ?>
                                            </p>
                                        </td>
                                    </tr>
                                </table>

                                <!-- Sandbox Testing Help Box -->
                                <div class="ggmc-info-box" style="background: #e6f4f3; border-left: 4px solid #0F766E; padding: 12px 16px; margin: 20px 0;">
                                    <h4 style="margin: 0 0 10px 0; color: #1E293B;">
                                        <span class="dashicons dashicons-info" style="color: #0F766E;"></span>
                                        Sandbox Testing Accounts
                                    </h4>
                                    <p style="margin: 0 0 10px 0; color: #50575e;">
                                        To test PayPal payments in sandbox mode, you need to create test buyer/seller accounts in the PayPal Developer Dashboard:
                                    </p>
                                    <ol style="margin: 0 0 15px 20px; color: #50575e;">
                                        <li>Go to <a href="https://developer.paypal.com/dashboard/accounts" target="_blank" rel="noopener">PayPal Developer Dashboard → Sandbox Accounts</a></li>
                                        <li>Create or use an existing "Personal" (buyer) test account</li>
                                        <li>Note the email and password for that test account</li>
                                        <li>Use these credentials in the PayPal popup during checkout testing</li>
                                    </ol>
                                    <p style="margin: 0; color: #50575e;">
                                        <strong>Default sandbox test credentials:</strong><br>
                                        <code style="background: #fff; padding: 2px 6px; border-radius: 3px;">sb-xxxxx@personal.example.com</code> (check your sandbox accounts for actual email)<br>
                                        Password is set when you create or view the sandbox account details.
                                    </p>
                                </div>

                                <h3>Webhook Configuration <button type="button" class="ggmc-info-btn" data-help="webhook" title="Learn about Webhooks"><span class="dashicons dashicons-info-outline"></span></button></h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row">Webhook URL</th>
                                        <td>
                                            <code style="background: #f0f0f1; padding: 5px 10px; display: inline-block;"><?php echo esc_html(rest_url('ggm-commerce/v1/webhooks/paypal')); ?></code>
                                            <button type="button" class="button button-small copy-url" data-url="<?php echo esc_attr(rest_url('ggm-commerce/v1/webhooks/paypal')); ?>">Copy</button>
                                            <p class="description">Add this URL in your <a href="https://developer.paypal.com/dashboard/applications" target="_blank">PayPal Developer Dashboard → Webhooks</a></p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="paypal_webhook_id">Webhook ID</label></th>
                                        <td>
                                            <input type="text" id="paypal_webhook_id" name="paypal[webhook_id]"
                                                   value="<?php echo esc_attr($paypal_settings['webhook_id'] ?? ''); ?>"
                                                   class="regular-text">
                                            <p class="description">Get this from your PayPal webhook configuration.</p>
                                        </td>
                                    </tr>
                                </table>

                                <h3>Payment Methods <button type="button" class="ggmc-info-btn" data-help="payment-methods" title="Learn about Payment Methods"><span class="dashicons dashicons-info-outline"></span></button></h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row">PayPal</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="paypal[enable_paypal]" value="yes"
                                                    <?php checked($paypal_settings['enable_paypal'] ?? 'yes', 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable standard PayPal payments.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Pay Later</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="paypal[enable_pay_later]" value="yes"
                                                    <?php checked($paypal_settings['enable_pay_later'] ?? 'no', 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable Pay Later / Buy Now Pay Later options.</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Venmo</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="paypal[enable_venmo]" value="yes"
                                                    <?php checked($paypal_settings['enable_venmo'] ?? 'no', 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable Venmo payments (US only).</p>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row">Cards via PayPal</th>
                                        <td>
                                            <label class="ggmc-toggle-switch">
                                                <input type="checkbox" name="paypal[enable_card]" value="yes"
                                                    <?php checked($paypal_settings['enable_card'] ?? 'yes', 'yes'); ?>>
                                                <span class="ggmc-slider"></span>
                                            </label>
                                            <p class="description">Enable card payments processed through PayPal.</p>
                                        </td>
                                    </tr>
                                </table>

                                <h3>Button Style <button type="button" class="ggmc-info-btn" data-help="button-style" title="Learn about Button Styles"><span class="dashicons dashicons-info-outline"></span></button></h3>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row"><label for="paypal_button_layout">Layout</label></th>
                                        <td>
                                            <select id="paypal_button_layout" name="paypal[button_layout]">
                                                <option value="vertical" <?php selected($paypal_settings['button_layout'] ?? 'vertical', 'vertical'); ?>>Vertical</option>
                                                <option value="horizontal" <?php selected($paypal_settings['button_layout'] ?? 'vertical', 'horizontal'); ?>>Horizontal</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="paypal_button_color">Color</label></th>
                                        <td>
                                            <select id="paypal_button_color" name="paypal[button_color]">
                                                <option value="gold" <?php selected($paypal_settings['button_color'] ?? 'gold', 'gold'); ?>>Gold</option>
                                                <option value="blue" <?php selected($paypal_settings['button_color'] ?? 'gold', 'blue'); ?>>Blue</option>
                                                <option value="silver" <?php selected($paypal_settings['button_color'] ?? 'gold', 'silver'); ?>>Silver</option>
                                                <option value="white" <?php selected($paypal_settings['button_color'] ?? 'gold', 'white'); ?>>White</option>
                                                <option value="black" <?php selected($paypal_settings['button_color'] ?? 'gold', 'black'); ?>>Black</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="paypal_button_shape">Shape</label></th>
                                        <td>
                                            <select id="paypal_button_shape" name="paypal[button_shape]">
                                                <option value="rect" <?php selected($paypal_settings['button_shape'] ?? 'rect', 'rect'); ?>>Rectangle</option>
                                                <option value="pill" <?php selected($paypal_settings['button_shape'] ?? 'rect', 'pill'); ?>>Pill</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th scope="row"><label for="paypal_button_label">Label</label></th>
                                        <td>
                                            <select id="paypal_button_label" name="paypal[button_label]">
                                                <option value="paypal" <?php selected($paypal_settings['button_label'] ?? 'paypal', 'paypal'); ?>>PayPal</option>
                                                <option value="checkout" <?php selected($paypal_settings['button_label'] ?? 'paypal', 'checkout'); ?>>Checkout</option>
                                                <option value="buynow" <?php selected($paypal_settings['button_label'] ?? 'paypal', 'buynow'); ?>>Buy Now</option>
                                                <option value="pay" <?php selected($paypal_settings['button_label'] ?? 'paypal', 'pay'); ?>>Pay</option>
                                            </select>
                                        </td>
                                    </tr>
                                </table>

                                <?php submit_button('Save PayPal Settings'); ?>
                            </form>
                        </div>
                    <?php endif; ?>

                <?php endif; ?>

                    </div><!-- .ggmc-payment-settings -->

                    <!-- Contextual Help Panel -->
                    <div class="ggmc-settings-help" id="ggmc-payment-help">
                        <div class="ggmc-help-default">
                            <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>
                            <p>Click the <span class="ggmc-info-icon-demo"><span class="dashicons dashicons-info-outline"></span></span> icons next to any setting to learn more about it.</p>

                            <div class="ggmc-help-quick-links">
                                <h4>Quick Links</h4>
                                <ul>
                                    <li><a href="https://dashboard.stripe.com/test/apikeys" target="_blank" rel="noopener"><span class="dashicons dashicons-external"></span> Stripe API Keys</a></li>
                                    <li><a href="https://dashboard.stripe.com/test/webhooks" target="_blank" rel="noopener"><span class="dashicons dashicons-external"></span> Stripe Webhooks</a></li>
                                    <li><a href="https://developer.paypal.com/dashboard/applications/sandbox" target="_blank" rel="noopener"><span class="dashicons dashicons-external"></span> PayPal Sandbox Apps</a></li>
                                    <li><a href="https://developer.paypal.com/dashboard/webhooks" target="_blank" rel="noopener"><span class="dashicons dashicons-external"></span> PayPal Webhooks</a></li>
                                </ul>
                            </div>

                            <div class="ggmc-help-test-cards">
                                <h4>Stripe Test Cards</h4>
                                <table class="ggmc-test-cards-table">
                                    <tr><td><code>4242 4242 4242 4242</code></td><td>Success</td></tr>
                                    <tr><td><code>4000 0000 0000 9995</code></td><td>Decline</td></tr>
                                    <tr><td><code>4000 0025 0000 3155</code></td><td>3D Secure</td></tr>
                                </table>
                                <p class="ggmc-help-note">Use any future date, any 3-digit CVC, and any postal code.</p>
                            </div>
                        </div>

                        <!-- Dynamic help content containers -->
                        <div class="ggmc-help-content" id="help-test-mode" style="display:none;">
                            <h3><span class="dashicons dashicons-admin-tools"></span> Test Mode</h3>
                            <p><strong>What it does:</strong> When enabled, all transactions use sandbox/test credentials. No real money is processed.</p>
                            <p><strong>When to use:</strong></p>
                            <ul>
                                <li>During initial setup and configuration</li>
                                <li>When testing checkout flow</li>
                                <li>Before going live with a new integration</li>
                            </ul>
                            <div class="ggmc-help-warning">
                                <span class="dashicons dashicons-warning"></span>
                                <strong>Important:</strong> Disable test mode before accepting real payments! Transactions made in test mode cannot be captured.
                            </div>
                        </div>

                        <div class="ggmc-help-content" id="help-api-keys" style="display:none;">
                            <h3><span class="dashicons dashicons-admin-network"></span> API Keys</h3>
                            <p><strong>Publishable Key:</strong> Used in frontend JavaScript to create payment forms. Safe to expose in browser.</p>
                            <p><strong>Secret Key:</strong> Used server-side to process payments. <strong>Never share this key!</strong></p>
                            <h4>Getting Your Keys:</h4>
                            <ol>
                                <li>Log in to your <a href="https://dashboard.stripe.com/apikeys" target="_blank">Stripe Dashboard</a></li>
                                <li>Navigate to Developers → API Keys</li>
                                <li>Copy both the Publishable and Secret keys</li>
                                <li>For test mode, use keys starting with <code>pk_test_</code> and <code>sk_test_</code></li>
                            </ol>
                            <div class="ggmc-help-tip">
                                <span class="dashicons dashicons-lightbulb"></span>
                                <strong>Tip:</strong> Create restricted keys with limited permissions for better security.
                            </div>
                        </div>

                        <div class="ggmc-help-content" id="help-webhook" style="display:none;">
                            <h3><span class="dashicons dashicons-admin-links"></span> Webhooks</h3>
                            <p><strong>What they do:</strong> Webhooks allow Stripe/PayPal to notify your site about events (successful payments, refunds, disputes).</p>
                            <h4>Setting Up Stripe Webhooks:</h4>
                            <ol>
                                <li>Go to <a href="https://dashboard.stripe.com/webhooks" target="_blank">Stripe Dashboard → Webhooks</a></li>
                                <li>Click "Add endpoint"</li>
                                <li>Paste your Webhook URL (shown above)</li>
                                <li>Select events to listen for:
                                    <ul>
                                        <li><code>payment_intent.succeeded</code></li>
                                        <li><code>payment_intent.payment_failed</code></li>
                                        <li><code>charge.refunded</code></li>
                                    </ul>
                                </li>
                                <li>Copy the Webhook Secret and paste it here</li>
                            </ol>
                            <div class="ggmc-help-warning">
                                <span class="dashicons dashicons-warning"></span>
                                <strong>Local Development:</strong> Webhooks cannot reach localhost. Use <a href="https://stripe.com/docs/stripe-cli" target="_blank">Stripe CLI</a> for local testing.
                            </div>
                        </div>

                        <div class="ggmc-help-content" id="help-payment-methods" style="display:none;">
                            <h3><span class="dashicons dashicons-money-alt"></span> Payment Methods</h3>
                            <p>Enable the payment methods you want to offer at checkout.</p>

                            <h4>Stripe Payment Methods:</h4>
                            <ul>
                                <li><strong>Cards:</strong> Always enabled. Accepts Visa, Mastercard, Amex, etc.</li>
                                <li><strong>Apple Pay:</strong> For iOS/macOS Safari users with cards in Apple Wallet</li>
                                <li><strong>Google Pay:</strong> For Chrome users with saved cards</li>
                                <li><strong>Link:</strong> Stripe's fast checkout with saved payment info</li>
                            </ul>

                            <h4>PayPal Payment Methods:</h4>
                            <ul>
                                <li><strong>PayPal:</strong> Standard PayPal account payments</li>
                                <li><strong>Pay Later:</strong> Interest-free installment options</li>
                                <li><strong>Venmo:</strong> US customers only</li>
                                <li><strong>Cards via PayPal:</strong> Guest checkout without PayPal account</li>
                            </ul>

                            <div class="ggmc-help-tip">
                                <span class="dashicons dashicons-lightbulb"></span>
                                <strong>Tip:</strong> Apple Pay and Google Pay automatically appear for compatible devices/browsers.
                            </div>
                        </div>

                        <div class="ggmc-help-content" id="help-paypal-credentials" style="display:none;">
                            <h3><span class="dashicons dashicons-admin-network"></span> PayPal Credentials</h3>
                            <p><strong>Client ID:</strong> Identifies your app to PayPal. Used in frontend JavaScript.</p>
                            <p><strong>Client Secret:</strong> Used server-side for API calls. <strong>Never share!</strong></p>

                            <h4>Getting Sandbox Credentials:</h4>
                            <ol>
                                <li>Go to <a href="https://developer.paypal.com/dashboard/applications/sandbox" target="_blank">PayPal Developer Dashboard</a></li>
                                <li>Click "Create App" or select existing app</li>
                                <li>Copy the Client ID and Secret from "Sandbox" tab</li>
                            </ol>

                            <h4>Getting Live Credentials:</h4>
                            <ol>
                                <li>Same dashboard, but use the "Live" tab</li>
                                <li>You need a verified PayPal Business account</li>
                            </ol>

                            <div class="ggmc-help-tip">
                                <span class="dashicons dashicons-lightbulb"></span>
                                <strong>Tip:</strong> Create a sandbox buyer account to test purchases at <a href="https://developer.paypal.com/dashboard/accounts" target="_blank">PayPal Sandbox Accounts</a>.
                            </div>
                        </div>

                        <div class="ggmc-help-content" id="help-button-style" style="display:none;">
                            <h3><span class="dashicons dashicons-art"></span> Button Style</h3>
                            <p>Customize how PayPal buttons appear on your checkout page.</p>

                            <h4>Options:</h4>
                            <ul>
                                <li><strong>Layout:</strong> Vertical (stacked) or Horizontal (side by side)</li>
                                <li><strong>Color:</strong> Gold (recommended), Blue, Silver, White, or Black</li>
                                <li><strong>Shape:</strong> Rectangle or Pill</li>
                                <li><strong>Label:</strong> Text displayed on the button</li>
                            </ul>

                            <div class="ggmc-help-tip">
                                <span class="dashicons dashicons-lightbulb"></span>
                                <strong>Tip:</strong> PayPal recommends the Gold color as it has the highest recognition and conversion rates.
                            </div>
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-payment-layout -->


                <script>
                jQuery(document).ready(function($) {
                    // Toggle password visibility
                    $('.toggle-password').on('click', function() {
                        var targetId = $(this).data('target');
                        var target = $('#' + targetId);
                        var button = $(this);

                        if (target.attr('type') === 'password') {
                            target.attr('type', 'text');
                            button.text('Hide');
                        } else {
                            target.attr('type', 'password');
                            button.text('Show');
                        }
                    });

                    // Copy URL to clipboard
                    $('.copy-url').on('click', function() {
                        var url = $(this).data('url');
                        var button = $(this);

                        navigator.clipboard.writeText(url).then(function() {
                            button.text('Copied!');
                            setTimeout(function() {
                                button.text('Copy');
                            }, 2000);
                        });
                    });

                    // Contextual help panel functionality
                    var $helpPanel = $('#ggmc-payment-help');
                    var $helpDefault = $helpPanel.find('.ggmc-help-default');
                    var $helpContents = $helpPanel.find('.ggmc-help-content');
                    var activeHelpId = null;

                    $('.ggmc-info-btn').on('click', function(e) {
                        e.preventDefault();
                        var helpId = $(this).data('help');
                        var $targetHelp = $('#help-' + helpId);

                        // Remove active state from all buttons
                        $('.ggmc-info-btn').removeClass('active');

                        // If clicking the same button, reset to default
                        if (activeHelpId === helpId) {
                            $helpContents.hide();
                            $helpDefault.show();
                            activeHelpId = null;
                            return;
                        }

                        // Show the selected help content
                        $(this).addClass('active');
                        $helpDefault.hide();
                        $helpContents.hide();
                        $targetHelp.fadeIn(200);
                        activeHelpId = helpId;

                        // Scroll help panel into view if needed
                        if ($helpPanel.length && window.innerWidth > 1200) {
                            var panelTop = $helpPanel.offset().top;
                            var scrollTop = $(window).scrollTop();
                            var windowHeight = $(window).height();

                            if (panelTop < scrollTop || panelTop > scrollTop + windowHeight - 200) {
                                $('html, body').animate({
                                    scrollTop: panelTop - 100
                                }, 300);
                            }
                        }
                    });

                    // Reset help when clicking elsewhere (optional, can be removed if not desired)
                    // Disabled to allow clicking around without losing help context
                    // $(document).on('click', function(e) {
                    //     if (!$(e.target).closest('.ggmc-info-btn, .ggmc-payment-help').length) {
                    //         $('.ggmc-info-btn').removeClass('active');
                    //         $helpContents.hide();
                    //         $helpDefault.show();
                    //         activeHelpId = null;
                    //     }
                    // });

                    // Save Stripe settings via AJAX
                    $('#stripe-settings-form').on('submit', function(e) {
                        e.preventDefault();
                        var form = $(this);
                        var submitBtn = form.find('input[type="submit"]');
                        var originalText = submitBtn.val();

                        submitBtn.val('Saving...').prop('disabled', true);

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_save_stripe_settings',
                                nonce: $('#stripe_settings_nonce').val(),
                                settings: form.serialize()
                            },
                            success: function(response) {
                                if (response.success) {
                                    submitBtn.val('Saved!');
                                    setTimeout(function() {
                                        submitBtn.val(originalText);
                                    }, 2000);
                                } else {
                                    alert('Error saving settings: ' + (response.data || 'Unknown error'));
                                    submitBtn.val(originalText);
                                }
                            },
                            error: function() {
                                alert('Error saving settings. Please try again.');
                                submitBtn.val(originalText);
                            },
                            complete: function() {
                                submitBtn.prop('disabled', false);
                            }
                        });
                    });

                    // Save PayPal settings via AJAX
                    $('#paypal-settings-form').on('submit', function(e) {
                        e.preventDefault();
                        var form = $(this);
                        var submitBtn = form.find('input[type="submit"]');
                        var originalText = submitBtn.val();

                        submitBtn.val('Saving...').prop('disabled', true);

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_save_paypal_settings',
                                nonce: $('#paypal_settings_nonce').val(),
                                settings: form.serialize()
                            },
                            success: function(response) {
                                if (response.success) {
                                    submitBtn.val('Saved!');
                                    setTimeout(function() {
                                        submitBtn.val(originalText);
                                    }, 2000);
                                } else {
                                    alert('Error saving settings: ' + (response.data || 'Unknown error'));
                                    submitBtn.val(originalText);
                                }
                            },
                            error: function() {
                                alert('Error saving settings. Please try again.');
                                submitBtn.val(originalText);
                            },
                            complete: function() {
                                submitBtn.prop('disabled', false);
                            }
                        });
                    });
                });
                </script>

            <?php elseif ($active_tab == 'subscriptions') : ?>
                <!-- Subscription Settings Tab -->
                <?php
                $sub_activated = class_exists( 'GGM_Commerce_Subscriptions' ) && GGM_Commerce_Subscriptions::is_activated();
                ?>
                <?php if ( ! $sub_activated ) : ?>
                    <div class="card" style="border-left: 4px solid #d97706;">
                        <h3 style="margin-top: 0;"><span class="dashicons dashicons-lock" style="margin-right: 8px;"></span>Premium Feature</h3>
                        <p>Subscription Billing is a premium component. Activate it in the <a href="?page=ggmc-settings&tab=premium-components">Premium Components</a> tab to configure these settings.</p>
                    </div>
                <?php else : ?>
                    <?php
                    // Handle form save.
                    if ( isset( $_POST['ggmc_save_subscription_settings'] ) && check_admin_referer( 'ggmc_subscription_settings' ) ) {
                        $settings = array(
                            'retry_schedule' => array(),
                            'grace_period'   => isset( $_POST['grace_period'] ) ? absint( $_POST['grace_period'] ) : 7,
                            'max_retries'    => isset( $_POST['max_retries'] ) ? absint( $_POST['max_retries'] ) : 3,
                            'allow_pause'    => ! empty( $_POST['allow_pause'] ),
                            'allow_cancel'   => ! empty( $_POST['allow_cancel'] ),
                            'allow_reactivate' => ! empty( $_POST['allow_reactivate'] ),
                            'allow_change_plan' => ! empty( $_POST['allow_change_plan'] ),
                            'allow_change_payment_method' => ! empty( $_POST['allow_change_payment_method'] ),
                            'max_pause_duration' => isset( $_POST['max_pause_duration'] ) ? absint( $_POST['max_pause_duration'] ) : 90,
                            'cancellation_behavior' => isset( $_POST['cancellation_behavior'] ) && in_array( $_POST['cancellation_behavior'], array( 'end_of_period', 'immediate' ), true ) ? sanitize_text_field( wp_unslash( $_POST['cancellation_behavior'] ) ) : 'end_of_period',
                        );

                        // Parse retry schedule (comma-separated days).
                        if ( ! empty( $_POST['retry_schedule'] ) ) {
                            $raw = sanitize_text_field( wp_unslash( $_POST['retry_schedule'] ) );
                            $days = array_map( 'absint', array_filter( explode( ',', $raw ) ) );
                            $settings['retry_schedule'] = array_values( array_slice( $days, 0, 10 ) );
                        }
                        if ( empty( $settings['retry_schedule'] ) ) {
                            $settings['retry_schedule'] = array( 1, 3, 5 );
                        }

                        update_option( 'ggm_commerce_subscription_settings', $settings );
                        echo '<div class="notice notice-success"><p>Subscription settings saved.</p></div>';
                    }

                    $settings = GGM_Commerce_Subscriptions::get_settings();
                    ?>

                    <div class="ggmc-settings-layout">
                        <div class="ggmc-settings-main">

                            <!-- Payment Retry Settings -->
                            <div class="card" style="margin-bottom: 20px;">
                                <form method="post">
                                    <?php wp_nonce_field( 'ggmc_subscription_settings' ); ?>

                                    <h3 style="margin-top: 0;">Payment Retry Settings</h3>
                                    <table class="form-table">
                                        <tr>
                                            <th scope="row"><label for="retry_schedule">Retry Schedule (days)</label></th>
                                            <td>
                                                <input type="text" id="retry_schedule" name="retry_schedule"
                                                       value="<?php echo esc_attr( implode( ', ', $settings['retry_schedule'] ) ); ?>"
                                                       class="regular-text" placeholder="1, 3, 5">
                                                <p class="description">Comma-separated number of days after failure to retry. E.g. "1, 3, 5" means retry after 1 day, 3 days, and 5 days.</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row"><label for="max_retries">Max Retries</label></th>
                                            <td>
                                                <input type="number" id="max_retries" name="max_retries"
                                                       value="<?php echo esc_attr( $settings['max_retries'] ); ?>"
                                                       min="0" max="10" style="width: 80px;">
                                                <p class="description">Maximum number of payment retry attempts before placing subscription on hold.</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row"><label for="grace_period">Grace Period (days)</label></th>
                                            <td>
                                                <input type="number" id="grace_period" name="grace_period"
                                                       value="<?php echo esc_attr( $settings['grace_period'] ); ?>"
                                                       min="0" max="90" style="width: 80px;">
                                                <p class="description">Days after final retry failure before the subscription is cancelled. Set to 0 for immediate cancellation.</p>
                                            </td>
                                        </tr>
                                    </table>

                                    <h3>Customer Self-Service Options</h3>
                                    <p class="description" style="margin-bottom: 15px;">Control which self-service actions customers can perform on their subscriptions.</p>
                                    <table class="form-table">
                                        <tr>
                                            <th scope="row">Allow Pause</th>
                                            <td>
                                                <label>
                                                    <input type="checkbox" name="allow_pause" value="1" <?php checked( $settings['allow_pause'] ); ?>>
                                                    Customers can pause their subscriptions
                                                </label>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Allow Cancel</th>
                                            <td>
                                                <label>
                                                    <input type="checkbox" name="allow_cancel" value="1" <?php checked( $settings['allow_cancel'] ); ?>>
                                                    Customers can cancel their subscriptions
                                                </label>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Allow Reactivate</th>
                                            <td>
                                                <label>
                                                    <input type="checkbox" name="allow_reactivate" value="1" <?php checked( $settings['allow_reactivate'] ); ?>>
                                                    Customers can reactivate cancelled subscriptions
                                                </label>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Allow Plan Change</th>
                                            <td>
                                                <label>
                                                    <input type="checkbox" name="allow_change_plan" value="1" <?php checked( $settings['allow_change_plan'] ); ?>>
                                                    Customers can upgrade or downgrade their plan
                                                </label>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Allow Payment Method Change</th>
                                            <td>
                                                <label>
                                                    <input type="checkbox" name="allow_change_payment_method" value="1" <?php checked( $settings['allow_change_payment_method'] ); ?>>
                                                    Customers can update their payment method
                                                </label>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row"><label for="max_pause_duration">Max Pause Duration (days)</label></th>
                                            <td>
                                                <input type="number" id="max_pause_duration" name="max_pause_duration"
                                                       value="<?php echo esc_attr( $settings['max_pause_duration'] ); ?>"
                                                       min="0" max="365" style="width: 80px;">
                                                <p class="description">Maximum days a subscription can stay paused. 0 = unlimited.</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <th scope="row"><label for="cancellation_behavior">Cancellation Behavior</label></th>
                                            <td>
                                                <select id="cancellation_behavior" name="cancellation_behavior">
                                                    <option value="end_of_period" <?php selected( $settings['cancellation_behavior'], 'end_of_period' ); ?>>
                                                        Cancel at end of billing period
                                                    </option>
                                                    <option value="immediate" <?php selected( $settings['cancellation_behavior'], 'immediate' ); ?>>
                                                        Cancel immediately
                                                    </option>
                                                </select>
                                                <p class="description">"End of period" keeps the subscription active until the next payment date. "Immediate" cancels straight away.</p>
                                            </td>
                                        </tr>
                                    </table>

                                    <?php submit_button( 'Save Subscription Settings', 'primary', 'ggmc_save_subscription_settings' ); ?>
                                </form>
                            </div>

                        </div><!-- .ggmc-settings-main -->

                        <div class="ggmc-settings-help">
                            <h3><span class="dashicons dashicons-editor-help"></span> Subscription Settings</h3>
                            <h4>Payment Retries</h4>
                            <p>When a recurring payment fails, the system will automatically retry based on your schedule. After all retries are exhausted, the subscription is placed on hold for the grace period before being cancelled.</p>
                            <h4>Self-Service</h4>
                            <p>These toggles control what actions customers see on their subscription management page. Admins can always perform all actions regardless of these settings.</p>
                            <h4>Cancellation</h4>
                            <p><strong>End of period</strong> is recommended — customers keep access until their paid period ends. <strong>Immediate</strong> stops access right away.</p>
                        </div><!-- .ggmc-settings-help -->
                    </div><!-- .ggmc-settings-layout -->
                <?php endif; ?>

            <?php elseif ($active_tab == 'transaction-export') : ?>
                <!-- Transaction Export Tab -->
                <?php
                require_once plugin_dir_path( __FILE__ ) . 'admin-transaction-export-tab.php';
                ggmc_render_transaction_export_tab();
                ?>

            <?php elseif ($active_tab == 'test-data' && current_user_can('manage_options')) : ?>
                <!-- Test Data Tab (Admin Only) -->
                <?php
                // Check if test data exists
                global $wpdb;
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $test_products_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'product'");
                $has_test_data = $test_products_count > 0;
                ?>

                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <div id="test-data-status"></div>

                <div class="ggmc-settings-grid">

                    <!-- Generate Test Data Section -->
                    <div class="card">
                        <h2 style="margin-top: 0;">Generate Test Data</h2>
                        <p>Create sample products, categories, and tags to help you test all the Goose Commerce features and widgets.</p>

                        <table class="form-table" style="margin-top: 20px;">
                            <tr>
                                <th scope="row">Categories</th>
                                <td>
                                    <label><input type="checkbox" id="generate-categories" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate 8 product categories</label>
                                    <p class="description">Electronics, Clothing, Books, Home & Garden, Sports, Beauty, Toys, Food & Beverages</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Tags</th>
                                <td>
                                    <label><input type="checkbox" id="generate-tags" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate 15 product tags</label>
                                    <p class="description">Popular, Sale, New Arrival, Limited Edition, Best Seller, etc.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Variation Attributes</th>
                                <td>
                                    <label><input type="checkbox" id="generate-attributes" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate 5 variation attributes</label>
                                    <p class="description">Color, Size, Storage, RAM, Material - with multiple options each</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Products</th>
                                <td>
                                    <label><input type="checkbox" id="generate-products" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate 28 sample products</label>
                                    <p class="description">Simple, Variable, Digital, Virtual, Kit, and Build product types</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Product Variations</th>
                                <td>
                                    <label><input type="checkbox" id="generate-variations" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Apply variations to products</label>
                                    <p class="description">Combined mode (iPhone, MacBook) and Independent mode (T-Shirt, Jacket) variations</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Kits &amp; Builds</th>
                                <td>
                                    <label><input type="checkbox" id="generate-kits" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate kit/build components</label>
                                    <p class="description">Create kit bundles and permanent builds with component products</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Digital Downloads</th>
                                <td>
                                    <label><input type="checkbox" id="generate-downloads" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate download files</label>
                                    <p class="description">Add downloadable files and licenses to digital products</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Custom Attributes</th>
                                <td>
                                    <label><input type="checkbox" id="generate-custom-attributes" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate custom product attributes</label>
                                    <p class="description">Create attribute groups (Electronics, Clothing, etc.) and assign values to products</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Reviews</th>
                                <td>
                                    <label><input type="checkbox" id="generate-reviews" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate sample product reviews</label>
                                    <p class="description">1-6 reviews per product with varied ratings, helpful votes, and verified purchase badges</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Customers</th>
                                <td>
                                    <label><input type="checkbox" id="generate-customers" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate 12 test customers</label>
                                    <p class="description">UK/US customers with billing and shipping addresses</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Orders</th>
                                <td>
                                    <label><input type="checkbox" id="generate-orders" checked <?php echo $has_test_data ? 'disabled' : ''; ?>> Generate 20 test orders</label>
                                    <p class="description">Mixed statuses, payment methods, and date range over 90 days</p>
                                </td>
                            </tr>
                        </table>

                        <p class="submit">
                            <button type="button" id="generate-test-data-btn" class="button button-primary" <?php echo $has_test_data ? 'disabled' : ''; ?>>
                                Generate Test Data
                            </button>
                        </p>

                        <?php if ($has_test_data): ?>
                            <div class="notice notice-info inline" style="margin: 0; padding: 10px;">
                                <p style="margin: 0;"><strong>ℹ️ Test data already exists.</strong> Clear existing test data first to generate new data.</p>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Clear Test Data Section -->
                    <div class="card">
                        <h2 style="margin-top: 0;">Clear Test Data</h2>
                        <p>Remove test products and optionally categories and tags created by the test data generator.</p>

                        <table class="form-table" style="margin-top: 20px;">
                            <tr>
                                <th scope="row">Clear Options</th>
                                <td>
                                    <label><input type="checkbox" id="clear-categories" <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test categories</label><br>
                                    <label><input type="checkbox" id="clear-tags" <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test tags</label><br>
                                    <label><input type="checkbox" id="clear-attributes" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test variation attributes</label><br>
                                    <label><input type="checkbox" id="clear-variations" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test variations</label><br>
                                    <label><input type="checkbox" id="clear-kits" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test kits/builds</label><br>
                                    <label><input type="checkbox" id="clear-downloads" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test downloads</label><br>
                                    <label><input type="checkbox" id="clear-custom-attributes" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test custom attributes</label><br>
                                    <label><input type="checkbox" id="clear-reviews" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test reviews</label><br>
                                    <label><input type="checkbox" id="clear-orders" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test orders</label><br>
                                    <label><input type="checkbox" id="clear-customers" checked <?php echo !$has_test_data ? 'disabled' : ''; ?>> Also remove test customers</label>
                                    <p class="description">Choose what to delete. Unchecked = keep for reuse.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">Current Data</th>
                                <td>
                                    <p style="margin: 0;">
                                        <strong>Test Products:</strong> <?php echo intval($test_products_count); ?><br>
                                        <?php
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_categories_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'category'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_tags_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'tag'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_attributes_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'variation_attribute'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_variations_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'product_variation'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_kits_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'product_kit'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_downloads_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'product_download'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_custom_attrs_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type IN ('custom_attribute_group', 'custom_attribute', 'product_attribute_value')");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_reviews_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'review'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_customers_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'customer'");
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $test_orders_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_test_data_registry WHERE item_type = 'order'");
                                        ?>
                                        <strong>Test Categories:</strong> <?php echo intval($test_categories_count); ?><br>
                                        <strong>Test Tags:</strong> <?php echo intval($test_tags_count); ?><br>
                                        <strong>Test Variation Attrs:</strong> <?php echo intval($test_attributes_count); ?><br>
                                        <strong>Test Variations:</strong> <?php echo intval($test_variations_count); ?><br>
                                        <strong>Test Kits/Builds:</strong> <?php echo intval($test_kits_count); ?><br>
                                        <strong>Test Downloads:</strong> <?php echo intval($test_downloads_count); ?><br>
                                        <strong>Test Custom Attrs:</strong> <?php echo intval($test_custom_attrs_count); ?><br>
                                        <strong>Test Reviews:</strong> <?php echo intval($test_reviews_count); ?><br>
                                        <strong>Test Customers:</strong> <?php echo intval($test_customers_count); ?><br>
                                        <strong>Test Orders:</strong> <?php echo intval($test_orders_count); ?>
                                    </p>
                                </td>
                            </tr>
                        </table>

                        <p class="submit">
                            <button type="button" id="clear-test-data-btn" class="button button-secondary" <?php echo !$has_test_data ? 'disabled' : ''; ?>>
                                Clear Test Products
                            </button>
                        </p>

                        <?php if (!$has_test_data): ?>
                            <div class="notice notice-warning inline" style="margin: 0; padding: 10px;">
                                <p style="margin: 0;"><strong>⚠️ No test data found.</strong> Generate test data first before clearing.</p>
                            </div>
                        <?php endif; ?>
                    </div>

                </div>

                <!-- Cart Management Section -->
                <?php
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $db_cart_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_cart");

                // Get session cart count
                if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
                    session_start();
                }
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Cart data is internal
                $session_cart = isset($_SESSION['ggm_commerce_cart']) ? $_SESSION['ggm_commerce_cart'] : [];
                $session_cart_count = !empty($session_cart) ? array_sum(array_column($session_cart, 'quantity')) : 0;

                $has_cart_data = ($db_cart_count > 0 || $session_cart_count > 0);
                ?>
                <div class="card" style="margin-top: 20px;">
                    <h2 style="margin-top: 0;">Cart Management</h2>
                    <p>Clear all cart data from database and PHP sessions. Useful for fixing cart synchronization issues during development.</p>

                    <table class="form-table" style="margin-top: 20px;">
                        <tr>
                            <th scope="row">Cart Data Status</th>
                            <td>
                                <strong>Database:</strong> <?php echo intval($db_cart_count); ?> items<br>
                                <strong>Current Session:</strong> <?php echo intval($session_cart_count); ?> items
                                <?php if ($db_cart_count != $session_cart_count && ($db_cart_count > 0 || $session_cart_count > 0)): ?>
                                    <br><span style="color: #d63638;">⚠️ Out of sync - clearing will fix this</span>
                                <?php endif; ?>
                                <p class="description">Database stores persistent cart data; sessions store temporary cart state</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">Clear All Carts</th>
                            <td>
                                <button type="button" id="clear-all-carts-btn" class="button button-secondary" <?php echo !$has_cart_data ? 'disabled' : ''; ?>>
                                    Clear All Cart Data
                                </button>
                                <p class="description">Clears both database cart items and PHP session data. This action cannot be undone.</p>
                                <div id="cart-clear-status" style="margin-top: 10px;"></div>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- Wishlist Management Section -->
                <?php
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wishlist_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_wishlist");
                $has_wishlist_data = ($wishlist_count > 0);
                ?>
                <div class="card" style="margin-top: 20px;">
                    <h2 style="margin-top: 0;">Wishlist Management</h2>
                    <p>Clear all wishlist data from database. Useful for cleaning up during development and testing.</p>

                    <table class="form-table" style="margin-top: 20px;">
                        <tr>
                            <th scope="row">Wishlist Data Status</th>
                            <td>
                                <strong>Database:</strong> <?php echo intval($wishlist_count); ?> items
                                <p class="description">Database stores wishlist items for logged-in users. Guest wishlists are stored in browser cookies.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">Clear All Wishlists</th>
                            <td>
                                <button type="button" id="clear-all-wishlists-btn" class="button button-secondary" <?php echo !$has_wishlist_data ? 'disabled' : ''; ?>>
                                    Clear All Wishlist Data
                                </button>
                                <p class="description">Clears all wishlist items from the database. Guest cookie wishlists will be cleared when cookies expire. This action cannot be undone.</p>
                                <div id="wishlist-clear-status" style="margin-top: 10px;"></div>
                            </td>
                        </tr>
                    </table>
                </div>

                <!-- Comparison Management Section -->
                <div class="card" style="margin-top: 20px;">
                    <h2 style="margin-top: 0;">Comparison Management</h2>
                    <p>Comparison lists are stored in browser cookies. Use this to clear your current comparison list for testing.</p>

                    <table class="form-table" style="margin-top: 20px;">
                        <tr>
                            <th scope="row">Comparison Data</th>
                            <td>
                                <strong>Storage:</strong> Browser cookies (client-side)
                                <p class="description">Product comparisons are stored in cookies on each user's browser.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">Clear Comparison Cookie</th>
                            <td>
                                <button type="button" id="clear-comparison-btn" class="button button-secondary">
                                    Clear My Comparison List
                                </button>
                                <p class="description">Clears the comparison cookie for your current browser session.</p>
                                <div id="comparison-clear-status" style="margin-top: 10px;"></div>
                            </td>
                        </tr>
                    </table>
                </div>

                <script>
                jQuery(document).ready(function($) {
                    // Ensure ajaxurl is defined
                    if (typeof ajaxurl === 'undefined') {
                        var ajaxurl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
                    }

                    $('#generate-test-data-btn').on('click', function() {
                        const button = $(this);
                        const statusDiv = $('#test-data-status');

                        button.prop('disabled', true).text('Generating...');
                        statusDiv.html('<div class="notice notice-info"><p>Generating test data, please wait...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            timeout: 120000, // 2 minutes timeout
                            data: {
                                action: 'ggm_commerce_generate_test_data',
                                generate_categories: $('#generate-categories').is(':checked'),
                                generate_tags: $('#generate-tags').is(':checked'),
                                generate_attributes: $('#generate-attributes').is(':checked'),
                                generate_products: $('#generate-products').is(':checked'),
                                generate_variations: $('#generate-variations').is(':checked'),
                                generate_kits: $('#generate-kits').is(':checked'),
                                generate_downloads: $('#generate-downloads').is(':checked'),
                                generate_custom_attributes: $('#generate-custom-attributes').is(':checked'),
                                generate_reviews: $('#generate-reviews').is(':checked'),
                                generate_customers: $('#generate-customers').is(':checked'),
                                generate_orders: $('#generate-orders').is(':checked'),
                                clear_existing: false, // Don't clear - button is disabled if data exists
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_test_data')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    statusDiv.html('<div class="notice notice-success"><p><strong>Success!</strong> ' + response.data.message + '</p><p><strong>You can now test all your Elementor widgets and controls!</strong></p></div>');
                                    // Reload page to update button states
                                    setTimeout(function() {
                                        location.reload();
                                    }, 2000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error"><p><strong>Error:</strong> ' + response.data.message + '</p></div>');
                                    button.prop('disabled', false).text('Generate Test Data');
                                }
                            },
                            error: function(xhr, errorStatus, errorMessage) {
                                if (errorStatus === 'timeout') {
                                    statusDiv.html('<div class="notice notice-error"><p><strong>Timeout:</strong> The request took too long. Try refreshing and checking if any data was created.</p></div>');
                                } else {
                                    statusDiv.html('<div class="notice notice-error"><p><strong>AJAX error:</strong> ' + errorMessage + '</p></div>');
                                }
                                button.prop('disabled', false).text('Generate Test Data');
                            }
                        });
                    });

                    $('#clear-test-data-btn').on('click', function() {
                        if (!confirm('Are you sure you want to clear test products? Categories and tags will be removed based on the checkboxes. This cannot be undone.')) {
                            return;
                        }

                        const button = $(this);
                        const statusDiv = $('#test-data-status');

                        button.prop('disabled', true).text('Clearing...');
                        statusDiv.html('<div class="notice notice-info"><p>Clearing test data...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_generate_test_data',
                                clear_only: true,
                                clear_categories: $('#clear-categories').is(':checked'),
                                clear_tags: $('#clear-tags').is(':checked'),
                                clear_attributes: $('#clear-attributes').is(':checked'),
                                clear_variations: $('#clear-variations').is(':checked'),
                                clear_kits: $('#clear-kits').is(':checked'),
                                clear_downloads: $('#clear-downloads').is(':checked'),
                                clear_custom_attributes: $('#clear-custom-attributes').is(':checked'),
                                clear_reviews: $('#clear-reviews').is(':checked'),
                                clear_orders: $('#clear-orders').is(':checked'),
                                clear_customers: $('#clear-customers').is(':checked'),
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_test_data')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    statusDiv.html('<div class="notice notice-success"><p><strong>Success!</strong> ' + response.data.message + '</p></div>');
                                    // Reload page to update button states
                                    setTimeout(function() {
                                        location.reload();
                                    }, 2000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error"><p><strong>Error:</strong> ' + response.data.message + '</p></div>');
                                    button.prop('disabled', false).text('Clear Test Products');
                                }
                            },
                            error: function(xhr, errorStatus, errorMessage) {
                                statusDiv.html('<div class="notice notice-error"><p><strong>AJAX Error:</strong> ' + errorMessage + '</p></div>');
                                button.prop('disabled', false).text('Clear Test Products');
                            }
                        });
                    });

                    // Clear all carts button
                    $('#clear-all-carts-btn').on('click', function() {
                        if (!confirm('Are you sure you want to clear ALL cart data?\n\nThis will remove all items from all customer sessions.\n\nThis action cannot be undone.')) {
                            return;
                        }

                        const button = $(this);
                        const statusDiv = $('#cart-clear-status');

                        button.prop('disabled', true).text('Clearing...');
                        statusDiv.html('<div class="notice notice-info inline"><p>Clearing all cart data...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_clear_all_carts',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_clear_carts')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    var message = '<strong>✅ Success!</strong> Cleared: ';
                                    var parts = [];
                                    if (response.data.db_count > 0) {
                                        parts.push(response.data.db_count + ' database item(s)');
                                    }
                                    if (response.data.session_count > 0) {
                                        parts.push(response.data.session_count + ' session item(s)');
                                    }
                                    message += parts.join(' and ') || 'no items found';
                                    statusDiv.html('<div class="notice notice-success inline"><p>' + message + '</p></div>');
                                    setTimeout(function() {
                                        location.reload();
                                    }, 2000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error inline"><p><strong>❌ Error:</strong> ' + response.data.message + '</p></div>');
                                    button.prop('disabled', false).text('Clear All Cart Data');
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error inline"><p><strong>❌ Error:</strong> Failed to clear carts. Please try again.</p></div>');
                                button.prop('disabled', false).text('Clear All Cart Data');
                            }
                        });
                    });

                    // Clear all wishlists button
                    $('#clear-all-wishlists-btn').on('click', function() {
                        if (!confirm('Are you sure you want to clear ALL wishlist data?\n\nThis will remove all saved wishlist items for all users.\n\nThis action cannot be undone.')) {
                            return;
                        }

                        const button = $(this);
                        const statusDiv = $('#wishlist-clear-status');

                        button.prop('disabled', true).text('Clearing...');
                        statusDiv.html('<div class="notice notice-info inline"><p>Clearing all wishlist data...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_clear_all_wishlists',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_clear_wishlists')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    statusDiv.html('<div class="notice notice-success inline"><p><strong>✅ Success!</strong> Cleared ' + response.data.count + ' wishlist item(s).</p></div>');
                                    setTimeout(function() {
                                        location.reload();
                                    }, 2000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error inline"><p><strong>❌ Error:</strong> ' + response.data.message + '</p></div>');
                                    button.prop('disabled', false).text('Clear All Wishlist Data');
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error inline"><p><strong>❌ Error:</strong> Failed to clear wishlists. Please try again.</p></div>');
                                button.prop('disabled', false).text('Clear All Wishlist Data');
                            }
                        });
                    });

                    // Clear comparison cookie button (client-side only)
                    $('#clear-comparison-btn').on('click', function() {
                        const button = $(this);
                        const statusDiv = $('#comparison-clear-status');

                        // Delete the comparison cookie
                        document.cookie = 'ggmc_compare=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';

                        statusDiv.html('<div class="notice notice-success inline"><p><strong>✅ Success!</strong> Comparison list cleared from your browser.</p></div>');
                        button.text('Cleared!');

                        setTimeout(function() {
                            button.text('Clear My Comparison List');
                            statusDiv.html('');
                        }, 3000);
                    });
                });
                </script>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>About Test Data</h4>
                        <p>Test data helps you explore all Goose Commerce features without manually creating products.</p>

                        <h4>What Gets Generated</h4>
                        <ul>
                            <li><strong>25 Products</strong> with images</li>
                            <li><strong>8 Categories</strong></li>
                            <li><strong>15 Tags</strong></li>
                            <li><strong>Reviews</strong> per product</li>
                        </ul>

                        <h4>Best Practices</h4>
                        <ul>
                            <li>Use on development/staging first</li>
                            <li>Clear test data before going live</li>
                            <li>Test all widgets with sample data</li>
                        </ul>

                        <div class="ggmc-help-tip">
                            <span class="dashicons dashicons-lightbulb"></span>
                            <strong>Tip:</strong> Cart data is stored separately. Use "Clear All Cart Data" to fix sync issues during testing.
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->

            <?php elseif ($active_tab == 'user-roles' && current_user_can('manage_options')) : ?>
                <!-- User Roles Tab (Admin Only) -->
                <?php
                $roles_enabled = class_exists('GGM_Commerce_Roles') && GGM_Commerce_Roles::is_enabled();
                $available_roles = class_exists('GGM_Commerce_Roles') ? GGM_Commerce_Roles::get_roles() : [];

                // Get users with Goose Commerce roles
                $ggmc_users = [];
                foreach (array_keys($available_roles) as $role_slug) {
                    $users = get_users(['role' => $role_slug]);
                    foreach ($users as $user) {
                        $ggmc_users[$user->ID] = [
                            'user' => $user,
                            'role' => $role_slug,
                        ];
                    }
                }
                ?>

                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                        <!-- Enable/Disable Custom Roles -->
                        <div class="card">
                            <h2 style="margin-top: 0;">
                                <span class="dashicons dashicons-admin-users" style="margin-right: 8px;"></span>
                                Custom Shop Roles
                            </h2>
                            <p>Enable custom user roles for your shop staff. These roles provide restricted access to WordPress admin, showing only Goose Commerce features relevant to their job.</p>

                            <form method="post" action="">
                                <?php wp_nonce_field('ggmc_toggle_roles', 'ggmc_roles_nonce'); ?>
                                <table class="form-table">
                                    <tr>
                                        <th scope="row">Enable Custom Roles</th>
                                        <td>
                                            <label>
                                                <input type="checkbox" name="ggmc_roles_enabled" value="1" <?php checked($roles_enabled); ?>>
                                                Enable Goose Commerce shop roles
                                            </label>
                                            <p class="description">
                                                When enabled, users with shop roles will see a simplified admin interface with only commerce-related features.
                                            </p>
                                        </td>
                                    </tr>
                                </table>
                                <p class="submit">
                                    <button type="submit" name="ggmc_save_roles_settings" class="button button-primary">Save Settings</button>
                                </p>
                            </form>
                        </div>

                        <!-- Role Descriptions -->
                        <div class="card">
                            <h2 style="margin-top: 0;">Available Roles</h2>
                            <p>These roles are available when custom roles are enabled. Assign them to users via Users &rarr; All Users.</p>

                            <table class="widefat striped" style="margin-top: 15px;">
                                <thead>
                                    <tr>
                                        <th>Role</th>
                                        <th>Description</th>
                                        <th>Key Permissions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><strong>Shop Manager</strong></td>
                                        <td>Full commerce access, no WordPress admin access</td>
                                        <td>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Products (full)<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Orders &amp; Refunds<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Customers<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Reviews<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Most Settings<br>
                                            <span class="dashicons dashicons-no" style="color: #dc3232;"></span> AI/Pages/Widget Settings
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><strong>Shop Staff</strong></td>
                                        <td>Day-to-day order processing</td>
                                        <td>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Orders (process, ship)<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Inventory (stock only)<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Customers (view only)<br>
                                            <span class="dashicons dashicons-no" style="color: #dc3232;"></span> Product creation/pricing<br>
                                            <span class="dashicons dashicons-no" style="color: #dc3232;"></span> Refunds<br>
                                            <span class="dashicons dashicons-no" style="color: #dc3232;"></span> Settings
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><strong>Inventory Manager</strong></td>
                                        <td>Stock and catalog management</td>
                                        <td>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Products (edit, no delete)<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Full inventory control<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Categories &amp; Attributes<br>
                                            <span class="dashicons dashicons-yes" style="color: #46b450;"></span> Variations<br>
                                            <span class="dashicons dashicons-no" style="color: #dc3232;"></span> Pricing<br>
                                            <span class="dashicons dashicons-no" style="color: #dc3232;"></span> Customer data
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <!-- Users with Shop Roles -->
                        <?php if ($roles_enabled) : ?>
                        <div class="card">
                            <h2 style="margin-top: 0;">Users with Shop Roles</h2>
                            <?php if (empty($ggmc_users)) : ?>
                                <p>No users are currently assigned to Goose Commerce roles.</p>
                                <p><a href="<?php echo esc_url(admin_url('user-new.php')); ?>" class="button">Add New User</a></p>
                            <?php else : ?>
                                <table class="widefat striped" style="margin-top: 15px;">
                                    <thead>
                                        <tr>
                                            <th>User</th>
                                            <th>Email</th>
                                            <th>Role</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($ggmc_users as $user_data) : ?>
                                        <tr>
                                            <td>
                                                <?php echo get_avatar($user_data['user']->ID, 32); ?>
                                                <strong><?php echo esc_html($user_data['user']->display_name); ?></strong>
                                            </td>
                                            <td><?php echo esc_html($user_data['user']->user_email); ?></td>
                                            <td><?php echo esc_html($available_roles[$user_data['role']]['display_name'] ?? $user_data['role']); ?></td>
                                            <td>
                                                <a href="<?php echo esc_url(get_edit_user_link($user_data['user']->ID)); ?>">Edit</a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Sticky Help Panel -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> Need Help?</h3>

                        <h4>About Shop Roles</h4>
                        <p>Custom roles let you give staff access to your shop without exposing WordPress admin features they don't need.</p>

                        <h4>Assigning Roles</h4>
                        <ol>
                            <li>Go to Users &rarr; All Users</li>
                            <li>Edit the user you want to update</li>
                            <li>Change their Role to a Goose Commerce role</li>
                            <li>Save the user</li>
                        </ol>

                        <h4>What Staff See</h4>
                        <ul>
                            <li>Simplified dashboard</li>
                            <li>Only Goose Commerce menu</li>
                            <li>No Plugins, Themes, Settings</li>
                            <li>Clean admin bar</li>
                        </ul>

                        <div class="ggmc-help-tip">
                            <span class="dashicons dashicons-lightbulb"></span>
                            <strong>Tip:</strong> Start with Shop Staff for new employees, then upgrade to Shop Manager as needed.
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->

                <?php
                // Handle form submission
                if (isset($_POST['ggmc_save_roles_settings']) && wp_verify_nonce($_POST['ggmc_roles_nonce'] ?? '', 'ggmc_toggle_roles')) {
                    $enable_roles = isset($_POST['ggmc_roles_enabled']);

                    if ($enable_roles) {
                        GGM_Commerce_Roles::enable();
                        echo '<div class="notice notice-success"><p>Custom roles enabled. The roles are now available in the user editor.</p></div>';
                    } else {
                        GGM_Commerce_Roles::disable();
                        echo '<div class="notice notice-info"><p>Custom roles disabled. Existing user role assignments are preserved.</p></div>';
                    }

                    // Refresh page to show updated state
                    echo '<script>setTimeout(function() { window.location.reload(); }, 1500);</script>';
                }
                ?>

            <?php elseif ($active_tab == 'widget-controls') : ?>
                <!-- Widget Controls Tab -->
                <?php
                // Check if defaults are enabled (they are enabled when option is NOT set to true)
                $defaults_cleared = get_option('ggm_commerce_defaults_cleared', false);
                $defaults_enabled = !$defaults_cleared;

                // Get widget controls settings
                // Handle various stored formats: '1', '0', 1, 0, true, false
                $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';
                $widgets_prioritized_raw = isset($widget_controls['widgets_prioritized']) ? $widget_controls['widgets_prioritized'] : '1';
                $widgets_prioritized = in_array($widgets_prioritized_raw, array('1', 1, true, 'true'), true) ? '1' : '0';

                // Check if Product Comparison premium feature is activated
                $comparison_premium_active = false;
                if (function_exists('ggm_commerce_license')) {
                    $license = ggm_commerce_license();
                    $comparison_premium_active = $license->is_widget_activated('product-comparison');
                }

                // Check if Wishlist premium feature is activated
                $wishlist_premium_active = false;
                if (function_exists('ggm_commerce_license')) {
                    $license = ggm_commerce_license();
                    $wishlist_premium_active = $license->is_widget_activated('wishlist');
                }
                ?>

                <div class="ggmc-settings-layout">
                    <div class="ggmc-settings-main">

                <div class="card">
                    <h2><?php esc_html_e('Widget Default Styling', 'ggm-commerce'); ?></h2>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="widget-defaults-toggle"><?php esc_html_e('Professional Defaults', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <!-- Toggle Switch -->
                                    <label class="ggmc-toggle-switch">
                                        <input type="checkbox" id="widget-defaults-toggle" <?php checked($defaults_enabled); ?>>
                                        <span class="ggmc-toggle-slider"></span>
                                    </label>

                                    <!-- Status Label -->
                                    <span id="toggle-status" style="font-weight: 600; color: <?php echo $defaults_enabled ? '#059669' : '#6b7280'; ?>;">
                                        <?php echo $defaults_enabled ? esc_html__('Enabled', 'ggm-commerce') : esc_html__('Disabled', 'ggm-commerce'); ?>
                                    </span>
                                </div>
                                <p class="description" id="toggle-description">
                                    <?php esc_html_e('When enabled, new widgets use professional styling. When disabled, widgets inherit from Elementor Site Settings.', 'ggm-commerce'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="widgets-prioritized-toggle"><?php esc_html_e('Prioritize in Elementor', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <!-- Toggle Switch -->
                                    <label class="ggmc-toggle-switch">
                                        <input type="checkbox" id="widgets-prioritized-toggle" <?php checked($widgets_prioritized, '1'); ?>>
                                        <span class="ggmc-toggle-slider"></span>
                                    </label>

                                    <!-- Status Label -->
                                    <span id="widgets-prioritized-status" style="font-weight: 600; color: <?php echo $widgets_prioritized === '1' ? '#059669' : '#6b7280'; ?>;">
                                        <?php echo $widgets_prioritized === '1' ? esc_html__('Enabled', 'ggm-commerce') : esc_html__('Disabled', 'ggm-commerce'); ?>
                                    </span>
                                </div>
                                <p class="description">
                                    <?php esc_html_e('When enabled, Goose Commerce widgets appear at the top of the Elementor widget panel. Disable to show them in normal alphabetical order.', 'ggm-commerce'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>

                    <div id="default-styles-status" style="margin: 20px 0;"></div>
                </div>

                <!-- Product Comparison Settings -->
                <div class="card">
                    <h2><?php esc_html_e('Product Comparison', 'ggm-commerce'); ?></h2>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="comparison_max_products"><?php esc_html_e('Maximum Products', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="number" id="comparison_max_products" min="2" max="10" step="1"
                                       value="<?php echo esc_attr($widget_controls['comparison_max_products'] ?? '4'); ?>"
                                       style="width: 80px;">
                                <p class="description">
                                    <?php esc_html_e('Maximum number of products customers can compare at once (2-10).', 'ggm-commerce'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="floating-bar-toggle"><?php esc_html_e('Floating Comparison Bar', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <?php if (!$comparison_premium_active) : ?>
                                    <div style="display: flex; align-items: center; gap: 10px;">
                                        <span class="dashicons dashicons-lock" style="color: #999;"></span>
                                        <label style="color: #999;">
                                            <input type="checkbox" disabled /> <?php esc_html_e('Show floating comparison bar', 'ggm-commerce'); ?>
                                        </label>
                                    </div>
                                    <p class="description" style="color: #999;">
                                        <strong><?php esc_html_e('Premium Feature:', 'ggm-commerce'); ?></strong> <?php esc_html_e('Activate the "Product Comparison" premium widget to enable this feature.', 'ggm-commerce'); ?>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>"><?php esc_html_e('Go to Activation', 'ggm-commerce'); ?></a>
                                    </p>
                                <?php else : ?>
                                    <div style="display: flex; align-items: center; gap: 15px;">
                                        <!-- Toggle Switch -->
                                        <label class="ggmc-toggle-switch">
                                            <input type="checkbox" id="floating-bar-toggle" <?php checked($show_floating_bar, '1'); ?>>
                                            <span class="ggmc-toggle-slider"></span>
                                        </label>

                                        <!-- Status Label -->
                                        <span id="floating-bar-status" style="font-weight: 600; color: <?php echo $show_floating_bar === '1' ? '#059669' : '#6b7280'; ?>;">
                                            <?php echo $show_floating_bar === '1' ? esc_html__('Enabled', 'ggm-commerce') : esc_html__('Disabled', 'ggm-commerce'); ?>
                                        </span>
                                    </div>
                                    <p class="description">
                                        <?php esc_html_e('Shows a bar at the bottom of the page with comparison count and quick actions.', 'ggm-commerce'); ?>
                                    </p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>

                    <?php if ($comparison_premium_active) : ?>
                    <!-- Bar Styling Section -->
                    <h3 style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;"><?php esc_html_e('Bar Styling', 'ggm-commerce'); ?></h3>

                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e('Background Gradient', 'ggm-commerce'); ?></th>
                            <td>
                                <div style="display: flex; gap: 30px; align-items: flex-start; flex-wrap: wrap;">
                                    <div>
                                        <label style="display: block; margin-bottom: 5px; font-weight: 500;"><?php esc_html_e('Start Color', 'ggm-commerce'); ?></label>
                                        <input type="text" class="ggmc-color-picker" id="compare_bar_bg_start"
                                               value="<?php echo esc_attr($widget_controls['compare_bar_bg_start'] ?? '#1e40af'); ?>">
                                    </div>
                                    <div>
                                        <label style="display: block; margin-bottom: 5px; font-weight: 500;"><?php esc_html_e('End Color', 'ggm-commerce'); ?></label>
                                        <input type="text" class="ggmc-color-picker" id="compare_bar_bg_end"
                                               value="<?php echo esc_attr($widget_controls['compare_bar_bg_end'] ?? '#3b82f6'); ?>">
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Text Color', 'ggm-commerce'); ?></th>
                            <td>
                                <input type="text" class="ggmc-color-picker" id="compare_bar_text_color"
                                       value="<?php echo esc_attr($widget_controls['compare_bar_text_color'] ?? '#ffffff'); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Button Colors', 'ggm-commerce'); ?></th>
                            <td>
                                <div style="display: flex; gap: 30px; align-items: flex-start; flex-wrap: wrap;">
                                    <div>
                                        <label style="display: block; margin-bottom: 5px; font-weight: 500;"><?php esc_html_e('Background', 'ggm-commerce'); ?></label>
                                        <input type="text" class="ggmc-color-picker" id="compare_bar_button_bg"
                                               value="<?php echo esc_attr($widget_controls['compare_bar_button_bg'] ?? '#ffffff'); ?>">
                                    </div>
                                    <div>
                                        <label style="display: block; margin-bottom: 5px; font-weight: 500;"><?php esc_html_e('Text', 'ggm-commerce'); ?></label>
                                        <input type="text" class="ggmc-color-picker" id="compare_bar_button_text"
                                               value="<?php echo esc_attr($widget_controls['compare_bar_button_text'] ?? '#1e40af'); ?>">
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Border Radius', 'ggm-commerce'); ?></th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <input type="range" id="compare_bar_border_radius" min="0" max="24" step="1"
                                           value="<?php echo esc_attr($widget_controls['compare_bar_border_radius'] ?? '0'); ?>"
                                           style="width: 200px;">
                                    <span id="compare_bar_radius_value"><?php echo esc_html($widget_controls['compare_bar_border_radius'] ?? '0'); ?>px</span>
                                </div>
                            </td>
                        </tr>
                    </table>

                    <!-- Comparison Messages Section -->
                    <h3 style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;"><?php esc_html_e('Message Text', 'ggm-commerce'); ?></h3>
                    <p class="description" style="margin-bottom: 15px;"><?php esc_html_e('Customize comparison notification text. Leave blank to use defaults.', 'ggm-commerce'); ?></p>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="msg_added_to_compare"><?php esc_html_e('Added to Comparison', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="msg_added_to_compare" class="regular-text"
                                       value="<?php echo esc_attr($widget_controls['msg_added_to_compare'] ?? ''); ?>"
                                       placeholder="<?php esc_attr_e('Product added to comparison.', 'ggm-commerce'); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="msg_removed_from_compare"><?php esc_html_e('Removed from Comparison', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="msg_removed_from_compare" class="regular-text"
                                       value="<?php echo esc_attr($widget_controls['msg_removed_from_compare'] ?? ''); ?>"
                                       placeholder="<?php esc_attr_e('Product removed from comparison.', 'ggm-commerce'); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="msg_max_compare"><?php esc_html_e('Max Comparison Reached', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="msg_max_compare" class="regular-text"
                                       value="<?php echo esc_attr($widget_controls['msg_max_compare'] ?? ''); ?>"
                                       placeholder="<?php esc_attr_e('Maximum of {max} products can be compared.', 'ggm-commerce'); ?>">
                                <p class="description"><?php esc_html_e('Use {max} as a placeholder for the maximum number.', 'ggm-commerce'); ?></p>
                            </td>
                        </tr>
                    </table>
                    <?php endif; ?>

                    <p style="margin-top: 20px;">
                        <button type="button" class="button button-primary" id="save-compare-bar-styles"><?php esc_html_e('Save Changes', 'ggm-commerce'); ?></button>
                    </p>
                    <div id="compare-bar-styles-status" style="margin: 20px 0;"></div>
                    <div id="floating-bar-settings-status" style="margin: 20px 0;"></div>
                </div>

                <!-- Wishlist Settings -->
                <div class="card">
                    <h2><?php esc_html_e('Wishlist', 'ggm-commerce'); ?></h2>

                    <?php if (!$wishlist_premium_active) : ?>
                        <p style="color: #999;">
                            <span class="dashicons dashicons-lock" style="color: #999;"></span>
                            <strong><?php esc_html_e('Premium Feature:', 'ggm-commerce'); ?></strong>
                            <?php esc_html_e('Activate the "Wishlist" premium widget to configure these settings.', 'ggm-commerce'); ?>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>"><?php esc_html_e('Go to Activation', 'ggm-commerce'); ?></a>
                        </p>
                    <?php else : ?>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="wishlist_max_lists"><?php esc_html_e('Maximum Wishlists', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="number" id="wishlist_max_lists" min="1" max="20" step="1"
                                       value="<?php echo esc_attr($widget_controls['wishlist_max_lists'] ?? '5'); ?>"
                                       style="width: 80px;">
                                <p class="description">
                                    <?php esc_html_e('Maximum number of wishlists each customer can create (1-20). Guests are limited to 1 wishlist.', 'ggm-commerce'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="wishlist-sharing-toggle"><?php esc_html_e('Enable Sharing', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <!-- Toggle Switch -->
                                    <label class="ggmc-toggle-switch">
                                        <input type="checkbox" id="wishlist-sharing-toggle" <?php checked($widget_controls['wishlist_sharing_enabled'] ?? '', '1'); ?>>
                                        <span class="ggmc-toggle-slider"></span>
                                    </label>

                                    <!-- Status Label -->
                                    <span id="wishlist-sharing-status" style="font-weight: 600; color: <?php echo ($widget_controls['wishlist_sharing_enabled'] ?? '') === '1' ? '#059669' : '#6b7280'; ?>;">
                                        <?php echo ($widget_controls['wishlist_sharing_enabled'] ?? '') === '1' ? esc_html__('Enabled', 'ggm-commerce') : esc_html__('Disabled', 'ggm-commerce'); ?>
                                    </span>
                                </div>
                                <p class="description">
                                    <?php esc_html_e('Allow customers to generate shareable links for their wishlists.', 'ggm-commerce'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>

                    <p style="margin-top: 20px;">
                        <button type="button" class="button button-primary" id="save-wishlist-settings"><?php esc_html_e('Save Changes', 'ggm-commerce'); ?></button>
                    </p>
                    <div id="wishlist-settings-status" style="margin: 20px 0;"></div>

                    <?php endif; ?>
                </div>

                <!-- Cart Notifications Card -->
                <div class="card">
                    <h2><?php esc_html_e('Cart Notifications', 'ggm-commerce'); ?></h2>
                    <p><?php esc_html_e('Configure the appearance and behavior of notification messages.', 'ggm-commerce'); ?></p>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="notifications-enabled"><?php esc_html_e('Enable Notifications', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <label class="ggmc-toggle-switch">
                                        <input type="checkbox" id="notifications-enabled" <?php checked($widget_controls['notifications_enabled'] ?? '1', '1'); ?>>
                                        <span class="ggmc-toggle-slider"></span>
                                    </label>
                                    <span id="notifications-status" style="font-weight: 600; color: <?php echo ($widget_controls['notifications_enabled'] ?? '1') === '1' ? '#059669' : '#6b7280'; ?>">
                                        <?php echo ($widget_controls['notifications_enabled'] ?? '1') === '1' ? esc_html__('Enabled', 'ggm-commerce') : esc_html__('Disabled', 'ggm-commerce'); ?>
                                    </span>
                                </div>
                                <p class="description"><?php esc_html_e('Show notification messages when products are added to cart or comparison.', 'ggm-commerce'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="notifications-position"><?php esc_html_e('Position', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <select id="notifications-position" style="min-width: 200px;">
                                    <option value="top-right" <?php selected($widget_controls['notifications_position'] ?? 'top-right', 'top-right'); ?>><?php esc_html_e('Top Right', 'ggm-commerce'); ?></option>
                                    <option value="top-left" <?php selected($widget_controls['notifications_position'] ?? '', 'top-left'); ?>><?php esc_html_e('Top Left', 'ggm-commerce'); ?></option>
                                    <option value="bottom-right" <?php selected($widget_controls['notifications_position'] ?? '', 'bottom-right'); ?>><?php esc_html_e('Bottom Right', 'ggm-commerce'); ?></option>
                                    <option value="bottom-left" <?php selected($widget_controls['notifications_position'] ?? '', 'bottom-left'); ?>><?php esc_html_e('Bottom Left', 'ggm-commerce'); ?></option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Display Duration', 'ggm-commerce'); ?></th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <input type="range" id="notifications-duration" min="1000" max="10000" step="500"
                                           value="<?php echo esc_attr($widget_controls['notifications_duration'] ?? '3000'); ?>"
                                           style="width: 200px;">
                                    <span id="duration-value"><?php echo esc_html(($widget_controls['notifications_duration'] ?? 3000) / 1000); ?></span> <?php esc_html_e('seconds', 'ggm-commerce'); ?>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Colors', 'ggm-commerce'); ?></th>
                            <td>
                                <div style="display: flex; gap: 30px; align-items: flex-start; flex-wrap: wrap;">
                                    <div>
                                        <label style="display: block; margin-bottom: 5px; font-weight: 500;"><?php esc_html_e('Background', 'ggm-commerce'); ?></label>
                                        <input type="text" class="ggmc-color-picker" id="notifications_bg_color"
                                               value="<?php echo esc_attr($widget_controls['notifications_bg_color'] ?? '#ffffff'); ?>">
                                    </div>
                                    <div>
                                        <label style="display: block; margin-bottom: 5px; font-weight: 500;"><?php esc_html_e('Text', 'ggm-commerce'); ?></label>
                                        <input type="text" class="ggmc-color-picker" id="notifications_text_color"
                                               value="<?php echo esc_attr($widget_controls['notifications_text_color'] ?? '#374151'); ?>">
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php esc_html_e('Border Radius', 'ggm-commerce'); ?></th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <input type="range" id="notifications_border_radius" min="0" max="24" step="1"
                                           value="<?php echo esc_attr($widget_controls['notifications_border_radius'] ?? '8'); ?>"
                                           style="width: 200px;">
                                    <span id="notifications_radius_value"><?php echo esc_html($widget_controls['notifications_border_radius'] ?? '8'); ?>px</span>
                                </div>
                            </td>
                        </tr>
                    </table>

                    <!-- Cart Message Text Section -->
                    <h3 style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;"><?php esc_html_e('Message Text', 'ggm-commerce'); ?></h3>
                    <p class="description" style="margin-bottom: 15px;"><?php esc_html_e('Customize cart notification text. Leave blank to use defaults.', 'ggm-commerce'); ?></p>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="msg_added_to_cart"><?php esc_html_e('Added to Cart', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="msg_added_to_cart" class="regular-text"
                                       value="<?php echo esc_attr($widget_controls['msg_added_to_cart'] ?? ''); ?>"
                                       placeholder="<?php esc_attr_e('Product added to cart.', 'ggm-commerce'); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="msg_select_options"><?php esc_html_e('Select Options', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="msg_select_options" class="regular-text"
                                       value="<?php echo esc_attr($widget_controls['msg_select_options'] ?? ''); ?>"
                                       placeholder="<?php esc_attr_e('Please select product options before adding to cart.', 'ggm-commerce'); ?>">
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="msg_error"><?php esc_html_e('Error Message', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <input type="text" id="msg_error" class="regular-text"
                                       value="<?php echo esc_attr($widget_controls['msg_error'] ?? ''); ?>"
                                       placeholder="<?php esc_attr_e('An error occurred. Please try again.', 'ggm-commerce'); ?>">
                            </td>
                        </tr>
                    </table>

                    <p style="margin-top: 20px;">
                        <button type="button" class="button button-primary" id="save-notification-settings"><?php esc_html_e('Save Changes', 'ggm-commerce'); ?></button>
                    </p>
                    <div id="notification-settings-status" style="margin: 20px 0;"></div>
                </div>

                <!-- Branding Settings -->
                <div class="card">
                    <h2><?php esc_html_e('Branding', 'ggm-commerce'); ?></h2>

                    <?php
                    $branding_can_disable = false;
                    if (function_exists('ggm_commerce_license')) {
                        $license = ggm_commerce_license();
                        $branding_can_disable = $license->is_license_valid() && $license->get_widget_limit() === 0;
                    }
                    $powered_by_disabled = isset($widget_controls['powered_by_disabled']) && $widget_controls['powered_by_disabled'] === '1';
                    ?>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="powered-by-toggle"><?php esc_html_e('"Powered by Goose" Footer', 'ggm-commerce'); ?></label>
                            </th>
                            <td>
                                <?php if (!$branding_can_disable) : ?>
                                    <div style="display: flex; align-items: center; gap: 10px;">
                                        <span class="dashicons dashicons-lock" style="color: #999;"></span>
                                        <label style="color: #999;">
                                            <input type="checkbox" disabled checked /> <?php esc_html_e('Show "Powered by Goose" footer on all pages', 'ggm-commerce'); ?>
                                        </label>
                                    </div>
                                    <p class="description" style="color: #999;">
                                        <strong><?php esc_html_e('Unlimited Plan:', 'ggm-commerce'); ?></strong> <?php esc_html_e('Upgrade to the Unlimited plan to hide the "Powered by Goose" footer branding.', 'ggm-commerce'); ?>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>"><?php esc_html_e('Go to Activation', 'ggm-commerce'); ?></a>
                                    </p>
                                <?php else : ?>
                                    <div style="display: flex; align-items: center; gap: 15px;">
                                        <label class="ggmc-toggle-switch">
                                            <input type="checkbox" id="powered-by-toggle" <?php checked(!$powered_by_disabled); ?>>
                                            <span class="ggmc-toggle-slider"></span>
                                        </label>

                                        <span id="powered-by-status" style="font-weight: 600; color: <?php echo !$powered_by_disabled ? '#059669' : '#6b7280'; ?>;">
                                            <?php echo !$powered_by_disabled ? esc_html__('Showing', 'ggm-commerce') : esc_html__('Hidden', 'ggm-commerce'); ?>
                                        </span>
                                    </div>
                                    <p class="description">
                                        <?php esc_html_e('Display the "Powered by Goose" branding footer on your site. Hiding the footer is available with your Unlimited plan.', 'ggm-commerce'); ?>
                                    </p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>

                    <div id="powered-by-settings-status" style="margin: 20px 0;"></div>
                </div>

                    </div><!-- .ggmc-settings-main -->

                    <!-- Need Help Sidebar -->
                    <div class="ggmc-settings-help">
                        <h3><span class="dashicons dashicons-editor-help"></span> <?php esc_html_e('Need Help?', 'ggm-commerce'); ?></h3>

                        <h4><?php esc_html_e('Widget Default Styles', 'ggm-commerce'); ?></h4>
                        <p><?php esc_html_e('Controls the initial styling for newly added Goose Commerce widgets. Existing widgets are never affected.', 'ggm-commerce'); ?></p>

                        <h4><?php esc_html_e('Product Comparison', 'ggm-commerce'); ?></h4>
                        <p><?php esc_html_e('Configure the floating comparison bar that appears when customers add products to compare. Customize colors, styling, and notification messages.', 'ggm-commerce'); ?></p>

                        <h4><?php esc_html_e('Cart Notifications', 'ggm-commerce'); ?></h4>
                        <p><?php esc_html_e('Toast notifications appear when products are added to cart. Configure position, duration, colors, and customize the message text.', 'ggm-commerce'); ?></p>

                        <h4><?php esc_html_e('Branding', 'ggm-commerce'); ?></h4>
                        <p><?php esc_html_e('The "Powered by Goose" footer appears on all pages. Users with an Unlimited plan can toggle this off.', 'ggm-commerce'); ?></p>

                        <div class="ggmc-help-tip">
                            <span class="dashicons dashicons-lightbulb"></span>
                            <strong><?php esc_html_e('Tip:', 'ggm-commerce'); ?></strong> <?php esc_html_e('Leave message text fields blank to use translatable defaults, or enter custom text to override.', 'ggm-commerce'); ?>
                        </div>
                    </div><!-- .ggmc-settings-help -->

                </div><!-- .ggmc-settings-layout -->

                <!-- Toggle Switch CSS -->

                <!-- Toggle Script -->
                <script>
                jQuery(document).ready(function($) {
                    const toggle = $('#widget-defaults-toggle');
                    const status = $('#toggle-status');
                    const description = $('#toggle-description');
                    const statusDiv = $('#default-styles-status');

                    toggle.on('change', function() {
                        const isEnabled = $(this).is(':checked');
                        const action = isEnabled ? 'ggm_commerce_apply_all_defaults' : 'ggm_commerce_remove_all_defaults';

                        // Disable toggle during AJAX
                        toggle.prop('disabled', true);
                        statusDiv.html('<div class="notice notice-info"><p>Updating settings...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: action,
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_default_styles')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    const successMsg = isEnabled
                                        ? '✅ Professional defaults enabled for NEW widgets!'
                                        : '✅ Defaults disabled. NEW widgets will inherit from Site Settings.';
                                    statusDiv.html('<div class="notice notice-success"><p><strong>' + successMsg + '</strong></p></div>');

                                    // Update status text and color
                                    status.text(isEnabled ? 'Professional Defaults' : 'Site Settings Only');
                                    status.css('color', isEnabled ? '#059669' : '#6b7280');

                                    // Update description
                                    description.text(isEnabled
                                        ? 'New widgets will start with professional styling (Poppins font, blue colors, consistent spacing).'
                                        : 'New widgets will start blank and inherit from Elementor Site Settings.'
                                    );

                                    toggle.prop('disabled', false);

                                    setTimeout(function() {
                                        statusDiv.fadeOut();
                                    }, 3000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> ' + response.data.message + '</p></div>');
                                    toggle.prop('checked', !isEnabled); // Revert toggle
                                    toggle.prop('disabled', false);
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to update settings. Please try again.</p></div>');
                                toggle.prop('checked', !isEnabled); // Revert toggle
                                toggle.prop('disabled', false);
                            }
                        });
                    });

                    // Floating bar toggle handler
                    const floatingBarToggle = $('#floating-bar-toggle');
                    const floatingBarStatus = $('#floating-bar-status');
                    const floatingBarStatusDiv = $('#floating-bar-settings-status');

                    floatingBarToggle.on('change', function() {
                        const isEnabled = $(this).is(':checked');

                        floatingBarToggle.prop('disabled', true);
                        floatingBarStatusDiv.html('<div class="notice notice-info"><p>Updating settings...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_update_floating_bar',
                                enabled: isEnabled ? '1' : '0',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_floating_bar')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    floatingBarStatusDiv.html('<div class="notice notice-success"><p><strong>✅ Settings updated!</strong></p></div>');
                                    floatingBarStatus.text(isEnabled ? 'Enabled' : 'Disabled');
                                    floatingBarStatus.css('color', isEnabled ? '#059669' : '#6b7280');
                                    floatingBarToggle.prop('disabled', false);

                                    setTimeout(function() {
                                        floatingBarStatusDiv.fadeOut();
                                    }, 3000);
                                } else {
                                    floatingBarStatusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> ' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                    floatingBarToggle.prop('checked', !isEnabled);
                                    floatingBarToggle.prop('disabled', false);
                                }
                            },
                            error: function() {
                                floatingBarStatusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to update settings. Please try again.</p></div>');
                                floatingBarToggle.prop('checked', !isEnabled);
                                floatingBarToggle.prop('disabled', false);
                            }
                        });
                    });

                    // Widgets prioritization toggle handler
                    const widgetsPrioritizedToggle = $('#widgets-prioritized-toggle');
                    const widgetsPrioritizedStatus = $('#widgets-prioritized-status');
                    const defaultStylesStatusDiv = $('#default-styles-status');

                    widgetsPrioritizedToggle.on('change', function() {
                        const isEnabled = $(this).is(':checked');

                        widgetsPrioritizedToggle.prop('disabled', true);
                        defaultStylesStatusDiv.html('<div class="notice notice-info"><p>Updating settings...</p></div>').show();

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_update_widgets_prioritized',
                                enabled: isEnabled ? '1' : '0',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_widgets_prioritized')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    defaultStylesStatusDiv.html('<div class="notice notice-success"><p><strong>✅ Settings updated!</strong> Refresh the Elementor editor to see changes.</p></div>');
                                    widgetsPrioritizedStatus.text(isEnabled ? 'Enabled' : 'Disabled');
                                    widgetsPrioritizedStatus.css('color', isEnabled ? '#059669' : '#6b7280');
                                    widgetsPrioritizedToggle.prop('disabled', false);

                                    setTimeout(function() {
                                        defaultStylesStatusDiv.fadeOut();
                                    }, 5000);
                                } else {
                                    defaultStylesStatusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> ' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                    widgetsPrioritizedToggle.prop('checked', !isEnabled);
                                    widgetsPrioritizedToggle.prop('disabled', false);
                                }
                            },
                            error: function() {
                                defaultStylesStatusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to update settings. Please try again.</p></div>');
                                widgetsPrioritizedToggle.prop('checked', !isEnabled);
                                widgetsPrioritizedToggle.prop('disabled', false);
                            }
                        });
                    });

                    // Initialize WordPress color pickers
                    if ($.fn.wpColorPicker) {
                        $('.ggmc-color-picker').wpColorPicker();
                    }

                    // Range slider value display handlers
                    $('#compare_bar_border_radius').on('input', function() {
                        $('#compare_bar_radius_value').text($(this).val() + 'px');
                    });

                    $('#notifications_border_radius').on('input', function() {
                        $('#notifications_radius_value').text($(this).val() + 'px');
                    });

                    $('#notifications-duration').on('input', function() {
                        $('#duration-value').text(($(this).val() / 1000));
                    });

                    // Product Comparison save handler (bar styles + comparison messages)
                    $('#save-compare-bar-styles').on('click', function() {
                        var $btn = $(this);
                        var $status = $('#compare-bar-styles-status');

                        $btn.prop('disabled', true);
                        $status.html('<div class="notice notice-info"><p>Saving...</p></div>').show();

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_save_compare_bar_styles',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_compare_bar_styles')); ?>',
                                // General comparison settings
                                comparison_max_products: $('#comparison_max_products').val(),
                                // Bar styling
                                compare_bar_bg_start: $('#compare_bar_bg_start').val(),
                                compare_bar_bg_end: $('#compare_bar_bg_end').val(),
                                compare_bar_text_color: $('#compare_bar_text_color').val(),
                                compare_bar_button_bg: $('#compare_bar_button_bg').val(),
                                compare_bar_button_text: $('#compare_bar_button_text').val(),
                                compare_bar_border_radius: $('#compare_bar_border_radius').val(),
                                // Comparison message text
                                msg_added_to_compare: $('#msg_added_to_compare').val(),
                                msg_removed_from_compare: $('#msg_removed_from_compare').val(),
                                msg_max_compare: $('#msg_max_compare').val()
                            },
                            success: function(response) {
                                if (response.success) {
                                    $status.html('<div class="notice notice-success"><p><strong>✅ Product comparison settings saved!</strong></p></div>');
                                    setTimeout(function() { $status.fadeOut(); }, 3000);
                                } else {
                                    $status.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> ' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                }
                                $btn.prop('disabled', false);
                            },
                            error: function() {
                                $status.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to save settings.</p></div>');
                                $btn.prop('disabled', false);
                            }
                        });
                    });

                    // Cart Notifications save handler (notification settings + cart messages)
                    $('#save-notification-settings').on('click', function() {
                        var $btn = $(this);
                        var $status = $('#notification-settings-status');

                        $btn.prop('disabled', true);
                        $status.html('<div class="notice notice-info"><p>Saving...</p></div>').show();

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_save_notification_settings',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_notification_settings')); ?>',
                                notifications_enabled: $('#notifications-enabled').is(':checked') ? '1' : '0',
                                notifications_position: $('#notifications-position').val(),
                                notifications_duration: $('#notifications-duration').val(),
                                notifications_bg_color: $('#notifications_bg_color').val(),
                                notifications_text_color: $('#notifications_text_color').val(),
                                notifications_border_radius: $('#notifications_border_radius').val(),
                                // Cart message text
                                msg_added_to_cart: $('#msg_added_to_cart').val(),
                                msg_select_options: $('#msg_select_options').val(),
                                msg_error: $('#msg_error').val()
                            },
                            success: function(response) {
                                if (response.success) {
                                    $status.html('<div class="notice notice-success"><p><strong>✅ Cart notification settings saved!</strong></p></div>');
                                    // Update status label
                                    var isEnabled = $('#notifications-enabled').is(':checked');
                                    $('#notifications-status').text(isEnabled ? 'Enabled' : 'Disabled');
                                    $('#notifications-status').css('color', isEnabled ? '#059669' : '#6b7280');
                                    setTimeout(function() { $status.fadeOut(); }, 3000);
                                } else {
                                    $status.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> ' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                }
                                $btn.prop('disabled', false);
                            },
                            error: function() {
                                $status.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to save settings.</p></div>');
                                $btn.prop('disabled', false);
                            }
                        });
                    });

                    // Wishlist settings save handler
                    $('#save-wishlist-settings').on('click', function() {
                        var $btn = $(this);
                        var $status = $('#wishlist-settings-status');

                        $btn.prop('disabled', true);
                        $status.html('<div class="notice notice-info"><p>Saving...</p></div>').show();

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_save_wishlist_settings',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_wishlist_settings')); ?>',
                                wishlist_max_lists: $('#wishlist_max_lists').val(),
                                wishlist_sharing_enabled: $('#wishlist-sharing-toggle').is(':checked') ? '1' : '0'
                            },
                            success: function(response) {
                                if (response.success) {
                                    $status.html('<div class="notice notice-success"><p><strong>✅ Wishlist settings saved!</strong></p></div>');
                                    // Update sharing status label
                                    var isEnabled = $('#wishlist-sharing-toggle').is(':checked');
                                    $('#wishlist-sharing-status').text(isEnabled ? 'Enabled' : 'Disabled');
                                    $('#wishlist-sharing-status').css('color', isEnabled ? '#059669' : '#6b7280');
                                    setTimeout(function() { $status.fadeOut(); }, 3000);
                                } else {
                                    $status.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> ' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                }
                                $btn.prop('disabled', false);
                            },
                            error: function() {
                                $status.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to save settings.</p></div>');
                                $btn.prop('disabled', false);
                            }
                        });
                    });

                    // Wishlist sharing toggle - update status label on change
                    $('#wishlist-sharing-toggle').on('change', function() {
                        var isEnabled = $(this).is(':checked');
                        $('#wishlist-sharing-status').text(isEnabled ? 'Enabled' : 'Disabled');
                        $('#wishlist-sharing-status').css('color', isEnabled ? '#059669' : '#6b7280');
                    });

                    // Powered by Goose branding toggle
                    $('#powered-by-toggle').on('change', function() {
                        var $toggle = $(this);
                        var isShowing = $toggle.is(':checked');
                        var $status = $('#powered-by-settings-status');

                        $toggle.prop('disabled', true);
                        $status.html('<div class="notice notice-info"><p>Saving...</p></div>').show();

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_update_powered_by',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_powered_by')); ?>',
                                disabled: isShowing ? '0' : '1'
                            },
                            success: function(response) {
                                if (response.success) {
                                    $status.html('<div class="notice notice-success"><p><strong>' + response.data.message + '</strong></p></div>');
                                    $('#powered-by-status').text(isShowing ? 'Showing' : 'Hidden');
                                    $('#powered-by-status').css('color', isShowing ? '#059669' : '#6b7280');
                                    setTimeout(function() { $status.fadeOut(); }, 3000);
                                } else {
                                    $status.html('<div class="notice notice-error"><p><strong>Error:</strong> ' + (response.data ? response.data.message : 'Unknown error') + '</p></div>');
                                    $toggle.prop('checked', !isShowing); // Revert toggle
                                }
                                $toggle.prop('disabled', false);
                            },
                            error: function() {
                                $status.html('<div class="notice notice-error"><p><strong>Error:</strong> Failed to save setting.</p></div>');
                                $toggle.prop('checked', !isShowing); // Revert toggle
                                $toggle.prop('disabled', false);
                            }
                        });
                    });
                });
                </script>

            <?php elseif ($active_tab == 'address-settings') : ?>
                <!-- Address Settings Tab -->
                <?php
                // Get current address settings
                $allow_multiple_billing = get_option('ggm_commerce_allow_multiple_billing', false);
                $allow_multiple_shipping = get_option('ggm_commerce_allow_multiple_shipping', false);
                ?>

                <div class="card">
                    <h2>Customer Address Settings</h2>
                    <p>Control how customers can manage their billing and shipping addresses.</p>

                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="multiple-billing-toggle">Multiple Billing Addresses</label>
                            </th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <!-- Toggle Switch -->
                                    <label class="ggmc-address-toggle-switch">
                                        <input type="checkbox" id="multiple-billing-toggle" <?php checked($allow_multiple_billing); ?>>
                                        <span class="ggmc-address-toggle-slider"></span>
                                    </label>

                                    <!-- Status Label -->
                                    <span id="billing-status" style="font-weight: 600; color: <?php echo $allow_multiple_billing ? '#059669' : '#6b7280'; ?>;">
                                        <?php echo $allow_multiple_billing ? 'Enabled' : 'Disabled'; ?>
                                    </span>
                                </div>
                                <p class="description" id="billing-description">
                                    <?php if ($allow_multiple_billing): ?>
                                        Customers can add and manage multiple billing addresses in their account.
                                    <?php else: ?>
                                        Customers can only have one billing address.
                                    <?php endif; ?>
                                </p>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="multiple-shipping-toggle">Multiple Shipping Addresses</label>
                            </th>
                            <td>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <!-- Toggle Switch -->
                                    <label class="ggmc-address-toggle-switch">
                                        <input type="checkbox" id="multiple-shipping-toggle" <?php checked($allow_multiple_shipping); ?>>
                                        <span class="ggmc-address-toggle-slider"></span>
                                    </label>

                                    <!-- Status Label -->
                                    <span id="shipping-status" style="font-weight: 600; color: <?php echo $allow_multiple_shipping ? '#059669' : '#6b7280'; ?>;">
                                        <?php echo $allow_multiple_shipping ? 'Enabled' : 'Disabled'; ?>
                                    </span>
                                </div>
                                <p class="description" id="shipping-description">
                                    <?php if ($allow_multiple_shipping): ?>
                                        Customers can add and manage multiple shipping addresses in their account.
                                    <?php else: ?>
                                        Customers can only have one shipping address.
                                    <?php endif; ?>
                                </p>
                            </td>
                        </tr>
                    </table>

                    <div id="address-settings-status" style="margin: 20px 0;"></div>

                    <hr>

                    <h3>How This Works</h3>
                    <div style="background: #f9f9f9; padding: 15px; border-left: 4px solid #2563eb;">
                        <p style="margin: 5px 0;"><strong>When Disabled (Single Address):</strong></p>
                        <ul style="margin: 10px 0 10px 20px;">
                            <li>Customers see standard billing/shipping address fields in checkout</li>
                            <li>Account dashboard shows one editable address of each type</li>
                            <li>Simple, traditional checkout experience</li>
                        </ul>

                        <p style="margin: 15px 0 5px 0;"><strong>When Enabled (Multiple Addresses):</strong></p>
                        <ul style="margin: 10px 0 10px 20px;">
                            <li>Customers can save multiple addresses in their account</li>
                            <li>Checkout shows dropdown to select from saved addresses</li>
                            <li>Customers can add new addresses during checkout</li>
                            <li>One address can be set as default for each type</li>
                            <li>Account dashboard allows adding, editing, and deleting addresses</li>
                        </ul>

                        <p style="margin: 15px 0 5px 0;"><strong>Auto-Population:</strong></p>
                        <ul style="margin: 10px 0 10px 20px;">
                            <li>Logged-in customers have their checkout forms auto-filled with default addresses</li>
                            <li>Works with both single and multiple address modes</li>
                            <li>Saves time and reduces errors for returning customers</li>
                        </ul>
                    </div>
                </div>

                <!-- Toggle Switch CSS -->

                <!-- Toggle Script -->
                <script>
                jQuery(document).ready(function($) {
                    // Multiple Billing Addresses Toggle
                    $('#multiple-billing-toggle').on('change', function() {
                        const isEnabled = $(this).is(':checked');
                        const toggle = $(this);
                        const status = $('#billing-status');
                        const description = $('#billing-description');
                        const statusDiv = $('#address-settings-status');

                        // Disable toggle during AJAX
                        toggle.prop('disabled', true);
                        statusDiv.html('<div class="notice notice-info"><p>Updating settings...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_toggle_multiple_billing',
                                enable: isEnabled ? 'yes' : 'no',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_address_settings')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    const successMsg = isEnabled
                                        ? '✅ Multiple billing addresses enabled!'
                                        : '✅ Multiple billing addresses disabled.';
                                    statusDiv.html('<div class="notice notice-success"><p><strong>' + successMsg + '</strong></p></div>');

                                    // Update status text and color
                                    status.text(isEnabled ? 'Enabled' : 'Disabled');
                                    status.css('color', isEnabled ? '#059669' : '#6b7280');

                                    // Update description
                                    description.text(isEnabled
                                        ? 'Customers can add and manage multiple billing addresses in their account.'
                                        : 'Customers can only have one billing address.'
                                    );

                                    toggle.prop('disabled', false);

                                    setTimeout(function() {
                                        statusDiv.fadeOut();
                                    }, 3000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to update setting.</p></div>');
                                    toggle.prop('checked', !isEnabled);
                                    toggle.prop('disabled', false);
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Request failed. Please try again.</p></div>');
                                toggle.prop('checked', !isEnabled);
                                toggle.prop('disabled', false);
                            }
                        });
                    });

                    // Multiple Shipping Addresses Toggle
                    $('#multiple-shipping-toggle').on('change', function() {
                        const isEnabled = $(this).is(':checked');
                        const toggle = $(this);
                        const status = $('#shipping-status');
                        const description = $('#shipping-description');
                        const statusDiv = $('#address-settings-status');

                        // Disable toggle during AJAX
                        toggle.prop('disabled', true);
                        statusDiv.html('<div class="notice notice-info"><p>Updating settings...</p></div>');

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'ggm_commerce_toggle_multiple_shipping',
                                enable: isEnabled ? 'yes' : 'no',
                                nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_address_settings')); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    const successMsg = isEnabled
                                        ? '✅ Multiple shipping addresses enabled!'
                                        : '✅ Multiple shipping addresses disabled.';
                                    statusDiv.html('<div class="notice notice-success"><p><strong>' + successMsg + '</strong></p></div>');

                                    // Update status text and color
                                    status.text(isEnabled ? 'Enabled' : 'Disabled');
                                    status.css('color', isEnabled ? '#059669' : '#6b7280');

                                    // Update description
                                    description.text(isEnabled
                                        ? 'Customers can add and manage multiple shipping addresses in their account.'
                                        : 'Customers can only have one shipping address.'
                                    );

                                    toggle.prop('disabled', false);

                                    setTimeout(function() {
                                        statusDiv.fadeOut();
                                    }, 3000);
                                } else {
                                    statusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Failed to update setting.</p></div>');
                                    toggle.prop('checked', !isEnabled);
                                    toggle.prop('disabled', false);
                                }
                            },
                            error: function() {
                                statusDiv.html('<div class="notice notice-error"><p><strong>❌ Error:</strong> Request failed. Please try again.</p></div>');
                                toggle.prop('checked', !isEnabled);
                                toggle.prop('disabled', false);
                            }
                        });
                    });
                });
                </script>



            <?php elseif ($active_tab == 'checkout-fields') : ?>
                <!-- Checkout Fields Tab -->
                <?php
                $is_checkout_fields_active = false;
                if ( function_exists( 'ggm_commerce_license' ) ) {
                    $license = ggm_commerce_license();
                    $is_checkout_fields_active = $license->is_widget_activated( 'checkout-fields' );
                }

                if ( ! $is_checkout_fields_active ) {
                    echo '<div style="background: #0F766E; color: white; padding: 15px 20px; border-radius: 6px; margin-bottom: 10px;">';
                    echo '<p style="margin: 0 0 8px 0;"><strong><span class="dashicons dashicons-lock" style="margin-right: 5px;"></span>Premium Feature Required</strong></p>';
                    echo '<p style="margin: 0; opacity: 0.9;">Custom Checkout Fields allows you to add custom fields to your checkout process — text, select, radio, checkbox, date, and more. Group fields and place them at various checkout positions.</p>';
                    echo '<p style="margin: 10px 0 0 0;"><a href="' . esc_url( admin_url( 'admin.php?page=ggmc-settings&tab=premium-components' ) ) . '" style="color: white; text-decoration: underline;">Activate this feature in Premium Components &rarr;</a></p>';
                    echo '</div>';
                } else {
                    ggm_commerce_render_checkout_fields_tab();
                }
                ?>

            <?php elseif ($active_tab == 'premium-components') : ?>
                <!-- Premium Components Tab -->
                <?php ggm_commerce_render_premium_widgets_tab(); ?>

            <?php elseif ($active_tab == 'legal') : ?>
                <!-- Legal / Compliance Tab -->
                <?php
                require_once plugin_dir_path( __FILE__ ) . 'admin-legal-tab.php';
                ggmc_render_legal_tab();
                ?>

            <?php elseif ($active_tab == 'google-merchant') : ?>
                <!-- Google Merchant Tab -->
                <?php
                // Check if viewing a specific feed
                $feed_id = isset($_GET['feed']) ? sanitize_key($_GET['feed']) : '';
                if ($feed_id) {
                    ggm_commerce_render_google_merchant_feed_edit($feed_id);
                } else {
                    ggm_commerce_render_google_merchant_tab();
                }
                ?>

            <?php endif; ?>
                </div><!-- /.ggmc-settings-content -->
            </div><!-- /.ggmc-settings-wrap -->
        </div><!-- /.wrap -->
        <?php
    }

    // CPT registration methods removed - plugin uses custom database tables only
    
    /**
     * Get the capability required for a menu item
     * Uses custom capabilities for shop roles, falls back to manage_options for non-shop users
     *
     * @param string $menu_type The menu type (dashboard, orders, products, etc.)
     * @return string The capability required
     */
    private function get_menu_capability($menu_type) {
        // Map menu types to custom capabilities
        $cap_map = [
            'dashboard' => 'ggmc_access_dashboard',
            'orders' => 'ggmc_manage_orders',
            'customers' => 'ggmc_view_customers',
            'products' => 'ggmc_manage_products',
            'categories' => 'ggmc_manage_categories',
            'tags' => 'ggmc_manage_categories',
            'attributes' => 'ggmc_manage_attributes',
            'variations' => 'ggmc_manage_variations',
            'reviews' => 'ggmc_manage_reviews',
            'settings' => 'ggmc_access_settings',
            'add_product' => 'ggmc_create_products',
            'edit_product' => 'ggmc_edit_products',
        ];

        $custom_cap = $cap_map[$menu_type] ?? 'ggmc_access_dashboard';

        // If user has the custom capability, use it
        // Otherwise fall back to manage_options (for admins without custom caps)
        if (current_user_can($custom_cap)) {
            return $custom_cap;
        }

        return 'manage_options';
    }

    /**
     * Register admin menu and submenus
     */
    public function admin_menu() {
        // Determine base capability - use custom cap if available, else manage_options
        $base_cap = current_user_can('ggmc_access_dashboard') ? 'ggmc_access_dashboard' : 'manage_options';

        // Main menu page
        add_menu_page(
            'Goose Dashboard',
            'Goose Commerce',
            $base_cap,
            'ggmc-plugin',
            array($this, 'admin_page'),
            'dashicons-cart',
            30
        );

        // First submenu replaces the default duplicate - rename to "Goose Dashboard"
        add_submenu_page(
            'ggmc-plugin',
            'Goose Dashboard',
            'Goose Dashboard',
            $base_cap,
            'ggmc-plugin',
            array($this, 'admin_page')
        );

        // Menu items in order: Orders, Customers, Products, Categories, Tags, Attributes, Reviews, Settings
        // Orders - for users with ggmc_manage_orders capability
        $orders_cap = current_user_can('ggmc_manage_orders') ? 'ggmc_manage_orders' : 'manage_options';
        add_submenu_page(
            'ggmc-plugin',
            'Orders',
            'Orders',
            $orders_cap,
            'ggmc-orders',
            array($this, 'orders_page')
        );

        // Customers - for users with ggmc_view_customers capability
        $customers_cap = current_user_can('ggmc_view_customers') ? 'ggmc_view_customers' : 'manage_options';
        add_submenu_page(
            'ggmc-plugin',
            'Customers',
            'Customers',
            $customers_cap,
            'ggmc-customers',
            array($this, 'customers_page')
        );

        // Products - for users with ggmc_manage_products capability
        $products_cap = current_user_can('ggmc_manage_products') ? 'ggmc_manage_products' : 'manage_options';
        add_submenu_page(
            'ggmc-plugin',
            'Products',
            'Products',
            $products_cap,
            'ggmc-products',
            array($this, 'products_page')
        );

        // Categories - for users with ggmc_manage_categories capability
        $categories_cap = current_user_can('ggmc_manage_categories') ? 'ggmc_manage_categories' : 'manage_options';
        add_submenu_page(
            'ggmc-plugin',
            'Categories',
            'Categories',
            $categories_cap,
            'ggmc-categories',
            array($this, 'categories_page')
        );

        // Tags - same as categories
        add_submenu_page(
            'ggmc-plugin',
            'Tags',
            'Tags',
            $categories_cap,
            'ggmc-tags',
            array($this, 'tags_page')
        );

        // Attributes - for users with ggmc_manage_attributes capability
        $attributes_cap = current_user_can('ggmc_manage_attributes') ? 'ggmc_manage_attributes' : 'manage_options';
        add_submenu_page(
            'ggmc-plugin',
            'Attributes',
            'Attributes',
            $attributes_cap,
            'ggmc-attributes',
            array($this, 'attributes_page')
        );

        // Only show Product Variations if premium feature is activated
        if ( class_exists( 'GGM_Commerce_License' ) && GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            $variations_cap = current_user_can('ggmc_manage_variations') ? 'ggmc_manage_variations' : 'manage_options';
            add_submenu_page(
                'ggmc-plugin',
                'Product Variations',
                'Variations',
                $variations_cap,
                'ggmc-variation-attributes',
                array($this, 'variation_attributes_page')
            );
        }

        // Reviews - for users with ggmc_manage_reviews capability
        $reviews_cap = current_user_can('ggmc_manage_reviews') ? 'ggmc_manage_reviews' : 'manage_options';
        add_submenu_page(
            'ggmc-plugin',
            'Reviews',
            'Reviews',
            $reviews_cap,
            'ggmc-reviews',
            array($this, 'reviews_page')
        );

        // Discounts & Vouchers - only show if premium feature is activated
        if ( class_exists( 'GGM_Commerce_Discounts' ) && GGM_Commerce_Discounts::is_activated() ) {
            add_submenu_page(
                'ggmc-plugin',
                __( 'Discounts & Vouchers', 'ggm-commerce' ),
                __( 'Discounts', 'ggm-commerce' ),
                'manage_options',
                'ggmc-discounts',
                array( $this, 'discounts_page' )
            );
        }

        // Checkout Fields - only show if premium feature is activated
        if ( class_exists( 'GGM_Commerce_Checkout_Fields' )
            && function_exists( 'ggm_commerce_license' )
            && ggm_commerce_license()->is_widget_activated( 'checkout-fields' )
        ) {
            add_submenu_page(
                'ggmc-plugin',
                __( 'Checkout Fields', 'ggm-commerce' ),
                __( 'Checkout Fields', 'ggm-commerce' ),
                'manage_options',
                'ggmc-checkout-fields',
                array( $this, 'checkout_fields_page' )
            );
        }

        // Subscriptions - only show if premium feature is activated
        if ( class_exists( 'GGM_Commerce_Subscriptions' ) && GGM_Commerce_Subscriptions::is_activated() ) {
            add_submenu_page(
                'ggmc-plugin',
                __( 'Subscriptions', 'ggm-commerce' ),
                __( 'Subscriptions', 'ggm-commerce' ),
                'manage_options',
                'ggmc-subscriptions',
                array( $this, 'subscriptions_page' )
            );
        }

        // Settings - for users with ggmc_access_settings capability
        $settings_cap = current_user_can('ggmc_access_settings') ? 'ggmc_access_settings' : 'manage_options';
        add_submenu_page(
            'ggmc-plugin',
            'Settings',
            'Settings',
            $settings_cap,
            'ggmc-settings',
            array($this, 'settings_page')
        );

        // Hidden pages (not shown in menu but accessible via direct URL)
        // Use 'options.php' as parent slug to avoid null path warnings, then hide via CSS
        $create_cap = current_user_can('ggmc_create_products') ? 'ggmc_create_products' : 'manage_options';
        add_submenu_page(
            'options.php',
            'Add Product',
            'Add Product',
            $create_cap,
            'ggmc-add-product',
            array($this, 'add_product_page')
        );

        $edit_cap = current_user_can('ggmc_edit_products') ? 'ggmc_edit_products' : 'manage_options';
        add_submenu_page(
            'options.php',
            'Edit Product',
            'Edit Product',
            $edit_cap,
            'ggmc-edit-product',
            array($this, 'edit_product_page')
        );
    }

    /**
     * Register plugin settings
     */
    public function register_settings() {
        // Include the settings file from the same directory
        $settings_file = plugin_dir_path(__FILE__) . 'settings.php';
        if (file_exists($settings_file)) {
            require_once $settings_file;
        }
    }

    /**
     * Handle product duplicate redirect early (before any output)
     */
    public function handle_product_duplicate_redirect() {
        // Only run on our products page with duplicate action
        if (!isset($_GET['page']) || $_GET['page'] !== 'ggmc-products') {
            return;
        }
        if (!isset($_GET['action']) || $_GET['action'] !== 'duplicate' || !isset($_GET['id'])) {
            return;
        }

        global $wpdb;
        $products_table = $wpdb->prefix . 'ggmc_products';
        $product_categories_table = $wpdb->prefix . 'ggmc_product_categories';
        $product_id = intval(wp_unslash($_GET['id']));

        // Verify nonce
        if (!wp_verify_nonce($_GET['_wpnonce'] ?? '', 'ggmc_duplicate_product_' . $product_id)) {
            // Don't redirect, let the page show an error
            return;
        }

        // Get the product to duplicate
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$products_table} WHERE id = %d",
            $product_id
        ));

        if (!$product) {
            return;
        }

        // Build duplicate data array - use correct column names and handle missing properties
        $duplicate_data = [
            'name' => ($product->name ?? '') . ' (Copy)',
            'slug' => '',  // Will be auto-generated on save
            'sku' => '',   // Must be unique, leave blank
            'description' => $product->description ?? '',
            'short_description' => $product->short_description ?? '',
            'price' => $product->price ?? 0,
            'sale_price' => $product->sale_price ?? null,
            'stock' => 0,  // Start with zero stock
            'weight' => $product->weight ?? null,
            'length' => $product->length ?? null,
            'width' => $product->width ?? null,
            'height' => $product->height ?? null,
            'status' => 'draft',  // Start as draft
            'product_type' => $product->product_type ?? 'simple',
            'featured_image_id' => $product->image_id ?? '',  // Correct column name
            'gallery_image_ids' => $product->gallery_ids ?? '',  // Correct column name
            'source_product_id' => $product_id,  // Track source for reference
        ];

        // Get categories for this product
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $categories = $wpdb->get_col($wpdb->prepare(
            "SELECT category_id FROM {$product_categories_table} WHERE product_id = %d",
            $product_id
        ));
        $duplicate_data['categories'] = $categories ?: [];

        // Get tags for this product
        $tags_table = $wpdb->prefix . 'ggmc_product_tags';
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $tags = $wpdb->get_col($wpdb->prepare(
            "SELECT tag_id FROM {$tags_table} WHERE product_id = %d",
            $product_id
        ));
        $duplicate_data['tags'] = $tags ?: [];

        // Get custom attributes for this product (if table exists)
        $attrs_table = $wpdb->prefix . 'ggmc_product_attribute_values';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $attrs_table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $attrs_table)) === $attrs_table;
        $custom_attrs = [];
        if ($attrs_table_exists) {
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
            $custom_attrs = $wpdb->get_results($wpdb->prepare(
                "SELECT attribute_id, value FROM {$attrs_table} WHERE product_id = %d",
                $product_id
            ));
        }
        $duplicate_data['custom_attributes'] = $custom_attrs ?: [];

        // If kit/build, get components
        if (in_array($product->product_type ?? '', ['kit', 'build'])) {
            $kits_manager = GGM_Commerce_Kits::get_instance();
            $existing_kit = $kits_manager->get_kit_by_product_id($product_id);
            if ($existing_kit) {
                $components = $kits_manager->get_kit_components($existing_kit->id);
                $duplicate_data['kit_components'] = [];
                foreach ($components as $comp) {
                    $duplicate_data['kit_components'][] = [
                        'product_id' => $comp->component_product_id,
                        'quantity' => $comp->quantity,
                    ];
                }
            }
        }

        // Store in transient (1 hour expiry)
        $transient_key = 'ggmc_duplicate_' . get_current_user_id();
        set_transient($transient_key, $duplicate_data, HOUR_IN_SECONDS);

        // Redirect to Add New Product page
        wp_safe_redirect(admin_url('admin.php?page=ggmc-add-product&duplicate=1'));
        exit;
    }

    /**
     * Main admin dashboard page
     */
    public function admin_page() {
        global $title;
        $title = 'Goose Dashboard';

        global $wpdb;

        // Table names
        $products_table = $wpdb->prefix . 'ggmc_products';
        $orders_table = $wpdb->prefix . 'ggmc_orders';
        $customers_table = $wpdb->prefix . 'ggmc_customers';
        $reviews_table = $wpdb->prefix . 'ggmc_product_reviews';
        $categories_table = $wpdb->prefix . 'ggmc_categories';
        $tags_table = $wpdb->prefix . 'ggmc_tags';

        // Check if tables exist
        $products_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $products_table)) === $products_table;
        $orders_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $orders_table)) === $orders_table;
        $customers_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $customers_table)) === $customers_table;
        $reviews_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $reviews_table)) === $reviews_table;

        // === GATHER STATISTICS ===

        // Product stats
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $products_count = $products_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $products_table WHERE status != 'trash'") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $active_products = $products_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $products_table WHERE status = 'active'") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $low_stock_count = $products_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $products_table WHERE manage_stock = 1 AND stock > 0 AND stock <= COALESCE(low_stock_threshold, 10) AND status = 'active'") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $out_of_stock_count = $products_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $products_table WHERE manage_stock = 1 AND stock <= 0 AND status = 'active'") : 0;

        // Order stats
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $orders_count = $orders_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $orders_table") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $pending_orders = $orders_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $orders_table WHERE status = 'pending'") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $processing_orders = $orders_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $orders_table WHERE status = 'processing'") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $total_revenue = $orders_exists ? (float) $wpdb->get_var("SELECT COALESCE(SUM(total_amount), 0) FROM $orders_table WHERE payment_status = 'paid'") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $orders_today = $orders_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $orders_table WHERE DATE(created_at) = CURDATE()") : 0;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $revenue_today = $orders_exists ? (float) $wpdb->get_var("SELECT COALESCE(SUM(total_amount), 0) FROM $orders_table WHERE DATE(created_at) = CURDATE() AND payment_status = 'paid'") : 0;

        // Customer stats
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $customers_count = $customers_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $customers_table") : 0;

        // Review stats
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $pending_reviews = $reviews_exists ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $reviews_table WHERE status = 'pending'") : 0;

        // Recent orders (last 5)
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $recent_orders = $orders_exists ? $wpdb->get_results("SELECT * FROM $orders_table ORDER BY created_at DESC LIMIT 5") : [];

        // Low stock products (up to 5)
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $low_stock_products = $products_exists ? $wpdb->get_results("SELECT id, name, sku, stock FROM $products_table WHERE manage_stock = 1 AND stock > 0 AND stock <= COALESCE(low_stock_threshold, 10) AND status = 'active' ORDER BY stock ASC LIMIT 5") : [];

        // Out of stock products (up to 5)
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Safe table name
        $out_of_stock_products = $products_exists ? $wpdb->get_results("SELECT id, name, sku FROM $products_table WHERE manage_stock = 1 AND stock <= 0 AND status = 'active' ORDER BY name ASC LIMIT 5") : [];

        // Currency symbol (default to £)
        $currency_options = get_option('ggm_commerce_currency_options', array());
        $currency_symbol = isset($currency_options['symbol']) ? $currency_options['symbol'] : '£';

        ?>
        <div class="wrap ggmc-dashboard-wrap">
            <?php self::page_title( 'Goose Dashboard' ); ?>

            <!-- Quick Actions -->
            <div class="ggmc-quick-actions">
                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-add-product')); ?>" class="button button-primary">
                    <span class="dashicons dashicons-plus-alt2"></span> Add Product
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-orders')); ?>" class="button">
                    <span class="dashicons dashicons-clipboard"></span> View Orders
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-customers')); ?>" class="button">
                    <span class="dashicons dashicons-groups"></span> Customers
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings')); ?>" class="button">
                    <span class="dashicons dashicons-admin-settings"></span> Settings
                </a>
            </div>

            <!-- Stats Cards -->
            <div class="ggmc-stats-grid">
                <div class="ggmc-stat-card success">
                    <span class="dashicons dashicons-chart-bar"></span>
                    <h3>Total Revenue</h3>
                    <div class="ggmc-stat-number"><?php echo esc_html($currency_symbol . number_format($total_revenue, 2)); ?></div>
                    <div class="ggmc-stat-subtext">Today: <?php echo esc_html($currency_symbol . number_format($revenue_today, 2)); ?></div>
                </div>

                <div class="ggmc-stat-card highlight">
                    <span class="dashicons dashicons-clipboard"></span>
                    <h3>Orders</h3>
                    <div class="ggmc-stat-number"><?php echo esc_html($orders_count); ?></div>
                    <div class="ggmc-stat-subtext">Today: <?php echo esc_html($orders_today); ?></div>
                </div>

                <div class="ggmc-stat-card">
                    <span class="dashicons dashicons-archive"></span>
                    <h3>Products</h3>
                    <div class="ggmc-stat-number"><?php echo esc_html($products_count); ?></div>
                    <div class="ggmc-stat-subtext">Active: <?php echo esc_html($active_products); ?></div>
                </div>

                <div class="ggmc-stat-card">
                    <span class="dashicons dashicons-groups"></span>
                    <h3>Customers</h3>
                    <div class="ggmc-stat-number"><?php echo esc_html($customers_count); ?></div>
                    <div class="ggmc-stat-subtext"><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-customers')); ?>">Manage</a></div>
                </div>
            </div>

            <!-- Alert Cards (Orders & Reviews needing attention) -->
            <?php if ($pending_orders > 0 || $processing_orders > 0 || $pending_reviews > 0): ?>
            <div class="ggmc-stats-grid" style="margin-top: 0;">
                <?php if ($pending_orders > 0): ?>
                <div class="ggmc-stat-card warning">
                    <h3>Pending Orders</h3>
                    <div class="ggmc-stat-number"><?php echo esc_html($pending_orders); ?></div>
                    <div class="ggmc-stat-subtext"><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-orders&status=pending')); ?>">View pending orders →</a></div>
                </div>
                <?php endif; ?>

                <?php if ($processing_orders > 0): ?>
                <div class="ggmc-stat-card highlight">
                    <h3>Processing Orders</h3>
                    <div class="ggmc-stat-number"><?php echo esc_html($processing_orders); ?></div>
                    <div class="ggmc-stat-subtext"><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-orders&status=processing')); ?>">View processing →</a></div>
                </div>
                <?php endif; ?>

                <?php if ($pending_reviews > 0): ?>
                <div class="ggmc-stat-card warning">
                    <h3>Reviews Pending</h3>
                    <div class="ggmc-stat-number"><?php echo esc_html($pending_reviews); ?></div>
                    <div class="ggmc-stat-subtext"><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-reviews&status=pending')); ?>">Moderate reviews →</a></div>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Main Dashboard Grid -->
            <div class="ggmc-dashboard-grid">
                <!-- Left Column: Recent Orders -->
                <div class="ggmc-card">
                    <div class="ggmc-card-header">
                        <h2>Recent Orders</h2>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-orders')); ?>" class="button button-small">View All</a>
                    </div>
                    <div class="ggmc-card-body">
                        <?php if (!empty($recent_orders)): ?>
                        <table class="wp-list-table widefat striped">
                            <thead>
                                <tr>
                                    <th>Order</th>
                                    <th>Customer</th>
                                    <th>Total</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recent_orders as $order): ?>
                                <tr>
                                    <td>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-orders&action=view&order_id=' . $order->id)); ?>">
                                            <strong>#<?php echo esc_html($order->order_number); ?></strong>
                                        </a>
                                    </td>
                                    <td><?php echo esc_html($order->customer_first_name . ' ' . $order->customer_last_name); ?></td>
                                    <td><?php echo esc_html($currency_symbol . number_format((float) $order->total_amount, 2)); ?></td>
                                    <td><span class="ggmc-status-badge ggmc-status-<?php echo esc_attr($order->status); ?>"><?php echo esc_html($order->status); ?></span></td>
                                    <td><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($order->created_at))); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <?php else: ?>
                        <div class="ggmc-empty-state">
                            <span class="dashicons dashicons-clipboard" style="font-size: 48px; color: #dcdcde;"></span>
                            <p>No orders yet. Orders will appear here when customers make purchases.</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Right Column: Stock Alerts -->
                <div>
                    <!-- Low Stock Alert -->
                    <div class="ggmc-card" style="margin-bottom: 20px;">
                        <div class="ggmc-card-header">
                            <h2>
                                <span class="dashicons dashicons-warning" style="color: #dba617;"></span>
                                Low Stock (<?php echo esc_html($low_stock_count); ?>)
                            </h2>
                        </div>
                        <div class="ggmc-card-body">
                            <?php if (!empty($low_stock_products)): ?>
                            <table class="wp-list-table widefat striped">
                                <tbody>
                                    <?php foreach ($low_stock_products as $product): ?>
                                    <tr>
                                        <td>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-edit-product&product_id=' . $product->id)); ?>">
                                                <?php echo esc_html($product->name); ?>
                                            </a>
                                            <?php if (!empty($product->sku)): ?>
                                            <br><small style="color: #64748b;">SKU: <?php echo esc_html($product->sku); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td style="text-align: right;">
                                            <span class="ggmc-stock-low"><?php echo esc_html($product->stock); ?> left</span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            <?php if ($low_stock_count > 5): ?>
                            <p style="padding: 10px 16px; margin: 0; text-align: center;">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-products&stock_status=low')); ?>">View all <?php echo esc_html($low_stock_count); ?> low stock products →</a>
                            </p>
                            <?php endif; ?>
                            <?php else: ?>
                            <div class="ggmc-empty-state" style="padding: 20px;">
                                <span class="dashicons dashicons-yes-alt" style="color: #00a32a;"></span>
                                <p style="margin: 5px 0 0;">All stocked up!</p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Out of Stock Alert -->
                    <div class="ggmc-card">
                        <div class="ggmc-card-header">
                            <h2>
                                <span class="dashicons dashicons-dismiss" style="color: #d63638;"></span>
                                Out of Stock (<?php echo esc_html($out_of_stock_count); ?>)
                            </h2>
                        </div>
                        <div class="ggmc-card-body">
                            <?php if (!empty($out_of_stock_products)): ?>
                            <table class="wp-list-table widefat striped">
                                <tbody>
                                    <?php foreach ($out_of_stock_products as $product): ?>
                                    <tr>
                                        <td>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-edit-product&product_id=' . $product->id)); ?>">
                                                <?php echo esc_html($product->name); ?>
                                            </a>
                                            <?php if (!empty($product->sku)): ?>
                                            <br><small style="color: #64748b;">SKU: <?php echo esc_html($product->sku); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td style="text-align: right;">
                                            <span class="ggmc-stock-out">Out of stock</span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            <?php if ($out_of_stock_count > 5): ?>
                            <p style="padding: 10px 16px; margin: 0; text-align: center;">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-products&stock_status=outofstock')); ?>">View all <?php echo esc_html($out_of_stock_count); ?> out of stock →</a>
                            </p>
                            <?php endif; ?>
                            <?php else: ?>
                            <div class="ggmc-empty-state" style="padding: 20px;">
                                <span class="dashicons dashicons-yes-alt" style="color: #00a32a;"></span>
                                <p style="margin: 5px 0 0;">No items out of stock</p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Products management page
     */
    /**
     * Product status constants
     */
    const PRODUCT_STATUS_DRAFT = 'draft';
    const PRODUCT_STATUS_FOR_REVIEW = 'for_review';
    const PRODUCT_STATUS_ACTIVE = 'active';
    const PRODUCT_STATUS_INACTIVE = 'inactive';
    const PRODUCT_STATUS_TRASH = 'trash';

    /**
     * Get product status labels
     */
    private function get_product_status_labels() {
        return [
            self::PRODUCT_STATUS_DRAFT => 'Draft',
            self::PRODUCT_STATUS_FOR_REVIEW => 'For Review',
            self::PRODUCT_STATUS_ACTIVE => 'Active',
            self::PRODUCT_STATUS_INACTIVE => 'Inactive',
            self::PRODUCT_STATUS_TRASH => 'Trash',
        ];
    }

    /**
     * Render product status badge with color coding
     */
    private function render_product_status_badge($status) {
        $colors = [
            self::PRODUCT_STATUS_DRAFT => '#6B7280',      // Gray
            self::PRODUCT_STATUS_FOR_REVIEW => '#F59E0B', // Amber
            self::PRODUCT_STATUS_ACTIVE => '#10B981',     // Green
            self::PRODUCT_STATUS_INACTIVE => '#EF4444',   // Red
            self::PRODUCT_STATUS_TRASH => '#991B1B',      // Dark Red
        ];

        $labels = $this->get_product_status_labels();
        $color = $colors[$status] ?? '#999';
        $label = $labels[$status] ?? ucfirst($status);

        return sprintf(
            '<span style="display: inline-block; padding: 3px 8px; background: %s; color: white; border-radius: 3px; font-size: 11px; font-weight: 600;">%s</span>',
            esc_attr($color),
            esc_html($label)
        );
    }

    /**
     * Get product categories as comma-separated string
     * Uses the ggmc_product_categories relationship table (source of truth)
     */
    private function get_product_categories_display($product_id) {
        global $wpdb;

        // Get all categories from the relationship table
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $categories = $wpdb->get_results($wpdb->prepare(
            "SELECT c.name FROM {$wpdb->prefix}ggmc_categories c
             INNER JOIN {$wpdb->prefix}ggmc_product_categories pc ON c.id = pc.category_id
             WHERE pc.product_id = %d AND c.status = 'active'
             ORDER BY c.name ASC",
            $product_id
        ));

        if (empty($categories)) {
            return '<span style="color: #999;">Uncategorised</span>';
        }

        // Build comma-separated list of category names
        $category_names = array_map(function($cat) {
            return esc_html($cat->name);
        }, $categories);

        return implode(', ', $category_names);
    }

    public function products_page() {
        // Set proper page title for WordPress
        global $title;
        $title = 'Products';

        global $wpdb;
        $products_table = $wpdb->prefix . 'ggmc_products';
        $categories_table = $wpdb->prefix . 'ggmc_categories';
        $product_categories_table = $wpdb->prefix . 'ggmc_product_categories';

        // Check if table exists before any operations
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $products_table)) === $products_table;

        // Only run database cleanup when actually viewing this page (not during admin menu registration)
        if (isset($_GET['page']) && $_GET['page'] === 'ggmc-products' && $table_exists) {
            // Ensure no NULL values in database using proper preparation
            // Note: categories and tags are now in separate relationship tables, not in products table
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
            $wpdb->query($wpdb->prepare("UPDATE {$products_table} SET sku = %s WHERE sku IS NULL", ''));
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
            $wpdb->query($wpdb->prepare("UPDATE {$products_table} SET name = %s WHERE name IS NULL OR name = %s", 'Untitled Product', ''));
        }

        // Handle AJAX status change
        if (isset($_POST['ggmc_product_status_change']) && check_admin_referer('ggmc_product_status_change')) {
            $product_id = isset($_POST['product_id']) ? intval(wp_unslash($_POST['product_id'])) : 0;
            $new_status = isset($_POST['new_status']) ? sanitize_text_field(wp_unslash($_POST['new_status'])) : '';
            $valid_statuses = array_keys($this->get_product_status_labels());

            if (in_array($new_status, $valid_statuses)) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update(
                    $products_table,
                    ['status' => $new_status, 'updated_at' => current_time('mysql')],
                    ['id' => $product_id]
                );
                echo '<div class="notice notice-success is-dismissible"><p>Product status updated successfully.</p></div>';
            }
        }

        // Note: Duplicate action is handled in handle_product_duplicate_redirect() via admin_init
        // to ensure redirect happens before any output

        // Get filter parameters
        $status_filter = isset($_GET['status']) ? sanitize_text_field(wp_unslash($_GET['status'])) : '';
        $category_filter = isset($_GET['category']) ? intval(wp_unslash($_GET['category'])) : 0;
        $product_type_filter = isset($_GET['product_type']) ? sanitize_text_field(wp_unslash($_GET['product_type'])) : '';
        $search_query = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '';
        $stock_status_filter = isset($_GET['stock_status']) ? sanitize_text_field(wp_unslash($_GET['stock_status'])) : '';

        // Get status counts
        $status_counts = [];
        if ($table_exists) {
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
            $counts_result = $wpdb->get_results("
                SELECT COALESCE(status, 'active') as status, COUNT(*) as count
                FROM {$products_table}
                GROUP BY status
            ");

            $status_counts = ['all' => 0];
            foreach ($counts_result as $stat) {
                $status_counts[$stat->status] = (int) $stat->count;
                if ($stat->status !== self::PRODUCT_STATUS_TRASH) {
                    $status_counts['all'] += (int) $stat->count;
                }
            }
        }

        // Get all categories for filter dropdown
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $all_categories = $table_exists ? $wpdb->get_results("SELECT id, name FROM {$categories_table} ORDER BY name ASC") : [];

        echo '<div class="wrap">';
        self::page_title( 'Products' );
        echo '<a href="' . esc_url(admin_url('admin.php?page=ggmc-add-product')) . '" class="page-title-action">Add New</a>';
        echo '<span class="ggmc-import-export-buttons" style="margin-left: 10px;">';
        echo '<button type="button" class="button ggmc-import-btn"><span class="dashicons dashicons-upload"></span> Import</button>';
        echo '<button type="button" class="button ggmc-export-btn"><span class="dashicons dashicons-download"></span> Export</button>';
        echo '<button type="button" class="button ggmc-reassociate-btn" title="Match images to products"><span class="dashicons dashicons-format-gallery"></span> Images</button>';
        echo '</span>';
        echo '<hr class="wp-header-end">';

        // Status Filter Tabs
        $status_labels = $this->get_product_status_labels();
        ?>
        <?php
        // Build filter query string parts for preserving filters in links
        $filter_params = '';
        if ($category_filter) {
            $filter_params .= '&category=' . esc_attr($category_filter);
        }
        if ($product_type_filter) {
            $filter_params .= '&product_type=' . esc_attr($product_type_filter);
        }
        if ($search_query) {
            $filter_params .= '&s=' . esc_attr(urlencode($search_query));
        }
        if ($stock_status_filter) {
            $filter_params .= '&stock_status=' . esc_attr($stock_status_filter);
        }
        ?>
        <ul class="subsubsub">
            <li>
                <a href="?page=ggmc-products<?php echo esc_attr($filter_params); ?>"
                   class="<?php echo !$status_filter ? 'current' : ''; ?>">
                    All <span class="count">(<?php echo esc_html($status_counts['all'] ?? 0); ?>)</span>
                </a> |
            </li>
            <?php
            $status_order = [self::PRODUCT_STATUS_DRAFT, self::PRODUCT_STATUS_FOR_REVIEW, self::PRODUCT_STATUS_ACTIVE, self::PRODUCT_STATUS_INACTIVE, self::PRODUCT_STATUS_TRASH];
            $last_status = end($status_order);
            foreach ($status_order as $status):
            ?>
            <li>
                <a href="?page=ggmc-products&status=<?php echo esc_attr($status); ?><?php echo esc_attr($filter_params); ?>"
                   class="<?php echo $status_filter === $status ? 'current' : ''; ?>">
                    <?php echo esc_html($status_labels[$status]); ?> <span class="count">(<?php echo esc_html($status_counts[$status] ?? 0); ?>)</span>
                </a><?php echo $status !== $last_status ? ' |' : ''; ?>
            </li>
            <?php endforeach; ?>
        </ul>

        <!-- Search and Category Filter Row -->
        <div class="tablenav top" style="clear: both;">
            <form method="get" style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
                <input type="hidden" name="page" value="ggmc-products" />
                <?php if ($status_filter): ?>
                    <input type="hidden" name="status" value="<?php echo esc_attr($status_filter); ?>" />
                <?php endif; ?>

                <input type="search" name="s" value="<?php echo esc_attr($search_query); ?>"
                       placeholder="Search by product name, SKU, or barcode..."
                       class="regular-text" style="min-width: 300px;" />

                <select name="category">
                    <option value="">All Categories</option>
                    <?php foreach ($all_categories as $cat): ?>
                        <option value="<?php echo esc_attr($cat->id); ?>" <?php selected($category_filter, $cat->id); ?>>
                            <?php echo esc_html($cat->name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <select name="product_type">
                    <option value="">All Types</option>
                    <option value="simple" <?php selected($product_type_filter, 'simple'); ?>>Simple Products</option>
                    <option value="variable" <?php selected($product_type_filter, 'variable'); ?>>Variable Products</option>
                    <option value="kit" <?php selected($product_type_filter, 'kit'); ?>>Kits</option>
                    <option value="build" <?php selected($product_type_filter, 'build'); ?>>Builds</option>
                    <option value="virtual" <?php selected($product_type_filter, 'virtual'); ?>>Virtual Products</option>
                    <option value="digital" <?php selected($product_type_filter, 'digital'); ?>>Digital Products</option>
                </select>

                <select name="stock_status">
                    <option value="">All Stock</option>
                    <option value="low" <?php selected($stock_status_filter, 'low'); ?>>Low Stock</option>
                    <option value="outofstock" <?php selected($stock_status_filter, 'outofstock'); ?>>Out of Stock</option>
                </select>

                <button type="submit" class="button">Filter</button>

                <?php if ($search_query || $category_filter || $product_type_filter || $stock_status_filter): ?>
                    <a href="?page=ggmc-products<?php echo $status_filter ? '&status=' . esc_attr($status_filter) : ''; ?>" class="button">Clear Filters</a>
                <?php endif; ?>
            </form>
        </div>
        <?php

        if ($search_query) {
            echo '<div style="background: #e7f7ff; border-left: 4px solid #0073aa; padding: 10px; margin: 10px 0;">';
            echo '<strong>Search results for:</strong> ' . esc_html($search_query);
            echo '</div>';
        }

        // Handle bulk actions only if table exists
        if ($table_exists && isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['product_ids'])) {
            $product_ids = array_map('intval', $_POST['product_ids']);
            $placeholders = implode(',', array_fill(0, count($product_ids), '%d'));
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
            $wpdb->query($wpdb->prepare("DELETE FROM {$products_table} WHERE id IN ({$placeholders})", $product_ids));
            echo '<div class="notice notice-success"><p>Products deleted successfully.</p></div>';
        }

        // Build WHERE clauses
        $where_clauses = [];
        $where_values = [];

        // Status filter (exclude trash from "All" by default)
        if ($status_filter) {
            $where_clauses[] = "p.status = %s";
            $where_values[] = $status_filter;
        } else {
            // Show all except trash when no status filter
            $where_clauses[] = "(p.status IS NULL OR p.status != %s)";
            $where_values[] = self::PRODUCT_STATUS_TRASH;
        }

        // Category filter
        if ($category_filter) {
            $where_clauses[] = "p.id IN (SELECT product_id FROM {$product_categories_table} WHERE category_id = %d)";
            $where_values[] = $category_filter;
        }

        // Product type filter
        if ($product_type_filter) {
            if ($product_type_filter === 'simple') {
                // Simple products: no variations and type is null/empty/simple
                $where_clauses[] = "(p.has_variations IS NULL OR p.has_variations = 0) AND (p.product_type IS NULL OR p.product_type = '' OR p.product_type = 'simple')";
            } elseif ($product_type_filter === 'variable') {
                // Variable products: has_variations = 1
                $where_clauses[] = "p.has_variations = 1";
            } else {
                $where_clauses[] = "p.product_type = %s";
                $where_values[] = $product_type_filter;
            }
        }

        // Stock status filter (from dashboard links)
        if ($stock_status_filter === 'low') {
            $where_clauses[] = "p.manage_stock = 1 AND p.stock > 0 AND p.stock <= COALESCE(p.low_stock_threshold, 10)";
        } elseif ($stock_status_filter === 'outofstock') {
            $where_clauses[] = "p.manage_stock = 1 AND p.stock <= 0";
        }

        // Search filter
        if ($search_query) {
            $search_like = '%' . $wpdb->esc_like($search_query) . '%';
            $where_clauses[] = "(p.name LIKE %s OR p.sku LIKE %s OR p.id IN (SELECT product_id FROM {$wpdb->prefix}ggmc_product_barcodes WHERE barcode_value LIKE %s))";
            $where_values[] = $search_like;
            $where_values[] = $search_like;
            $where_values[] = $search_like;
        }

        $where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

        // Get products from database with NULL safety only if table exists
        $products = array();
        if ($table_exists) {
            $query = "
                SELECT
                    p.id,
                    COALESCE(p.name, 'Untitled Product') as name,
                    COALESCE(p.slug, '') as slug,
                    COALESCE(p.sku, '') as sku,
                    COALESCE(p.price, 0) as price,
                    COALESCE(p.stock, 0) as stock,
                    COALESCE(p.manage_stock, 1) as manage_stock,
                    COALESCE(p.low_stock_threshold, 10) as low_stock_threshold,
                    COALESCE(p.status, 'active') as status,
                    COALESCE(p.product_type, 'simple') as product_type,
                    COALESCE(p.has_variations, 0) as has_variations,
                    COALESCE(p.created_at, NOW()) as created_at
                FROM {$products_table} p
                {$where_sql}
                ORDER BY p.created_at DESC
                LIMIT 50
            ";

            if (!empty($where_values)) {
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $query is built safely above, $where_values are sanitized
                $products = $wpdb->get_results($wpdb->prepare($query, $where_values));
            } else {
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $query has no user input when $where_values is empty
                $products = $wpdb->get_results($query);
            }
        }

        // Bulk Actions UI
        ?>
        <form id="ggmc-products-bulk-form" method="post">
            <?php wp_nonce_field('ggmc_bulk_products_action', 'ggmc_bulk_nonce'); ?>
            <div class="tablenav top" style="margin-bottom: 10px;">
                <div class="alignleft actions bulkactions">
                    <label for="bulk-action-selector-top" class="screen-reader-text">Select bulk action</label>
                    <select name="bulk_action" id="bulk-action-selector-top">
                        <option value="">Bulk Actions</option>
                        <option value="set_draft">Set to Draft</option>
                        <option value="set_for_review">Set to For Review</option>
                        <option value="set_active">Set to Active</option>
                        <option value="set_inactive">Set to Inactive</option>
                        <option value="move_to_trash">Move to Trash</option>
                        <?php if ($status_filter === self::PRODUCT_STATUS_TRASH): ?>
                        <option value="restore_from_trash">Restore from Trash</option>
                        <option value="delete_permanently">Delete Permanently</option>
                        <?php endif; ?>
                    </select>
                    <button type="button" id="ggmc-apply-bulk-action" class="button action">Apply</button>
                    <span id="ggmc-bulk-selected-count" style="margin-left: 10px; color: #64748b;"></span>
                </div>
            </div>

            <table class="wp-list-table widefat fixed striped" id="ggmc-products-table">
            <thead>
            <tr>
                <td id="cb" class="manage-column column-cb check-column" style="width: 2.5em;">
                    <input type="checkbox" id="cb-select-all-1" title="Select All" />
                </td>
                <th class="manage-column column-primary" style="width: 23%;">Product Name</th>
                <th class="manage-column" style="width: 9%;">SKU</th>
                <th class="manage-column" style="width: 11%;">Barcode</th>
                <th class="manage-column" style="width: 14%;">Categories</th>
                <th class="manage-column" style="width: 8%;">Price</th>
                <th class="manage-column" style="width: 6%;">Stock</th>
                <th class="manage-column" style="width: 9%;">Status</th>
                <th class="manage-column" style="width: 14%;">Actions</th>
            </tr>
            </thead>
            <tbody>
        <?php

        if ($products) {
            $barcode_manager = GGM_Commerce_Barcode::get_instance();

            foreach ($products as $product) {
                $edit_url = admin_url('admin.php?page=ggmc-edit-product&id=' . $product->id);

                // Get primary barcode
                $primary_barcode = $barcode_manager->get_primary_barcode($product->id);
                $barcode_display = $primary_barcode
                    ? '<code style="font-size: 11px;">' . esc_html($primary_barcode->barcode_value) . '</code>'
                    : '<span style="color: #999;">-</span>';

                // Get categories
                $categories_display = $this->get_product_categories_display($product->id);

                // Product type badge - check has_variations first, then product_type
                $product_type = $product->product_type ?? 'simple';
                $has_variations = !empty($product->has_variations);
                $type_badge = '';
                if ($has_variations) {
                    $type_badge = ' <span class="ggmc-product-type-badge ggmc-type-variable" title="Variable product with options">Variable</span>';
                } elseif ($product_type === 'kit') {
                    $type_badge = ' <span class="ggmc-product-type-badge ggmc-type-kit" title="Kit - can be broken down">Kit</span>';
                } elseif ($product_type === 'build') {
                    $type_badge = ' <span class="ggmc-product-type-badge ggmc-type-build" title="Build - permanent assembly">Build</span>';
                } elseif ($product_type === 'virtual') {
                    $type_badge = ' <span class="ggmc-product-type-badge ggmc-type-virtual" title="Virtual product - no shipping">Virtual</span>';
                } elseif ($product_type === 'digital') {
                    $type_badge = ' <span class="ggmc-product-type-badge ggmc-type-digital" title="Digital/downloadable product">Digital</span>';
                }

                echo '<tr data-product-id="' . esc_attr($product->id) . '">';
                echo '<th scope="row" class="check-column"><input type="checkbox" name="product_ids[]" value="' . esc_attr($product->id) . '" class="ggmc-bulk-checkbox" /></th>';
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $type_badge is constructed safely above
                echo '<td class="column-primary"><strong><a href="' . esc_url($edit_url) . '">' . esc_html($product->name) . '</a></strong>' . $type_badge . '</td>';
                echo '<td>' . esc_html($product->sku ?: '-') . '</td>';
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $barcode_display is escaped in get_primary_barcode()
                echo '<td>' . $barcode_display . '</td>';
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $categories_display is escaped in get_product_categories_display()
                echo '<td>' . $categories_display . '</td>';
                echo '<td>$' . esc_html(number_format($product->price, 2)) . '</td>';
                if (!empty($product->manage_stock)) {
                    $stock_qty = intval($product->stock);
                    $threshold = intval($product->low_stock_threshold);
                    if ($stock_qty <= 0) {
                        echo '<td><span class="ggmc-stock-badge ggmc-stock-out">' . esc_html($stock_qty) . '</span></td>';
                    } elseif ($stock_qty <= $threshold) {
                        echo '<td><span class="ggmc-stock-badge ggmc-stock-low">' . esc_html($stock_qty) . '</span></td>';
                    } else {
                        echo '<td><span class="ggmc-stock-badge ggmc-stock-in">' . esc_html($stock_qty) . '</span></td>';
                    }
                } else {
                    echo '<td><span class="ggmc-stock-badge ggmc-stock-unmanaged" title="Stock not tracked">&mdash;</span></td>';
                }
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_product_status_badge() returns escaped HTML
                echo '<td>' . $this->render_product_status_badge($product->status) . '</td>';
                echo '<td>';

                // Edit button
                echo '<a href="' . esc_url($edit_url) . '" class="button button-small" title="Edit">Edit</a> ';

                // View button (opens frontend product page)
                $view_url = home_url('/product-details/' . $product->slug);
                echo '<a href="' . esc_url($view_url) . '" class="button button-small" title="View on site" target="_blank"><span class="dashicons dashicons-visibility" style="font-size: 14px; width: 14px; height: 14px; vertical-align: middle;"></span></a> ';

                // Duplicate button
                $duplicate_url = wp_nonce_url(
                    admin_url('admin.php?page=ggmc-products&action=duplicate&id=' . $product->id),
                    'ggmc_duplicate_product_' . $product->id
                );
                echo '<a href="' . esc_url($duplicate_url) . '" class="button button-small" title="Duplicate"><span class="dashicons dashicons-admin-page" style="font-size: 14px; width: 14px; height: 14px; vertical-align: middle;"></span></a> ';

                // Suspend button (if not already inactive or trash)
                if ($product->status !== self::PRODUCT_STATUS_INACTIVE && $product->status !== self::PRODUCT_STATUS_TRASH) {
                    echo '<form method="post" style="display: inline;" onsubmit="return confirm(\'Suspend this product?\');">';
                    wp_nonce_field('ggmc_product_status_change');
                    echo '<input type="hidden" name="ggmc_product_status_change" value="1" />';
                    echo '<input type="hidden" name="product_id" value="' . esc_attr($product->id) . '" />';
                    echo '<input type="hidden" name="new_status" value="' . esc_attr(self::PRODUCT_STATUS_INACTIVE) . '" />';
                    echo '<button type="submit" class="button button-small" title="Suspend" style="color: #d63638;">Suspend</button> ';
                    echo '</form>';
                }

                // Restore button (if inactive)
                if ($product->status === self::PRODUCT_STATUS_INACTIVE) {
                    echo '<form method="post" style="display: inline;">';
                    wp_nonce_field('ggmc_product_status_change');
                    echo '<input type="hidden" name="ggmc_product_status_change" value="1" />';
                    echo '<input type="hidden" name="product_id" value="' . esc_attr($product->id) . '" />';
                    echo '<input type="hidden" name="new_status" value="' . esc_attr(self::PRODUCT_STATUS_ACTIVE) . '" />';
                    echo '<button type="submit" class="button button-small" title="Restore" style="color: #00a32a;">Restore</button> ';
                    echo '</form>';
                }

                // Trash button (if not already trash)
                if ($product->status !== self::PRODUCT_STATUS_TRASH) {
                    echo '<form method="post" style="display: inline;" onsubmit="return confirm(\'Move this product to trash?\');">';
                    wp_nonce_field('ggmc_product_status_change');
                    echo '<input type="hidden" name="ggmc_product_status_change" value="1" />';
                    echo '<input type="hidden" name="product_id" value="' . esc_attr($product->id) . '" />';
                    echo '<input type="hidden" name="new_status" value="' . esc_attr(self::PRODUCT_STATUS_TRASH) . '" />';
                    echo '<button type="submit" class="button button-small" title="Trash" style="color: #b32d2e;"><span class="dashicons dashicons-trash" style="font-size: 14px; width: 14px; height: 14px; vertical-align: middle;"></span></button>';
                    echo '</form>';
                }

                // Restore from trash and Delete permanently (if in trash)
                if ($product->status === self::PRODUCT_STATUS_TRASH) {
                    echo '<form method="post" style="display: inline;">';
                    wp_nonce_field('ggmc_product_status_change');
                    echo '<input type="hidden" name="ggmc_product_status_change" value="1" />';
                    echo '<input type="hidden" name="product_id" value="' . esc_attr($product->id) . '" />';
                    echo '<input type="hidden" name="new_status" value="' . esc_attr(self::PRODUCT_STATUS_DRAFT) . '" />';
                    echo '<button type="submit" class="button button-small" title="Restore" style="color: #00a32a;">Restore</button> ';
                    echo '</form>';

                    echo '<form method="post" style="display: inline;" onsubmit="return confirm(\'Permanently delete this product? This cannot be undone.\');">';
                    wp_nonce_field('ggmc_delete_product_permanently');
                    echo '<input type="hidden" name="ggmc_delete_product_permanently" value="1" />';
                    echo '<input type="hidden" name="product_id" value="' . esc_attr($product->id) . '" />';
                    echo '<button type="submit" class="button button-small" title="Delete Permanently" style="color: #b32d2e;">Delete</button>';
                    echo '</form>';
                }

                echo '</td>';
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="9">No products found. <a href="' . esc_url(admin_url('admin.php?page=ggmc-add-product')) . '">Create your first product</a></td></tr>';
        }

        echo '</tbody>';
        echo '</table>';
        echo '</form>'; // Close the bulk form
        echo '</div>';

        // Handle permanent deletion
        if ($table_exists && isset($_POST['ggmc_delete_product_permanently']) && check_admin_referer('ggmc_delete_product_permanently')) {
            $product_id = isset($_POST['product_id']) ? intval(wp_unslash($_POST['product_id'])) : 0;

            // Delete product categories
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->delete($product_categories_table, ['product_id' => $product_id]);

            // Delete product tags
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->delete("{$wpdb->prefix}ggmc_product_tags", ['product_id' => $product_id]);

            // Delete product barcodes
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->delete("{$wpdb->prefix}ggmc_product_barcodes", ['product_id' => $product_id]);

            // Delete product reviews
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->delete("{$wpdb->prefix}ggmc_product_reviews", ['product_id' => $product_id]);

            // Delete the product
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->delete($products_table, ['id' => $product_id]);

            echo '<script>window.location.href = "' . esc_url(admin_url('admin.php?page=ggmc-products&status=trash')) . '";</script>';
        }
    }
    
    /**
     * Orders management page
     */
    public function orders_page() {
        // Set proper page title for WordPress
        global $title, $wpdb;
        $title = 'Orders';

        // Check if viewing a single order
        $view_order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

        if ($view_order_id) {
            $this->render_order_detail($view_order_id);
            return;
        }

        // Handle status updates
        if (isset($_POST['update_order_status']) && check_admin_referer('ggmc_update_order_status')) {
            $order_id = isset($_POST['order_id']) ? intval(wp_unslash($_POST['order_id'])) : 0;
            $new_status = isset($_POST['order_status']) ? sanitize_text_field(wp_unslash($_POST['order_status'])) : '';
            $new_payment_status = isset($_POST['payment_status']) ? sanitize_text_field(wp_unslash($_POST['payment_status'])) : '';

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $updated = $wpdb->update(
                "{$wpdb->prefix}ggmc_orders",
                [
                    'status' => $new_status,
                    'payment_status' => $new_payment_status,
                    'updated_at' => current_time('mysql')
                ],
                ['id' => $order_id]
            );

            if ($updated !== false) {
                // Fire hooks for download permissions, email notifications, etc.
                do_action('ggm_commerce_order_status_changed', $order_id, $new_status, $new_payment_status);
                do_action('ggmc_order_status_' . $new_status, $order_id);

                echo '<div class="notice notice-success"><p>Order status updated successfully!</p></div>';
            }
        }

        $orders_table = $wpdb->prefix . 'ggmc_orders';

        // Get filter parameters
        $status_filter = isset($_GET['status']) ? sanitize_text_field(wp_unslash($_GET['status'])) : '';
        $payment_filter = isset($_GET['payment_status']) ? sanitize_text_field(wp_unslash($_GET['payment_status'])) : '';

        // Build query with filters
        $where_clauses = [];
        if ($status_filter) {
            $where_clauses[] = $wpdb->prepare("status = %s", $status_filter);
        }
        if ($payment_filter) {
            $where_clauses[] = $wpdb->prepare("payment_status = %s", $payment_filter);
        }

        $where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

        // Get orders with error handling
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $orders_table)) === $orders_table;
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $orders = $table_exists ? $wpdb->get_results("SELECT * FROM $orders_table $where_sql ORDER BY created_at DESC LIMIT 100") : array();

        // Get status counts
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $status_counts = $table_exists ? $wpdb->get_results(
            "SELECT status, COUNT(*) as count FROM {$orders_table} GROUP BY status"
        ) : [];

        $counts = ['all' => 0];
        foreach ($status_counts as $stat) {
            $counts[$stat->status] = $stat->count;
            $counts['all'] += $stat->count;
        }

        ?>
        <div class="wrap">
            <?php self::page_title( 'Orders' ); ?>

            <!-- Status Filter Tabs -->
            <ul class="subsubsub">
                <li><a href="?page=ggmc-orders" class="<?php echo !$status_filter ? 'current' : ''; ?>">All <span class="count">(<?php echo esc_html($counts['all']); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-orders&status=pending" class="<?php echo $status_filter === 'pending' ? 'current' : ''; ?>">Pending <span class="count">(<?php echo esc_html($counts['pending'] ?? 0); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-orders&status=processing" class="<?php echo $status_filter === 'processing' ? 'current' : ''; ?>">Processing <span class="count">(<?php echo esc_html($counts['processing'] ?? 0); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-orders&status=shipped" class="<?php echo $status_filter === 'shipped' ? 'current' : ''; ?>">Shipped <span class="count">(<?php echo esc_html($counts['shipped'] ?? 0); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-orders&status=completed" class="<?php echo $status_filter === 'completed' ? 'current' : ''; ?>">Completed <span class="count">(<?php echo esc_html($counts['completed'] ?? 0); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-orders&status=cancelled" class="<?php echo $status_filter === 'cancelled' ? 'current' : ''; ?>">Cancelled <span class="count">(<?php echo esc_html($counts['cancelled'] ?? 0); ?>)</span></a></li>
            </ul>

            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width: 100px;">Order</th>
                        <th>Customer</th>
                        <th style="width: 100px;">Total</th>
                        <th style="width: 120px;">Order Status</th>
                        <th style="width: 120px;">Payment</th>
                        <th style="width: 150px;">Date</th>
                        <th style="width: 100px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($orders): ?>
                        <?php foreach ($orders as $order): ?>
                            <tr>
                                <td>
                                    <strong><a href="?page=ggmc-orders&order_id=<?php echo esc_attr($order->id); ?>">#<?php echo esc_html($order->order_number); ?></a></strong>
                                </td>
                                <td>
                                    <?php echo esc_html($order->customer_first_name . ' ' . $order->customer_last_name); ?>
                                    <?php if (!empty($order->is_tax_exempt)): ?>
                                        <span style="background: #e7f3ff; color: #0073aa; padding: 1px 4px; border-radius: 2px; font-size: 10px; margin-left: 3px;" title="B2B Tax Exempt">B2B</span>
                                    <?php endif; ?><br>
                                    <small><?php echo esc_html($order->customer_email); ?></small>
                                </td>
                                <td>$<?php echo esc_html(number_format($order->total_amount, 2)); ?></td>
                                <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_status_badge() returns escaped HTML ?>
                                <td><?php echo $this->render_status_badge($order->status); ?></td>
                                <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_payment_status_badge() returns escaped HTML ?>
                                <td><?php echo $this->render_payment_status_badge($order->payment_status); ?></td>
                                <td><?php echo esc_html(gmdate('M j, Y g:i a', strtotime($order->created_at))); ?></td>
                                <td>
                                    <a href="?page=ggmc-orders&order_id=<?php echo esc_attr($order->id); ?>" class="button button-small">View</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="7" style="text-align: center; padding: 40px;">No orders found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php
    }
    
    /**
     * Add product page implementation
     */
    public function add_product_page() {
        global $wpdb, $title;

        // Set default title to avoid null warnings
        if (empty($title)) {
            $title = 'Add Product';
        }

        // Check for duplicate transient data
        $transient_key = 'ggmc_duplicate_' . get_current_user_id();
        $duplicate_data = get_transient($transient_key);
        $is_duplicate = !empty($duplicate_data) && isset($_GET['duplicate']);

        // Handle form submission
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (isset($_POST['submit']) && wp_verify_nonce($_POST['ggm_commerce_nonce'], 'ggm_commerce_add_product')) {
            $products_table = $wpdb->prefix . 'ggmc_products';

            // Check if table exists before inserting
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $products_table)) === $products_table;
            
            if ($table_exists) {
                // Generate unique slug from product name or use custom slug
                $product_name = isset($_POST['product_name']) ? sanitize_text_field(wp_unslash($_POST['product_name'])) : '';
                $custom_slug = isset($_POST['product_slug']) ? sanitize_title(wp_unslash($_POST['product_slug'])) : '';

                if (!empty($custom_slug)) {
                    // Use custom slug, ensure uniqueness
                    $slug = GGM_Commerce_Database::generate_unique_slug($custom_slug);
                } else {
                    // Auto-generate from product name
                    $slug = GGM_Commerce_Database::generate_unique_slug($product_name);
                }

                // Validate and sanitize status
                $valid_statuses = array_keys($this->get_product_status_labels());
                $product_status = isset($_POST['product_status']) ? sanitize_text_field(wp_unslash($_POST['product_status'])) : self::PRODUCT_STATUS_DRAFT;
                if (!in_array($product_status, $valid_statuses) || $product_status === self::PRODUCT_STATUS_TRASH) {
                    $product_status = self::PRODUCT_STATUS_DRAFT;
                }

                // Validate product type using centralized configuration
                $valid_product_types = array_keys(GGM_Commerce_Helpers::get_product_types());
                $product_type = isset($_POST['product_type']) ? sanitize_text_field(wp_unslash($_POST['product_type'])) : 'simple';
                if (!in_array($product_type, $valid_product_types, true)) {
                    $product_type = 'simple';
                }

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                $result = $wpdb->insert(
                    $products_table,
                    array(
                        'name' => $product_name,
                        'slug' => $slug,
                        'description' => isset($_POST['product_description']) ? wp_kses_post(wp_unslash($_POST['product_description'])) : '',
                        'price' => isset($_POST['product_price']) ? floatval(wp_unslash($_POST['product_price'])) : 0,
                        'sale_price' => !empty($_POST['product_sale_price']) ? floatval(wp_unslash($_POST['product_sale_price'])) : null,
                        'stock' => isset($_POST['stock_quantity']) ? intval(wp_unslash($_POST['stock_quantity'])) : 0,
                        'manage_stock' => isset($_POST['manage_stock']) ? 1 : 0,
                        'stock_status' => isset($_POST['manage_stock']) ? (intval($_POST['stock_quantity'] ?? 0) > 0 ? 'instock' : 'outofstock') : 'instock',
                        'low_stock_threshold' => isset($_POST['low_stock_threshold']) ? intval(wp_unslash($_POST['low_stock_threshold'])) : 10,
                        'restock_date' => !empty($_POST['restock_date']) ? sanitize_text_field(wp_unslash($_POST['restock_date'])) : null,
                        'sku' => isset($_POST['sku']) ? sanitize_text_field(wp_unslash($_POST['sku'])) : '',
                        'short_description' => isset($_POST['short_description']) ? sanitize_textarea_field(wp_unslash($_POST['short_description'])) : '',
                        'weight' => !empty($_POST['product_weight']) ? floatval(wp_unslash($_POST['product_weight'])) : null,
                        'length' => !empty($_POST['product_length']) ? floatval(wp_unslash($_POST['product_length'])) : null,
                        'width' => !empty($_POST['product_width']) ? floatval(wp_unslash($_POST['product_width'])) : null,
                        'height' => !empty($_POST['product_height']) ? floatval(wp_unslash($_POST['product_height'])) : null,
                        'image_id' => !empty($_POST['main_image_id']) ? intval(wp_unslash($_POST['main_image_id'])) : 0,
                        'gallery_ids' => isset($_POST['gallery_image_ids']) ? sanitize_text_field(wp_unslash($_POST['gallery_image_ids'])) : '',
                        'status' => $product_status,
                        'product_type' => $product_type,
                        'tax_rate_id' => !empty($_POST['tax_rate_id']) ? intval(wp_unslash($_POST['tax_rate_id'])) : null,
                        'gift_card_value' => $product_type === 'gift_card' && isset($_POST['gift_card_value']) && $_POST['gift_card_value'] !== '' ? floatval(wp_unslash($_POST['gift_card_value'])) : null,
                        'gift_card_type' => $product_type === 'gift_card' && isset($_POST['gift_card_type']) ? sanitize_text_field(wp_unslash($_POST['gift_card_type'])) : 'fixed',
                        'gift_card_single_use' => $product_type === 'gift_card' && isset($_POST['gift_card_single_use']) ? 1 : 0,
                        'gift_card_valid_days' => $product_type === 'gift_card' && isset($_POST['gift_card_valid_days']) && $_POST['gift_card_valid_days'] !== '' ? intval(wp_unslash($_POST['gift_card_valid_days'])) : null,
                        'gift_card_code_prefix' => $product_type === 'gift_card' && isset($_POST['gift_card_code_prefix']) ? sanitize_text_field(wp_unslash($_POST['gift_card_code_prefix'])) : 'GC',
                        'is_subscription' => isset($_POST['is_subscription']) ? 1 : 0,
                        'subscription_period' => isset($_POST['subscription_period']) ? sanitize_text_field(wp_unslash($_POST['subscription_period'])) : 'month',
                        'subscription_interval' => isset($_POST['subscription_interval']) ? intval(wp_unslash($_POST['subscription_interval'])) : 1,
                        'subscription_trial_length' => isset($_POST['subscription_trial_length']) ? intval(wp_unslash($_POST['subscription_trial_length'])) : 0,
                        'subscription_trial_period' => isset($_POST['subscription_trial_period']) ? sanitize_text_field(wp_unslash($_POST['subscription_trial_period'])) : 'day',
                        'subscription_sign_up_fee' => isset($_POST['subscription_sign_up_fee']) ? floatval(wp_unslash($_POST['subscription_sign_up_fee'])) : 0.00,
                        'subscription_length' => isset($_POST['subscription_length']) ? intval(wp_unslash($_POST['subscription_length'])) : 0,
                        'created_at' => current_time('mysql')
                    ),
                    array('%s', '%s', '%s', '%f', '%f', '%d', '%d', '%s', '%d', '%s', '%s', '%f', '%f', '%f', '%f', '%d', '%s', '%s', '%s', '%d', '%f', '%s', '%d', '%d', '%s', '%d', '%s', '%d', '%d', '%s', '%f', '%d', '%s')
                );

                if ($result !== false) {
                    $product_id = $wpdb->insert_id;

                    // Handle categories
                    $taxonomy = GGM_Commerce_Taxonomy::get_instance();
                    $category_ids = isset($_POST['product_categories']) ? array_map('intval', (array)$_POST['product_categories']) : [];
                    $taxonomy->set_product_categories($product_id, $category_ids);

                    // Handle tags
                    $tag_ids = isset($_POST['product_tags']) ? array_map('intval', (array)$_POST['product_tags']) : [];
                    $taxonomy->set_product_tags($product_id, $tag_ids);

                    // Clear filter caches for new product (price range may have changed)
                    GGM_Commerce_Taxonomy::clear_price_range_cache();

                    // Handle custom attributes (premium feature)
                    if (GGM_Commerce_License::instance()->is_widget_activated('custom-attributes')) {
                        $attributes_manager = GGM_Commerce_Attributes::get_instance();
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Attributes data sanitized in set_product_attribute_values method
                        $attributes_data = isset($_POST['custom_attributes']) ? wp_unslash($_POST['custom_attributes']) : [];
                        $attributes_manager->set_product_attribute_values($product_id, $attributes_data);
                    }

                    // Handle kit/build creation (premium feature)
                    if (in_array($product_type, array('kit', 'build'), true) && GGM_Commerce_License::instance()->is_widget_activated('product-kits')) {
                        $kits_manager = GGM_Commerce_Kits::get_instance();
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Components data sanitized in create_kit method
                        $components_data = isset($_POST['kit_components']) ? wp_unslash($_POST['kit_components']) : [];
                        $auto_price = isset($_POST['kit_auto_price']) && $_POST['kit_auto_price'] === '1';

                        $components = array();
                        if (!empty($components_data['product_id'])) {
                            foreach ($components_data['product_id'] as $index => $comp_product_id) {
                                if (!empty($comp_product_id)) {
                                    $components[] = array(
                                        'product_id' => absint($comp_product_id),
                                        'quantity' => absint($components_data['quantity'][$index] ?? 1),
                                    );
                                }
                            }
                        }

                        $kits_manager->create_kit($product_id, $product_type, $components, $auto_price);
                    }

                    // Clear duplicate transient after successful save
                    if ($is_duplicate) {
                        delete_transient($transient_key);
                        $is_duplicate = false;
                        $duplicate_data = null;
                    }

                    echo '<div class="notice notice-success"><p>Product added successfully!</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>Error adding product: ' . esc_html($wpdb->last_error) . '</p></div>';
                }
            } else {
                echo '<div class="notice notice-error"><p>Error: Products table does not exist. Please activate the plugin properly.</p></div>';
            }
        }
        
        ?>
        <div class="wrap ggmc-product-form">
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-products')); ?>">&larr; Back to Products</a></p>
            <?php self::page_title( $is_duplicate ? 'Duplicate Product' : 'Add New Product' ); ?>

            <?php if ($is_duplicate): ?>
            <div class="notice notice-info is-dismissible">
                <p><span class="dashicons dashicons-info" style="color: #0F766E;"></span> <strong>Duplicating product.</strong> Review the details below and save when ready. The duplicate will not be created until you save.</p>
            </div>
            <?php endif; ?>

            <form method="post" action="">
                <?php wp_nonce_field('ggm_commerce_add_product', 'ggm_commerce_nonce'); ?>

                <!-- Section 1: Product Identity -->
                <div class="ggmc-product-section" data-section="identity">
                    <h2>Product Identity</h2>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="product_name">Product Name</label></th>
                            <td><input name="product_name" type="text" id="product_name" value="<?php echo $is_duplicate ? esc_attr($duplicate_data['name']) : ''; ?>" class="regular-text" required /></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_slug">URL Slug</label></th>
                            <td>
                                <input name="product_slug" type="text" id="product_slug" value="" class="regular-text" />
                                <p class="description">The URL-friendly version of the product name. Leave blank to auto-generate from name.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="sku">SKU</label></th>
                            <td>
                                <input name="sku" type="text" id="sku" value="<?php echo $is_duplicate ? esc_attr($duplicate_data['sku'] ?? '') : ''; ?>" class="regular-text" />
                                <?php if ($is_duplicate): ?>
                                <p class="description" style="color: #d63638;">SKU must be unique. Please enter a new SKU for this duplicate.</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_status">Status</label></th>
                            <td>
                                <?php
                                $status_labels = $this->get_product_status_labels();
                                $selected_status = $is_duplicate ? ($duplicate_data['status'] ?? self::PRODUCT_STATUS_DRAFT) : self::PRODUCT_STATUS_DRAFT;
                                ?>
                                <select name="product_status" id="product_status" style="width: 200px;">
                                    <?php foreach ($status_labels as $value => $label): ?>
                                        <?php if ($value !== self::PRODUCT_STATUS_TRASH): ?>
                                            <option value="<?php echo esc_attr($value); ?>" <?php selected($value, $selected_status); ?>>
                                                <?php echo esc_html($label); ?>
                                            </option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description">Set product visibility. Draft products are not visible on the frontend.</p>
                            </td>
                        </tr>
                        <?php
                        // Product Type selector - shows all types with premium locking
                        $product_type_options = GGM_Commerce_Helpers::get_product_type_options();
                        $selected_product_type = $is_duplicate ? ($duplicate_data['product_type'] ?? 'simple') : 'simple';
                        ?>
                        <tr>
                            <th scope="row"><label for="product_type">Product Type</label></th>
                            <td>
                                <select name="product_type" id="product_type" style="width: 250px;">
                                    <?php foreach ($product_type_options as $value => $option): ?>
                                        <option value="<?php echo esc_attr($value); ?>"
                                                <?php selected($value, $selected_product_type); ?>
                                                <?php disabled(!$option['available']); ?>
                                                data-available="<?php echo $option['available'] ? 'true' : 'false'; ?>">
                                            <?php echo esc_html($option['label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description" id="product-type-description">
                                    <?php esc_html_e('Select the type of product. Premium types show 🔒 if not activated.', 'ggm-commerce'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Save Product</button>
                    </div>
                </div>

                <!-- Kit Components Section (shown when kit or build selected) -->
                <?php
                $kits_activated = GGM_Commerce_Helpers::is_product_type_available('kit');
                $dup_kit_components = $is_duplicate ? ($duplicate_data['kit_components'] ?? []) : [];
                $show_kit_section = $is_duplicate && in_array($selected_product_type, ['kit', 'build']);
                ?>
                <div class="ggmc-product-section" id="kit-components-section" data-section="kit-components" style="<?php echo $show_kit_section ? '' : 'display: none;'; ?>">
                    <h2>Kit Components</h2>
                    <p class="description">Add the products that make up this kit or build. Stock for components will be deducted when kit units are created.</p>

                    <div class="ggmc-kit-components-list" id="kit-components-list">
                        <?php
                        // Pre-populate components from duplicate data
                        if ($is_duplicate && !empty($dup_kit_components)) {
                            global $wpdb;
                            foreach ($dup_kit_components as $comp) {
                                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                $comp_product = $wpdb->get_row($wpdb->prepare(
                                    "SELECT id, name, sku, price, stock FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
                                    $comp['product_id']
                                ));
                                if ($comp_product) {
                                    $comp_name = $comp_product->name . ($comp_product->sku ? ' (' . $comp_product->sku . ')' : '');
                                    ?>
                                    <div class="ggmc-kit-component-row kit-component-row" data-product-id="<?php echo esc_attr($comp_product->id); ?>">
                                        <span class="component-name"><?php echo esc_html($comp_name); ?></span>
                                        <input type="hidden" name="kit_components[product_id][]" value="<?php echo esc_attr($comp_product->id); ?>" />
                                        <label>Qty:</label>
                                        <input type="number" name="kit_components[quantity][]" value="<?php echo esc_attr($comp['quantity']); ?>" min="1" class="component-qty" data-price="<?php echo esc_attr($comp_product->price); ?>" data-stock="<?php echo esc_attr($comp_product->stock); ?>" />
                                        <span class="component-stock">(Stock: <?php echo esc_html($comp_product->stock); ?>)</span>
                                        <span class="component-remove dashicons dashicons-no-alt" title="Remove"></span>
                                    </div>
                                    <?php
                                }
                            }
                        }
                        ?>
                    </div>

                    <div class="ggmc-kit-add-component">
                        <select id="kit-component-select" style="width: 300px;">
                            <option value="">Select a product to add...</option>
                        </select>
                        <input type="number" id="kit-component-qty" value="1" min="1" style="width: 60px;" />
                        <button type="button" class="button" id="add-kit-component">Add Component</button>
                    </div>

                    <div class="ggmc-kit-stats" id="kit-stats" style="display: none;">
                        <p><strong>Calculated Price:</strong> <span class="stat-value" id="kit-calc-price">$0.00</span></p>
                        <p><strong>Maximum Creatable:</strong> <span class="stat-value" id="kit-max-creatable">0 units</span></p>
                        <p class="description" id="kit-limiting-factor"></p>
                    </div>

                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Save Product</button>
                    </div>
                </div>

                <!-- Gift Card Settings Section (shown when gift_card selected) -->
                <?php
                $gift_card_activated = GGM_Commerce_Helpers::is_product_type_available('gift_card');
                $show_gift_card_section = $is_duplicate && $selected_product_type === 'gift_card';
                $dup_gift_card_value = $is_duplicate ? ($duplicate_data['gift_card_value'] ?? '') : '';
                $dup_gift_card_type = $is_duplicate ? ($duplicate_data['gift_card_type'] ?? 'fixed') : 'fixed';
                $dup_gift_card_single_use = $is_duplicate ? ($duplicate_data['gift_card_single_use'] ?? 0) : 0;
                $dup_gift_card_valid_days = $is_duplicate ? ($duplicate_data['gift_card_valid_days'] ?? '') : '';
                $dup_gift_card_code_prefix = $is_duplicate ? ($duplicate_data['gift_card_code_prefix'] ?? 'GC') : 'GC';
                ?>
                <div class="ggmc-product-section" id="gift-card-section" data-section="gift-card-settings" style="<?php echo $show_gift_card_section ? '' : 'display: none;'; ?>">
                    <h2><?php esc_html_e( 'Gift Card Settings', 'ggm-commerce' ); ?></h2>
                    <p class="description"><?php esc_html_e( 'Configure the voucher that will be generated when this gift card is purchased.', 'ggm-commerce' ); ?></p>

                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="gift_card_value"><?php esc_html_e( 'Voucher Value', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" step="0.01" min="0" name="gift_card_value" id="gift_card_value" value="<?php echo esc_attr( $dup_gift_card_value ); ?>" style="width: 150px;" />
                                <p class="description"><?php esc_html_e( 'The value of the voucher that will be generated. Leave empty to use the product price.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_type"><?php esc_html_e( 'Voucher Type', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <select name="gift_card_type" id="gift_card_type" style="width: 200px;">
                                    <option value="fixed" <?php selected( $dup_gift_card_type, 'fixed' ); ?>><?php esc_html_e( 'Fixed Amount', 'ggm-commerce' ); ?></option>
                                    <option value="percentage" <?php selected( $dup_gift_card_type, 'percentage' ); ?>><?php esc_html_e( 'Percentage', 'ggm-commerce' ); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e( 'Fixed amount creates a voucher worth a set value. Percentage creates a % discount voucher.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_single_use"><?php esc_html_e( 'Single Use', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="gift_card_single_use" id="gift_card_single_use" value="1" <?php checked( $dup_gift_card_single_use, 1 ); ?> />
                                    <?php esc_html_e( 'Voucher can only be used once (full value applied)', 'ggm-commerce' ); ?>
                                </label>
                                <p class="description"><?php esc_html_e( 'If unchecked, partial use is allowed and remaining balance carries forward.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_valid_days"><?php esc_html_e( 'Valid For (Days)', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" min="0" name="gift_card_valid_days" id="gift_card_valid_days" value="<?php echo esc_attr( $dup_gift_card_valid_days ); ?>" style="width: 100px;" />
                                <p class="description"><?php esc_html_e( 'Number of days the voucher is valid after purchase. Leave empty for no expiration.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_code_prefix"><?php esc_html_e( 'Code Prefix', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="text" maxlength="10" name="gift_card_code_prefix" id="gift_card_code_prefix" value="<?php echo esc_attr( $dup_gift_card_code_prefix ); ?>" style="width: 100px;" />
                                <p class="description"><?php esc_html_e( 'Prefix for generated voucher codes (e.g., GC-XXXX).', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                    </table>

                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary"><?php esc_html_e( 'Save Product', 'ggm-commerce' ); ?></button>
                    </div>
                </div>

                <!-- Subscription Settings Section -->
                <?php
                $subscriptions_activated = class_exists( 'GGM_Commerce_Subscriptions' ) && GGM_Commerce_Subscriptions::is_activated();
                ?>
                <div class="ggmc-product-section" data-section="subscription-settings">
                    <h2>
                        <?php esc_html_e( 'Subscription Settings', 'ggm-commerce' ); ?>
                        <?php if ( ! $subscriptions_activated ) : ?>
                            <span class="dashicons dashicons-lock" style="color: #0F766E;" title="<?php esc_attr_e( 'Premium Feature', 'ggm-commerce' ); ?>"></span>
                        <?php endif; ?>
                    </h2>
                    <?php if ( $subscriptions_activated ) : ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Enable Subscription', 'ggm-commerce' ); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="is_subscription" id="is_subscription" value="1">
                                    <?php esc_html_e( 'This is a subscription product', 'ggm-commerce' ); ?>
                                </label>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" style="display:none;">
                            <th scope="row"><label><?php esc_html_e( 'Billing Cycle', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <?php esc_html_e( 'Every', 'ggm-commerce' ); ?>
                                <input type="number" name="subscription_interval" value="1" min="1" max="365" style="width: 60px;">
                                <select name="subscription_period">
                                    <?php foreach ( GGM_Commerce_Subscriptions::get_billing_periods() as $value => $label ) : ?>
                                        <option value="<?php echo esc_attr( $value ); ?>" <?php selected( 'month', $value ); ?>><?php echo esc_html( $label ); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" style="display:none;">
                            <th scope="row"><label><?php esc_html_e( 'Free Trial', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" name="subscription_trial_length" value="0" min="0" style="width: 60px;">
                                <select name="subscription_trial_period">
                                    <option value="day"><?php esc_html_e( 'day(s)', 'ggm-commerce' ); ?></option>
                                    <option value="week"><?php esc_html_e( 'week(s)', 'ggm-commerce' ); ?></option>
                                    <option value="month"><?php esc_html_e( 'month(s)', 'ggm-commerce' ); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e( 'Set to 0 for no trial period.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" style="display:none;">
                            <th scope="row"><label for="subscription_sign_up_fee"><?php esc_html_e( 'Sign-up Fee', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" name="subscription_sign_up_fee" value="0.00" min="0" step="0.01" style="width: 100px;">
                                <p class="description"><?php esc_html_e( 'One-time fee charged on first payment. Leave as 0 for none.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" style="display:none;">
                            <th scope="row"><label for="subscription_length"><?php esc_html_e( 'Subscription Length', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" name="subscription_length" value="0" min="0" style="width: 60px;">
                                <span><?php esc_html_e( 'billing cycles (0 = until cancelled)', 'ggm-commerce' ); ?></span>
                            </td>
                        </tr>
                    </table>
                    <script>
                    (function() {
                        var cb = document.getElementById('is_subscription');
                        if (cb) {
                            cb.addEventListener('change', function() {
                                var rows = document.querySelectorAll('.ggmc-subscription-options');
                                for (var i = 0; i < rows.length; i++) {
                                    rows[i].style.display = this.checked ? '' : 'none';
                                }
                            });
                        }
                    })();
                    </script>
                    <?php else : ?>
                    <p style="padding: 12px; color: #666;">
                        <?php esc_html_e( 'Subscription billing is a premium feature. Activate it in your license settings to enable recurring billing for this product.', 'ggm-commerce' ); ?>
                    </p>
                    <?php endif; ?>
                </div>

                <script>
                (function($) {
                    var availableProducts = <?php
                        // Get available simple products for component selection
                        global $wpdb;
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $simple_products = $wpdb->get_results(
                            "SELECT id, name, sku, price, stock
                             FROM {$wpdb->prefix}ggmc_products
                             WHERE (product_type = 'simple' OR product_type IS NULL OR product_type = '')
                             AND status = 'active'
                             ORDER BY name ASC"
                        );
                        echo wp_json_encode($simple_products ?: array());
                    ?>;

                    var componentCount = <?php echo count($dup_kit_components); ?>;

                    // Toggle kit and gift card section visibility based on product type
                    function toggleKitSection() {
                        var productType = $('#product_type').val();
                        if (productType === 'kit' || productType === 'build') {
                            $('#kit-components-section').slideDown();
                        } else {
                            $('#kit-components-section').slideUp();
                        }
                        // Toggle gift card section
                        if (productType === 'gift_card') {
                            $('#gift-card-section').slideDown();
                        } else {
                            $('#gift-card-section').slideUp();
                        }
                    }

                    // Populate product dropdown
                    function populateProductDropdown() {
                        var $select = $('#kit-component-select');
                        $select.empty();
                        $select.append('<option value="">Select a product to add...</option>');

                        // Get currently added product IDs
                        var addedIds = [];
                        $('#kit-components-list .kit-component-row').each(function() {
                            addedIds.push($(this).data('product-id'));
                        });

                        $.each(availableProducts, function(i, product) {
                            if (addedIds.indexOf(parseInt(product.id)) === -1) {
                                var label = product.name;
                                if (product.sku) label += ' (' + product.sku + ')';
                                label += ' - $' + parseFloat(product.price).toFixed(2);
                                label += ' [Stock: ' + product.stock + ']';
                                $select.append('<option value="' + product.id + '" data-price="' + product.price + '" data-stock="' + product.stock + '">' + label + '</option>');
                            }
                        });
                    }

                    // Add component row
                    function addComponent(productId, productName, qty, price, stock) {
                        var $row = $('<div class="ggmc-kit-component-row kit-component-row" data-product-id="' + productId + '">');
                        $row.append('<span class="component-name">' + productName + '</span>');
                        $row.append('<input type="hidden" name="kit_components[product_id][]" value="' + productId + '" />');
                        $row.append('<label>Qty:</label>');
                        $row.append('<input type="number" name="kit_components[quantity][]" value="' + qty + '" min="1" class="component-qty" data-price="' + price + '" data-stock="' + stock + '" />');
                        $row.append('<span class="component-stock">(Stock: ' + stock + ')</span>');
                        $row.append('<span class="component-remove dashicons dashicons-no-alt" title="Remove"></span>');

                        $('#kit-components-list').append($row);
                        componentCount++;
                        updateKitStats();
                        populateProductDropdown();
                    }

                    // Update kit statistics
                    function updateKitStats() {
                        var totalPrice = 0;
                        var maxCreatable = Infinity;
                        var limitingProduct = '';

                        $('#kit-components-list .kit-component-row').each(function() {
                            var $row = $(this);
                            var $qty = $row.find('.component-qty');
                            var price = parseFloat($qty.data('price')) || 0;
                            var stock = parseInt($qty.data('stock')) || 0;
                            var qty = parseInt($qty.val()) || 1;

                            totalPrice += price * qty;

                            if (qty > 0) {
                                var possible = Math.floor(stock / qty);
                                if (possible < maxCreatable) {
                                    maxCreatable = possible;
                                    limitingProduct = $row.find('.component-name').text();
                                }
                            }
                        });

                        if (componentCount > 0) {
                            $('#kit-stats').show();
                            $('#kit-calc-price').text('$' + totalPrice.toFixed(2));
                            if (maxCreatable === Infinity) maxCreatable = 0;
                            $('#kit-max-creatable').text(maxCreatable + ' units');
                            if (limitingProduct && maxCreatable < 100) {
                                $('#kit-limiting-factor').text('Limited by: ' + limitingProduct).show();
                            } else {
                                $('#kit-limiting-factor').hide();
                            }
                        } else {
                            $('#kit-stats').hide();
                        }
                    }

                    $(document).ready(function() {
                        // Initial setup
                        toggleKitSection();
                        populateProductDropdown();
                        updateKitStats();  // Update stats for pre-populated components

                        // Product type change
                        $('#product_type').on('change', toggleKitSection);

                        // Add component button
                        $('#add-kit-component').on('click', function() {
                            var $select = $('#kit-component-select');
                            var productId = $select.val();
                            if (!productId) return;

                            var $option = $select.find('option:selected');
                            var productName = $option.text().split(' - ')[0];
                            var price = $option.data('price');
                            var stock = $option.data('stock');
                            var qty = parseInt($('#kit-component-qty').val()) || 1;

                            addComponent(productId, productName, qty, price, stock);
                            $('#kit-component-qty').val(1);
                        });

                        // Remove component
                        $(document).on('click', '.component-remove', function() {
                            $(this).closest('.kit-component-row').remove();
                            componentCount--;
                            updateKitStats();
                            populateProductDropdown();
                        });

                        // Update stats when quantity changes
                        $(document).on('change', '.component-qty', updateKitStats);
                    });
                })(jQuery);
                </script>

                <!-- Section 2: Description -->
                <div class="ggmc-product-section" data-section="description">
                    <h2>Description</h2>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="product_description">Full Description</label></th>
                            <td>
                                <?php
                                $description_content = $is_duplicate ? ($duplicate_data['description'] ?? '') : '';
                                wp_editor($description_content, 'product_description', array('textarea_rows' => 8));
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="short_description">Short Description</label></th>
                            <td><textarea name="short_description" id="short_description" rows="3" cols="50"><?php echo $is_duplicate ? esc_textarea($duplicate_data['short_description'] ?? '') : ''; ?></textarea></td>
                        </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Save Product</button>
                    </div>
                </div>

                <!-- Section 3: Pricing, Inventory & Specifications -->
                <div class="ggmc-product-section" data-section="pricing" data-section-group="pricing-inventory-specs">
                    <h2>Pricing, Inventory &amp; Specifications</h2>
                    <?php
                    $units_options = get_option('ggm_commerce_units_options', []);
                    $weight_unit = isset($units_options['weight_unit']) ? $units_options['weight_unit'] : 'kg';
                    $dimension_unit = isset($units_options['dimension_unit']) ? $units_options['dimension_unit'] : 'cm';
                    $attributes_activated = GGM_Commerce_License::instance()->is_widget_activated('custom-attributes');
                    $barcode_activated = GGM_Commerce_License::instance()->is_widget_activated('barcode');

                    // Get tax settings for price label
                    $tax = ggm_commerce_tax();
                    $tax_enabled = $tax->is_enabled();
                    $prices_include_tax = $tax->prices_include_tax();
                    $tax_label = $tax->get_label();
                    $price_tax_hint = '';
                    if ($tax_enabled) {
                        // Prices are always stored inclusive of tax
                        $price_tax_hint = sprintf(
                            /* translators: %s: tax label (e.g., "VAT", "GST") */
                            __('(incl. %s)', 'ggm-commerce'),
                            $tax_label
                        );
                    }
                    // Get tax rates for dropdown
                    $tax_rates = $tax_enabled ? $tax->get_tax_rates() : [];
                    $default_tax_rate = $tax_enabled ? $tax->get_default_tax_rate() : null;
                    ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="product_price"><?php esc_html_e('Price', 'ggm-commerce'); ?> <?php if ($price_tax_hint): ?><span class="description" style="font-weight: normal;"><?php echo esc_html($price_tax_hint); ?></span><?php endif; ?></label></th>
                            <td><input name="product_price" type="number" step="0.01" id="product_price" value="<?php echo $is_duplicate ? esc_attr($duplicate_data['price'] ?? '') : ''; ?>" class="small-text" required /></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_sale_price"><?php esc_html_e('Sale Price', 'ggm-commerce'); ?> <?php if ($price_tax_hint): ?><span class="description" style="font-weight: normal;"><?php echo esc_html($price_tax_hint); ?></span><?php endif; ?></label></th>
                            <td><input name="product_sale_price" type="number" step="0.01" id="product_sale_price" value="<?php echo $is_duplicate && !empty($duplicate_data['sale_price']) ? esc_attr($duplicate_data['sale_price']) : ''; ?>" class="small-text" /></td>
                        </tr>
                        <?php if ($tax_enabled && !empty($tax_rates)): ?>
                        <tr>
                            <th scope="row"><label for="tax_rate_id"><?php echo esc_html($tax_label); ?> <?php esc_html_e('Rate', 'ggm-commerce'); ?></label></th>
                            <td>
                                <select name="tax_rate_id" id="tax_rate_id">
                                    <?php foreach ($tax_rates as $rate): ?>
                                        <option value="<?php echo esc_attr($rate->id); ?>" <?php selected($default_tax_rate && $default_tax_rate->id == $rate->id); ?>>
                                            <?php echo esc_html($rate->name); ?> (<?php echo esc_html(number_format($rate->rate, 2)); ?>%)
                                            <?php if ($rate->is_default): ?>(<?php esc_html_e('Default', 'ggm-commerce'); ?>)<?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <tr>
                            <th scope="row"><label for="manage_stock">Manage Stock</label></th>
                            <td>
                                <label>
                                    <input name="manage_stock" type="checkbox" id="manage_stock" value="1" checked />
                                    Enable stock management for this product
                                </label>
                                <p class="description">When disabled, this product can be purchased without stock limits.</p>
                            </td>
                        </tr>
                        <tr class="ggmc-stock-fields">
                            <th scope="row"><label for="stock_quantity">Stock Quantity</label></th>
                            <td>
                                <input name="stock_quantity" type="number" id="stock_quantity" value="<?php echo $is_duplicate ? '0' : '0'; ?>" class="small-text" />
                                <?php if ($is_duplicate): ?>
                                <p class="description">Stock starts at 0 for duplicates. Adjust as needed.</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr class="ggmc-stock-fields">
                            <th scope="row"><label for="low_stock_threshold">Low Stock Threshold</label></th>
                            <td>
                                <input name="low_stock_threshold" type="number" id="low_stock_threshold" value="10" class="small-text" min="0" />
                                <p class="description">You will be notified when stock falls to this level.</p>
                            </td>
                        </tr>
                        <tr class="ggmc-stock-fields">
                            <th scope="row"><label for="restock_date">Expected Restock Date</label></th>
                            <td>
                                <input name="restock_date" type="date" id="restock_date" value="" class="regular-text" />
                                <p class="description">Optional. Shown to customers when the product is out of stock.</p>
                            </td>
                        </tr>
                        <script>
                        (function() {
                            var cb = document.getElementById('manage_stock');
                            function toggleStockFields() {
                                var rows = document.querySelectorAll('.ggmc-stock-fields');
                                for (var i = 0; i < rows.length; i++) {
                                    rows[i].style.display = cb.checked ? '' : 'none';
                                }
                            }
                            cb.addEventListener('change', toggleStockFields);
                            toggleStockFields();
                        })();
                        </script>
                        <tr>
                            <th scope="row"><label for="product_weight">Weight</label></th>
                            <td>
                                <input name="product_weight" type="number" step="0.01" id="product_weight" value="<?php echo $is_duplicate && !empty($duplicate_data['weight']) ? esc_attr($duplicate_data['weight']) : ''; ?>" class="small-text" />
                                <span class="description"><?php echo esc_html($weight_unit); ?></span>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_dimensions">Dimensions (L × W × H)</label></th>
                            <td>
                                <input name="product_length" type="number" step="0.01" id="product_length" value="<?php echo $is_duplicate && !empty($duplicate_data['length']) ? esc_attr($duplicate_data['length']) : ''; ?>" class="small-text" placeholder="Length" />
                                <span>×</span>
                                <input name="product_width" type="number" step="0.01" id="product_width" value="<?php echo $is_duplicate && !empty($duplicate_data['width']) ? esc_attr($duplicate_data['width']) : ''; ?>" class="small-text" placeholder="Width" />
                                <span>×</span>
                                <input name="product_height" type="number" step="0.01" id="product_height" value="<?php echo $is_duplicate && !empty($duplicate_data['height']) ? esc_attr($duplicate_data['height']) : ''; ?>" class="small-text" placeholder="Height" />
                                <span class="description"><?php echo esc_html($dimension_unit); ?></span>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label>Custom Attributes</label>
                                <?php if (!$attributes_activated): ?>
                                    <span class="dashicons dashicons-lock" style="color: #0F766E; margin-left: 5px;" title="Premium Feature"></span>
                                <?php endif; ?>
                            </th>
                            <td>
                                <?php if ($attributes_activated): ?>
                                    <?php
                                    $attributes_manager = GGM_Commerce_Attributes::get_instance();
                                    $all_attributes = $attributes_manager->get_all_attributes();
                                    $attribute_groups = $attributes_manager->get_attribute_groups();
                                    ?>
                                    <div class="ggmc-custom-attributes-section">
                                        <div class="ggmc-attribute-actions" style="margin-bottom: 15px;">
                                            <select id="add-single-attribute" style="width: 200px;">
                                                <option value="">-- Add Attribute --</option>
                                                <?php foreach ($all_attributes as $attr): ?>
                                                    <option value="<?php echo esc_attr($attr->id); ?>"
                                                            data-type="<?php echo esc_attr($attr->attribute_type); ?>"
                                                            data-options="<?php echo esc_attr($attr->options); ?>"
                                                            data-unit="<?php echo esc_attr($attr->unit); ?>"
                                                            data-name="<?php echo esc_attr($attr->name); ?>">
                                                        <?php echo esc_html($attr->name); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <?php if (!empty($attribute_groups)): ?>
                                            <select id="add-from-group" style="width: 200px; margin-left: 10px;">
                                                <option value="">-- Add from Group --</option>
                                                <?php foreach ($attribute_groups as $group): ?>
                                                    <option value="<?php echo esc_attr($group->id); ?>">
                                                        <?php echo esc_html($group->name); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <?php endif; ?>
                                        </div>
                                        <div id="custom-attributes-container">
                                            <!-- Attributes will be added here dynamically -->
                                        </div>
                                        <?php if (empty($all_attributes)): ?>
                                        <p class="description" style="color: #999;">
                                            No custom attributes defined yet. <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes')); ?>">Create attributes</a> first.
                                        </p>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="ggmc-premium-notice">
                                        <strong>Premium Feature</strong>
                                        <p>Add custom attributes like specifications, dimensions, and more to your products.</p>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>" class="button">Activate Custom Attributes</a>
                                    </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label>Product Barcodes</label>
                                <?php if (!$barcode_activated): ?>
                                    <span class="dashicons dashicons-lock" style="color: #0F766E; margin-left: 5px;" title="Premium Feature"></span>
                                <?php endif; ?>
                            </th>
                            <td>
                                <?php if ($barcode_activated): ?>
                                    <div class="ggmc-info-notice">
                                        <span class="dashicons dashicons-info"></span>
                                        <strong>Barcodes can be added after the product is created.</strong>
                                        <p>Save this product first, then edit it to add EAN, UPC, QR codes and other barcodes.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="ggmc-premium-notice">
                                        <strong>Premium Feature</strong>
                                        <p>Add EAN, UPC, QR codes and other barcodes to your products.</p>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>" class="button">Activate Barcode Feature</a>
                                    </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Save Product</button>
                    </div>
                </div>

                <!-- Section 4: Images -->
                <?php
                $dup_main_image_id = $is_duplicate ? ($duplicate_data['featured_image_id'] ?? '') : '';
                $dup_gallery_ids = $is_duplicate ? ($duplicate_data['gallery_image_ids'] ?? '') : '';
                $dup_main_image_url = $dup_main_image_id ? wp_get_attachment_image_url($dup_main_image_id, 'thumbnail') : '';
                ?>
                <div class="ggmc-product-section" data-section="images">
                    <h2>Product Images</h2>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="main_image">Main Image</label></th>
                            <td>
                                <div class="ggmc-image-upload">
                                    <input type="hidden" name="main_image_id" id="main_image_id" value="<?php echo esc_attr($dup_main_image_id); ?>" />
                                    <div id="main_image_preview" class="image-preview">
                                        <?php if ($dup_main_image_url): ?>
                                            <img src="<?php echo esc_url($dup_main_image_url); ?>" style="max-width: 150px; height: auto;" />
                                        <?php endif; ?>
                                    </div>
                                    <button type="button" class="button upload-image-button" data-target="main_image">Choose Main Image</button>
                                    <button type="button" class="button remove-image-button" data-target="main_image" style="<?php echo $dup_main_image_id ? '' : 'display: none;'; ?>">Remove Image</button>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gallery_images">Gallery Images</label></th>
                            <td>
                                <div class="ggmc-gallery-upload">
                                    <input type="hidden" name="gallery_image_ids" id="gallery_image_ids" value="<?php echo esc_attr($dup_gallery_ids); ?>" />
                                    <div id="gallery_images_preview" class="gallery-preview">
                                        <?php
                                        if ($dup_gallery_ids) {
                                            $gallery_ids_array = explode(',', $dup_gallery_ids);
                                            foreach ($gallery_ids_array as $img_id) {
                                                $img_url = wp_get_attachment_image_url(trim($img_id), 'thumbnail');
                                                if ($img_url) {
                                                    echo '<div class="gallery-image" data-id="' . esc_attr($img_id) . '">';
                                                    echo '<img src="' . esc_url($img_url) . '" style="max-width: 100px; height: auto; margin: 2px;" />';
                                                    echo '<span class="remove-gallery-image dashicons dashicons-no-alt"></span>';
                                                    echo '</div>';
                                                }
                                            }
                                        }
                                        ?>
                                    </div>
                                    <button type="button" class="button upload-gallery-button" data-target="gallery_images">Add Gallery Images</button>
                                    <button type="button" class="button remove-all-gallery-button" data-target="gallery_images" style="<?php echo $dup_gallery_ids ? '' : 'display: none;'; ?>">Remove All</button>
                                    <p class="description">Hold Ctrl/Cmd to select multiple images</p>
                                </div>
                            </td>
                        </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Save Product</button>
                    </div>
                </div>

                <!-- Section 5: Categories & Tags -->
                <div class="ggmc-product-section" data-section="categories">
                    <h2>Categories &amp; Tags</h2>
                    <?php
                    $taxonomy = GGM_Commerce_Taxonomy::get_instance();
                    $categories = $taxonomy->get_categories();
                    $uncategorised = $taxonomy->get_uncategorised_category();
                    $tags = $taxonomy->get_tags();
                    $dup_categories = $is_duplicate ? ($duplicate_data['categories'] ?? []) : [];
                    $dup_tags = $is_duplicate ? ($duplicate_data['tags'] ?? []) : [];
                    ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="product_categories">Categories</label></th>
                            <td>
                                <select name="product_categories[]" id="product_categories" multiple size="6" style="width: 300px;">
                                    <?php foreach ($categories as $category): ?>
                                        <?php
                                        $is_selected = $is_duplicate
                                            ? in_array($category->id, $dup_categories)
                                            : ($category->id == $uncategorised->id);
                                        ?>
                                        <option value="<?php echo esc_attr($category->id); ?>" <?php selected($is_selected); ?>>
                                            <?php echo esc_html($category->name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description">Hold Ctrl/Cmd to select multiple categories. Defaults to "Uncategorised" if none selected.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_tags">Tags</label></th>
                            <td>
                                <select name="product_tags[]" id="product_tags" multiple size="6" style="width: 300px;">
                                    <?php foreach ($tags as $tag): ?>
                                        <option value="<?php echo esc_attr($tag->id); ?>" <?php selected($is_duplicate && in_array($tag->id, $dup_tags)); ?>>
                                            <?php echo esc_html($tag->name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description">Hold Ctrl/Cmd to select multiple tags. Optional.</p>
                            </td>
                        </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Save Product</button>
                    </div>
                </div>
            </form>
        </div>


        <script>
        jQuery(document).ready(function($) {
            // WordPress media uploader
            var mediaUploader;
            var galleryUploader;

            // Main image uploader
            $('.upload-image-button').click(function(e) {
                e.preventDefault();
                
                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }
                
                mediaUploader = wp.media({
                    title: 'Choose Main Product Image',
                    button: {
                        text: 'Choose Image'
                    },
                    multiple: false
                });
                
                mediaUploader.on('select', function() {
                    var attachment = mediaUploader.state().get('selection').first().toJSON();
                    $('#main_image_id').val(attachment.id);
                    
                    var imageHtml = '<div class="image-item" data-id="' + attachment.id + '">' +
                                   '<img src="' + attachment.url + '" alt="Main Product Image" />' +
                                   '<span class="remove-single-image" data-id="' + attachment.id + '">&times;</span>' +
                                   '</div>';
                    
                    $('#main_image_preview').html(imageHtml);
                    $('.remove-image-button[data-target="main_image"]').show();
                });
                
                mediaUploader.open();
            });
            
            // Gallery images uploader
            $('.upload-gallery-button').click(function(e) {
                e.preventDefault();
                
                if (galleryUploader) {
                    galleryUploader.open();
                    return;
                }
                
                galleryUploader = wp.media({
                    title: 'Choose Gallery Images',
                    button: {
                        text: 'Add to Gallery'
                    },
                    multiple: true
                });
                
                galleryUploader.on('select', function() {
                    var attachments = galleryUploader.state().get('selection').toJSON();
                    var currentIds = $('#gallery_image_ids').val();
                    var idsArray = currentIds ? currentIds.split(',') : [];
                    
                    $.each(attachments, function(index, attachment) {
                        if (idsArray.indexOf(attachment.id.toString()) === -1) {
                            idsArray.push(attachment.id);
                            
                            var imageHtml = '<div class="image-item" data-id="' + attachment.id + '">' +
                                           '<img src="' + attachment.url + '" alt="Gallery Image" />' +
                                           '<span class="remove-single-image" data-id="' + attachment.id + '">&times;</span>' +
                                           '</div>';
                            
                            $('#gallery_images_preview').append(imageHtml);
                        }
                    });
                    
                    $('#gallery_image_ids').val(idsArray.join(','));
                    $('.remove-all-gallery-button[data-target="gallery_images"]').show();
                });
                
                galleryUploader.open();
            });
            
            // Remove single main image
            $(document).on('click', '.remove-image-button[data-target="main_image"]', function() {
                $('#main_image_id').val('');
                $('#main_image_preview').empty();
                $(this).hide();
            });
            
            // Remove single gallery image
            $(document).on('click', '.remove-single-image', function() {
                var imageId = $(this).data('id').toString();
                var currentIds = $('#gallery_image_ids').val();
                var idsArray = currentIds ? currentIds.split(',') : [];
                var index = idsArray.indexOf(imageId);
                
                if (index > -1) {
                    idsArray.splice(index, 1);
                }
                
                $('#gallery_image_ids').val(idsArray.join(','));
                $(this).parent().remove();
                
                if (idsArray.length === 0) {
                    $('.remove-all-gallery-button[data-target="gallery_images"]').hide();
                }
            });
            
            // Remove all gallery images
            $(document).on('click', '.remove-all-gallery-button[data-target="gallery_images"]', function() {
                $('#gallery_image_ids').val('');
                $('#gallery_images_preview').empty();
                $(this).hide();
            });

            <?php if (GGM_Commerce_License::instance()->is_widget_activated('custom-attributes')):
                $attributes_manager = GGM_Commerce_Attributes::get_instance();
            ?>
            // Custom Attributes Management
            var attributeIndex = 0;
            var groupAttributes = <?php echo wp_json_encode($attributes_manager->get_group_attributes_map_v2()); ?>;

            // Add single attribute
            $('#add-single-attribute').on('change', function() {
                var $selected = $(this).find('option:selected');
                var attrId = $selected.val();
                if (!attrId) return;

                var attrName = $selected.data('name');
                var attrType = $selected.data('type');
                var attrOptions = $selected.data('options');
                var attrUnit = $selected.data('unit') || '';

                addAttributeRow(attrId, attrName, attrType, attrOptions, attrUnit);

                // Remove from dropdown and reset
                $selected.remove();
                $(this).val('');
            });

            // Add from group
            $('#add-from-group').on('change', function() {
                var groupId = $(this).val();
                if (!groupId || !groupAttributes[groupId]) return;

                var attrs = groupAttributes[groupId];
                attrs.forEach(function(attr) {
                    // Check if attribute already exists
                    if ($('.ggmc-attribute-row[data-attribute-id="' + attr.id + '"]').length === 0) {
                        addAttributeRow(attr.id, attr.name, attr.attribute_type, attr.options, attr.unit || '');
                        // Remove from single attribute dropdown
                        $('#add-single-attribute option[value="' + attr.id + '"]').remove();
                    }
                });

                $(this).val('');
            });

            // Add attribute row helper
            function addAttributeRow(attrId, attrName, attrType, attrOptions, attrUnit) {
                var valueInput = '';
                if (attrType === 'select' && attrOptions) {
                    var options = typeof attrOptions === 'string' ? JSON.parse(attrOptions) : attrOptions;
                    if (Array.isArray(options) && options.length > 0) {
                        valueInput = '<select name="custom_attributes[' + attributeIndex + '][value]" style="width: 200px;"><option value="">-- Select --</option>';
                        options.forEach(function(opt) {
                            valueInput += '<option value="' + escapeHtml(opt) + '">' + escapeHtml(opt) + '</option>';
                        });
                        valueInput += '</select>';
                    } else {
                        valueInput = '<input type="text" name="custom_attributes[' + attributeIndex + '][value]" value="" style="width: 200px;" />';
                    }
                } else if (attrType === 'number') {
                    valueInput = '<input type="number" step="any" name="custom_attributes[' + attributeIndex + '][value]" value="" style="width: 150px;" />';
                } else {
                    valueInput = '<input type="text" name="custom_attributes[' + attributeIndex + '][value]" value="" style="width: 200px;" />';
                }

                var unitSpan = attrUnit ? '<span class="attr-unit" style="color: #666;">' + escapeHtml(attrUnit) + '</span>' : '<span class="attr-unit"></span>';

                var rowHtml = '<div class="ggmc-attribute-row" data-attribute-id="' + attrId + '" style="margin-bottom: 10px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">' +
                    '<div style="display: grid; grid-template-columns: auto 150px 1fr auto auto; gap: 10px; align-items: center;">' +
                        '<span class="dashicons dashicons-menu ggmc-drag-handle" style="cursor: grab; color: #999;"></span>' +
                        '<input type="hidden" name="custom_attributes[' + attributeIndex + '][attribute_id]" value="' + attrId + '" />' +
                        '<input type="hidden" name="custom_attributes[' + attributeIndex + '][display_order]" class="attr-order" value="' + attributeIndex + '" />' +
                        '<label style="font-weight: 500;">' + escapeHtml(attrName) + '</label>' +
                        valueInput +
                        unitSpan +
                        '<button type="button" class="button remove-attribute-btn" data-attribute-id="' + attrId + '">&times;</button>' +
                    '</div>' +
                '</div>';

                $('#custom-attributes-container').append(rowHtml);
                attributeIndex++;
                updateAttributeOrder();
            }

            // Remove attribute
            $(document).on('click', '.remove-attribute-btn', function(e) {
                e.preventDefault();
                e.stopPropagation();

                var $row = $(this).closest('.ggmc-attribute-row');
                $row.remove();
                updateAttributeOrder();
            });

            // Update display order values
            function updateAttributeOrder() {
                $('#custom-attributes-container .ggmc-attribute-row').each(function(index) {
                    $(this).find('.attr-order').val(index);
                });
            }

            // Helper function to escape HTML
            function escapeHtml(text) {
                if (!text) return '';
                var div = document.createElement('div');
                div.appendChild(document.createTextNode(text));
                return div.innerHTML;
            }

            // Make sortable if jQuery UI is available
            if ($.fn.sortable) {
                $('#custom-attributes-container').sortable({
                    handle: '.ggmc-drag-handle',
                    update: function() {
                        updateAttributeOrder();
                    }
                });
            }
            <?php endif; ?>

            // Product Type visibility controller
            var productTypeSections = <?php echo wp_json_encode(GGM_Commerce_Helpers::get_product_types()); ?>;

            function updateSectionVisibility() {
                var selectedType = $('#product_type').val();
                var typeConfig = productTypeSections[selectedType];

                if (!typeConfig) {
                    typeConfig = productTypeSections['simple'];
                }

                var visibleSections = typeConfig.sections || [];

                // Show/hide sections based on product type
                $('[data-section]').each(function() {
                    var sectionKey = $(this).data('section');
                    if (visibleSections.indexOf(sectionKey) !== -1) {
                        $(this).slideDown(200);
                    } else {
                        $(this).slideUp(200);
                    }
                });

                // Check if premium type is selected but not available
                var selectedOption = $('#product_type option:selected');
                var isAvailable = selectedOption.data('available') === true || selectedOption.data('available') === 'true';

                if (!isAvailable) {
                    // Show premium upgrade prompt
                    $('#product-type-description').html(
                        '<span style="color: #d63638;">This product type requires premium activation. ' +
                        '<a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>">Activate Premium Features</a></span>'
                    );
                } else {
                    $('#product-type-description').text('<?php echo esc_js(__('Select the type of product. Premium types show 🔒 if not activated.', 'ggm-commerce')); ?>');
                }
            }

            // Bind change event to product type dropdown
            $('#product_type').on('change', updateSectionVisibility);

            // Initial visibility update (only if dropdown exists)
            if ($('#product_type').length) {
                updateSectionVisibility();
            }
        });
        </script>
        <?php
    }

    /**
     * Edit product page implementation
     */
    public function edit_product_page() {
        global $wpdb, $title;

        // Set default title to avoid null warnings
        if (empty($title)) {
            $title = 'Edit Product';
        }

        $product_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        
        if (!$product_id) {
            wp_die('Invalid product ID');
        }
        
        $products_table = $wpdb->prefix . 'ggmc_products';

        // Check if table exists before querying
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $products_table)) === $products_table;

        if (!$table_exists) {
            wp_die('Products table does not exist. Please activate the plugin properly.');
        }

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $product = $wpdb->get_row($wpdb->prepare("SELECT * FROM $products_table WHERE id = %d", $product_id));

        if (!$product) {
            wp_die('Product not found');
        }

        // Update title with product name
        $product_name = !empty($product->name) ? $product->name : 'Untitled Product';
        $title = 'Edit Product: ' . $product_name;

        // Handle form submission
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        // Note: Check for nonce presence instead of submit button name (which can be unreliable)
        if (isset($_POST['ggm_commerce_nonce']) && wp_verify_nonce($_POST['ggm_commerce_nonce'], 'ggm_commerce_edit_product')) {
            $product_name = isset($_POST['product_name']) ? sanitize_text_field(wp_unslash($_POST['product_name'])) : '';
            $custom_slug = isset($_POST['product_slug']) ? sanitize_title(wp_unslash($_POST['product_slug'])) : '';

            // Determine slug: use custom slug if provided, otherwise auto-generate
            if (!empty($custom_slug)) {
                // Validate custom slug is unique (excluding current product)
                global $wpdb;
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $existing = $wpdb->get_var($wpdb->prepare(
                    "SELECT id FROM {$wpdb->prefix}ggmc_products WHERE slug = %s AND id != %d",
                    $custom_slug,
                    $product_id
                ));
                if ($existing) {
                    // Custom slug already exists, append number to make unique
                    $slug = GGM_Commerce_Database::generate_unique_slug($custom_slug, $product_id);
                } else {
                    $slug = $custom_slug;
                }
            } elseif ($product_name !== $product->name || empty($product->slug)) {
                // Auto-generate slug if name changed or no existing slug
                $slug = GGM_Commerce_Database::generate_unique_slug($product_name, $product_id);
            } else {
                // Keep existing slug
                $slug = $product->slug;
            }

            // Validate and sanitize status
            $valid_statuses = array_keys($this->get_product_status_labels());
            $product_status = isset($_POST['product_status']) ? sanitize_text_field(wp_unslash($_POST['product_status'])) : $product->status;
            if (!in_array($product_status, $valid_statuses)) {
                $product_status = self::PRODUCT_STATUS_ACTIVE;
            }

            // Validate product type using centralized configuration
            $valid_product_types = array_keys(GGM_Commerce_Helpers::get_product_types());
            $product_type = isset($_POST['product_type']) ? sanitize_text_field(wp_unslash($_POST['product_type'])) : ($product->product_type ?? 'simple');
            if (!in_array($product_type, $valid_product_types, true)) {
                $product_type = 'simple';
            }

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $result = $wpdb->update(
                $products_table,
                array(
                    'name' => $product_name,
                    'slug' => $slug,
                    'description' => isset($_POST['product_description']) ? wp_kses_post(wp_unslash($_POST['product_description'])) : '',
                    'price' => isset($_POST['product_price']) ? floatval(wp_unslash($_POST['product_price'])) : 0,
                    'sale_price' => !empty($_POST['product_sale_price']) ? floatval(wp_unslash($_POST['product_sale_price'])) : null,
                    'stock' => isset($_POST['stock_quantity']) ? intval(wp_unslash($_POST['stock_quantity'])) : 0,
                    'manage_stock' => isset($_POST['manage_stock']) ? 1 : 0,
                    'stock_status' => isset($_POST['manage_stock']) ? (intval($_POST['stock_quantity'] ?? 0) > 0 ? 'instock' : 'outofstock') : 'instock',
                    'low_stock_threshold' => isset($_POST['low_stock_threshold']) ? intval(wp_unslash($_POST['low_stock_threshold'])) : 10,
                    'restock_date' => !empty($_POST['restock_date']) ? sanitize_text_field(wp_unslash($_POST['restock_date'])) : null,
                    'sku' => isset($_POST['sku']) ? sanitize_text_field(wp_unslash($_POST['sku'])) : '',
                    'short_description' => isset($_POST['short_description']) ? sanitize_textarea_field(wp_unslash($_POST['short_description'])) : '',
                    'weight' => !empty($_POST['product_weight']) ? floatval(wp_unslash($_POST['product_weight'])) : null,
                    'length' => !empty($_POST['product_length']) ? floatval(wp_unslash($_POST['product_length'])) : null,
                    'width' => !empty($_POST['product_width']) ? floatval(wp_unslash($_POST['product_width'])) : null,
                    'height' => !empty($_POST['product_height']) ? floatval(wp_unslash($_POST['product_height'])) : null,
                    'image_id' => !empty($_POST['main_image_id']) ? intval(wp_unslash($_POST['main_image_id'])) : 0,
                    'gallery_ids' => isset($_POST['gallery_image_ids']) ? sanitize_text_field(wp_unslash($_POST['gallery_image_ids'])) : '',
                    'status' => $product_status,
                    'product_type' => $product_type,
                    'tax_rate_id' => !empty($_POST['tax_rate_id']) ? intval(wp_unslash($_POST['tax_rate_id'])) : null,
                    'gift_card_value' => $product_type === 'gift_card' && isset($_POST['gift_card_value']) && $_POST['gift_card_value'] !== '' ? floatval(wp_unslash($_POST['gift_card_value'])) : null,
                    'gift_card_type' => $product_type === 'gift_card' && isset($_POST['gift_card_type']) ? sanitize_text_field(wp_unslash($_POST['gift_card_type'])) : 'fixed',
                    'gift_card_single_use' => $product_type === 'gift_card' && isset($_POST['gift_card_single_use']) ? 1 : 0,
                    'gift_card_valid_days' => $product_type === 'gift_card' && isset($_POST['gift_card_valid_days']) && $_POST['gift_card_valid_days'] !== '' ? intval(wp_unslash($_POST['gift_card_valid_days'])) : null,
                    'gift_card_code_prefix' => $product_type === 'gift_card' && isset($_POST['gift_card_code_prefix']) ? sanitize_text_field(wp_unslash($_POST['gift_card_code_prefix'])) : 'GC',
                    'is_subscription' => isset($_POST['is_subscription']) ? 1 : 0,
                    'subscription_period' => isset($_POST['subscription_period']) ? sanitize_text_field(wp_unslash($_POST['subscription_period'])) : 'month',
                    'subscription_interval' => isset($_POST['subscription_interval']) ? intval(wp_unslash($_POST['subscription_interval'])) : 1,
                    'subscription_trial_length' => isset($_POST['subscription_trial_length']) ? intval(wp_unslash($_POST['subscription_trial_length'])) : 0,
                    'subscription_trial_period' => isset($_POST['subscription_trial_period']) ? sanitize_text_field(wp_unslash($_POST['subscription_trial_period'])) : 'day',
                    'subscription_sign_up_fee' => isset($_POST['subscription_sign_up_fee']) ? floatval(wp_unslash($_POST['subscription_sign_up_fee'])) : 0.00,
                    'subscription_length' => isset($_POST['subscription_length']) ? intval(wp_unslash($_POST['subscription_length'])) : 0,
                    'updated_at' => current_time('mysql')
                ),
                array('id' => $product_id),
                array('%s', '%s', '%s', '%f', '%f', '%d', '%d', '%s', '%d', '%s', '%s', '%f', '%f', '%f', '%f', '%d', '%s', '%s', '%s', '%d', '%f', '%s', '%d', '%d', '%s', '%d', '%s', '%d', '%d', '%s', '%f', '%d', '%s'),
                array('%d')
            );

            if ($result !== false) {
                // Handle categories
                $taxonomy = GGM_Commerce_Taxonomy::get_instance();
                $category_ids = isset($_POST['product_categories']) ? array_map('intval', (array)$_POST['product_categories']) : [];
                $taxonomy->set_product_categories($product_id, $category_ids);

                // Handle tags
                $tag_ids = isset($_POST['product_tags']) ? array_map('intval', (array)$_POST['product_tags']) : [];
                $taxonomy->set_product_tags($product_id, $tag_ids);

                // Clear filter caches (price range may have changed)
                GGM_Commerce_Taxonomy::clear_price_range_cache();

                // Handle barcodes (premium feature)
                $barcode_save_result = true;
                if (GGM_Commerce_License::instance()->is_widget_activated('barcode')) {
                    $barcode_manager = GGM_Commerce_Barcode::get_instance();
                    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Barcode data sanitized in save_product_barcodes method
                    $barcodes_data = isset($_POST['barcodes']) ? wp_unslash($_POST['barcodes']) : [];
                    $barcode_save_result = $barcode_manager->save_product_barcodes($product_id, $barcodes_data);
                }

                // Handle custom attributes (premium feature)
                if (GGM_Commerce_License::instance()->is_widget_activated('custom-attributes')) {
                    $attributes_manager = GGM_Commerce_Attributes::get_instance();
                    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Attributes data sanitized in set_product_attribute_values method
                    $attributes_data = isset($_POST['custom_attributes']) ? wp_unslash($_POST['custom_attributes']) : [];
                    $attributes_manager->set_product_attribute_values($product_id, $attributes_data);
                }

                // Handle kit/build updates (premium feature)
                if (GGM_Commerce_License::instance()->is_widget_activated('product-kits')) {
                    $kits_manager = GGM_Commerce_Kits::get_instance();
                    $existing_kit = $kits_manager->get_kit_by_product_id($product_id);
                    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Components data sanitized in methods
                    $components_data = isset($_POST['kit_components']) ? wp_unslash($_POST['kit_components']) : [];
                    $auto_price = isset($_POST['kit_auto_price']) && $_POST['kit_auto_price'] === '1';

                    // Parse components from form data
                    $components = array();
                    if (!empty($components_data['product_id'])) {
                        foreach ($components_data['product_id'] as $index => $comp_product_id) {
                            if (!empty($comp_product_id)) {
                                $components[] = array(
                                    'product_id' => absint($comp_product_id),
                                    'quantity' => absint($components_data['quantity'][$index] ?? 1),
                                );
                            }
                        }
                    }

                    if (in_array($product_type, array('kit', 'build'), true)) {
                        if ($existing_kit) {
                            // Update existing kit
                            $kits_manager->update_kit($existing_kit->id, $product_type, $auto_price);
                            $kits_manager->update_kit_components($existing_kit->id, $components);
                        } else {
                            // Create new kit
                            $kits_manager->create_kit($product_id, $product_type, $components, $auto_price);
                        }
                    } elseif ($existing_kit && $product_type === 'simple') {
                        // Changed from kit/build to simple, delete kit definition
                        $kits_manager->delete_kit($existing_kit->id);
                    }
                }

                // Handle variations (premium feature)
                if (GGM_Commerce_License::instance()->is_widget_activated('product-variations')) {
                    $variations_manager = GGM_Commerce_Variations::instance();
                    $has_variations = isset($_POST['has_variations']) && $_POST['has_variations'] === '1';
                    $variation_stock_mode = isset($_POST['variation_stock_mode']) ? sanitize_key(wp_unslash($_POST['variation_stock_mode'])) : 'parent';
                    $variation_mode = isset($_POST['variation_mode']) ? sanitize_key(wp_unslash($_POST['variation_mode'])) : 'combined';

                    // Update product variation settings
                    $variations_manager->set_product_has_variations($product_id, $has_variations, $variation_stock_mode);

                    // Update variation mode
                    $variations_manager->set_product_variation_mode($product_id, $variation_mode);

                    if ($has_variations) {
                        // Update variation attribute config
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Array of integers
                        $variation_attributes = isset($_POST['variation_attributes']) ? array_map('intval', (array) wp_unslash($_POST['variation_attributes'])) : array();
                        $variations_manager->set_product_variation_config($product_id, $variation_attributes);

                        // Update individual variations
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Variations data sanitized in loop
                        $variations_data = isset($_POST['variations']) ? wp_unslash($_POST['variations']) : array();
                        foreach ($variations_data as $variation_id => $data) {
                            $update_data = array();
                            if (isset($data['sku'])) {
                                $update_data['sku'] = sanitize_text_field($data['sku']);
                            }
                            if (isset($data['price']) && $data['price'] !== '') {
                                $update_data['price'] = floatval($data['price']);
                            }
                            if (isset($data['price_type'])) {
                                $price_type_value = sanitize_key($data['price_type']);
                                $update_data['price_type'] = in_array($price_type_value, array('absolute', 'modifier'), true) ? $price_type_value : 'absolute';
                            }
                            if (isset($data['stock'])) {
                                $update_data['stock'] = intval($data['stock']);
                            }
                            if (!empty($update_data)) {
                                $variations_manager->update_variation(intval($variation_id), $update_data);
                            }
                        }

                        // Handle default variation (Combined mode)
                        if (isset($_POST['default_variation'])) {
                            $default_id = intval(wp_unslash($_POST['default_variation']));
                            if ($default_id > 0) {
                                // Set this variation as default (will clear others automatically)
                                $variations_manager->update_variation($default_id, array('is_default' => 1));
                            } else {
                                // Clear all defaults - no pre-selected variation
                                $variations_manager->clear_default_variation($product_id);
                            }
                        }

                        // Handle Independent mode options
                        // With explicit add/remove model: options exist or don't (added/removed via AJAX)
                        // Form submission only updates modifiers and defaults for existing options
                        if ($variation_mode === 'independent' && isset($_POST['independent_options'])) {
                            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Options data sanitized in loop
                            $independent_options = wp_unslash($_POST['independent_options']);

                            foreach ($independent_options as $attr_id => $attr_options) {
                                $attr_id = intval($attr_id);
                                $default_value = isset($attr_options['default']) ? sanitize_text_field($attr_options['default']) : '';

                                // Update each submitted option's modifier
                                foreach ($attr_options as $opt_value => $opt_data) {
                                    // Skip the 'default' key which holds the radio value
                                    if ($opt_value === 'default') {
                                        continue;
                                    }

                                    $opt_value = sanitize_text_field($opt_value);
                                    $modifier = isset($opt_data['modifier']) ? floatval($opt_data['modifier']) : 0.00;

                                    // Update the option's price modifier
                                    $variations_manager->update_product_variation_option(
                                        $product_id,
                                        $attr_id,
                                        $opt_value,
                                        array('price_modifier' => $modifier)
                                    );
                                }

                                // Set the default option for this attribute
                                if ($default_value) {
                                    $variations_manager->set_default_option($product_id, $attr_id, $default_value);
                                }
                            }

                            // Force stock mode to 'parent' for independent mode
                            $variations_manager->set_product_has_variations($product_id, $has_variations, 'parent');
                        }
                    }
                }

                // Handle downloads and virtual product settings (premium feature)
                if (GGM_Commerce_License::instance()->is_widget_activated('downloads')) {
                    $virtual_helper = GGM_Commerce_Virtual_Products::instance();
                    $downloads_manager = GGM_Commerce_Downloads::instance();

                    $is_virtual = isset($_POST['is_virtual']) && $_POST['is_virtual'] === '1';
                    $is_downloadable = isset($_POST['is_downloadable']) && $_POST['is_downloadable'] === '1';
                    $download_access_mode = isset($_POST['download_access_mode']) ? sanitize_key(wp_unslash($_POST['download_access_mode'])) : 'unlimited';

                    // Update product settings
                    $virtual_helper->set_product_settings($product_id, array(
                        'is_virtual'           => $is_virtual,
                        'is_downloadable'      => $is_downloadable,
                        'requires_shipping'    => !$is_virtual, // Virtual products don't need shipping
                        'download_access_mode' => $download_access_mode,
                    ));

                    // Handle downloadable files
                    if ($is_downloadable) {
                        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Downloads data sanitized in loop
                        $downloads_data = isset($_POST['downloads']) ? wp_unslash($_POST['downloads']) : array();

                        // Get existing downloads to track which to delete
                        $existing_downloads = $downloads_manager->get_product_downloads($product_id, array('status' => 'all'));
                        $existing_ids = array_column($existing_downloads, 'id');
                        $submitted_ids = array();

                        foreach ($downloads_data as $index => $download) {
                            $file_name = isset($download['name']) ? sanitize_text_field($download['name']) : '';
                            $file_url = isset($download['file_url']) ? esc_url_raw($download['file_url']) : '';

                            if (empty($file_name) || empty($file_url)) {
                                continue;
                            }

                            $download_data = array(
                                'name'              => $file_name,
                                'file_url'          => $file_url,
                                'download_limit'    => isset($download['download_limit']) ? intval($download['download_limit']) : -1,
                                'access_expiry_days' => isset($download['access_expiry_days']) ? intval($download['access_expiry_days']) : -1,
                                'display_order'     => $index,
                            );

                            if (isset($download['id']) && !empty($download['id'])) {
                                // Update existing download
                                $download_id = intval($download['id']);
                                $downloads_manager->update_download($download_id, $download_data);
                                $submitted_ids[] = $download_id;
                            } else {
                                // Add new download
                                $new_id = $downloads_manager->add_download($product_id, $download_data);
                                if ($new_id) {
                                    $submitted_ids[] = $new_id;
                                }
                            }
                        }

                        // Delete downloads that were removed
                        foreach ($existing_ids as $existing_id) {
                            if (!in_array($existing_id, $submitted_ids)) {
                                $downloads_manager->delete_download($existing_id);
                            }
                        }
                    }
                }

                if (is_wp_error($barcode_save_result)) {
                    echo '<div class="notice notice-error"><p>Error saving barcodes: ' . esc_html($barcode_save_result->get_error_message()) . '</p></div>';
                } else {
                    echo '<div class="notice notice-success"><p>Product updated successfully!</p></div>';
                }

                // Refresh product data
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
                $product = $wpdb->get_row($wpdb->prepare("SELECT * FROM $products_table WHERE id = %d", $product_id));
            } else {
                echo '<div class="notice notice-error"><p>Error updating product: ' . esc_html($wpdb->last_error) . '</p></div>';
            }
        }
        
        ?>
        <div class="wrap ggmc-product-form">
            <p><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-products')); ?>">&larr; Back to Products</a></p>
            <?php self::page_title( 'Edit Product: ' . esc_html( $product->name ?? 'Untitled Product' ) ); ?>

            <form method="post" action="">
                <?php wp_nonce_field('ggm_commerce_edit_product', 'ggm_commerce_nonce'); ?>

                <!-- Section 1: Product Identity -->
                <div class="ggmc-product-section" data-section="identity">
                    <h2>Product Identity</h2>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="product_name">Product Name</label></th>
                            <td><input name="product_name" type="text" id="product_name" value="<?php echo esc_attr($product->name ?? ''); ?>" class="regular-text" required /></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_slug">URL Slug</label></th>
                            <td>
                                <input name="product_slug" type="text" id="product_slug" value="<?php echo esc_attr($product->slug ?? ''); ?>" class="regular-text" />
                                <p class="description">
                                    The URL-friendly version of the product name. Leave blank to auto-generate from name.
                                    <?php if (!empty($product->slug)): ?>
                                        <br>Current URL: <code><?php echo esc_html(GGM_Commerce_Helpers::get_product_details_url($product_id)); ?></code>
                                    <?php endif; ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="sku">SKU</label></th>
                            <td><input name="sku" type="text" id="sku" value="<?php echo esc_attr($product->sku ?? ''); ?>" class="regular-text" /></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_status">Status</label></th>
                            <td>
                                <?php
                                $status_labels = $this->get_product_status_labels();
                                $current_status = $product->status ?? self::PRODUCT_STATUS_ACTIVE;
                                ?>
                                <select name="product_status" id="product_status" style="width: 200px;">
                                    <?php foreach ($status_labels as $value => $label): ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($current_status, $value); ?>>
                                            <?php echo esc_html($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description">Set product visibility. Only Active products are visible on the frontend.</p>
                            </td>
                        </tr>
                        <?php
                        // Product Type selector - shows all types with premium locking
                        $product_type_options = GGM_Commerce_Helpers::get_product_type_options();
                        // Check if product has variations - if so, it's a variable product regardless of product_type field
                        $product_has_variations = false;
                        if (class_exists('GGM_Commerce_Variations')) {
                            $variations_manager_check = GGM_Commerce_Variations::instance();
                            $product_has_variations = $variations_manager_check->product_has_variations($product_id);
                        }
                        $current_product_type = $product_has_variations ? 'variable' : ($product->product_type ?? 'simple');
                        ?>
                        <tr>
                            <th scope="row"><label for="product_type">Product Type</label></th>
                            <td>
                                <select name="product_type" id="product_type" style="width: 250px;">
                                    <?php foreach ($product_type_options as $value => $option): ?>
                                        <option value="<?php echo esc_attr($value); ?>"
                                                <?php selected($value, $current_product_type); ?>
                                                <?php disabled(!$option['available']); ?>
                                                data-available="<?php echo $option['available'] ? 'true' : 'false'; ?>">
                                            <?php echo esc_html($option['label']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="description" id="product-type-description">
                                    <?php esc_html_e('Select the type of product. Premium types show 🔒 if not activated.', 'ggm-commerce'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

                <!-- Kit Components Section (shown when kit or build selected) -->
                <?php
                    $kits_activated = GGM_Commerce_Helpers::is_product_type_available('kit');
                    $kits_manager = GGM_Commerce_Kits::get_instance();
                    $existing_kit = $kits_manager->get_kit_by_product_id($product_id);
                    $existing_components = $existing_kit ? $kits_manager->get_kit_components($existing_kit->id) : array();
                    $components_locked = !empty($existing_kit) && !empty($existing_components);
                ?>
                <div class="ggmc-product-section" id="kit-components-section" data-section="kit-components" <?php echo !in_array($current_product_type, ['kit', 'build']) ? 'style="display: none;"' : ''; ?>>
                    <h2>Kit Components</h2>
                    <?php if ($components_locked): ?>
                    <div class="ggmc-components-locked-notice" style="background: #fff8e5; border-left: 4px solid #ffb900; padding: 12px 15px; margin-bottom: 15px;">
                        <p style="margin: 0; display: flex; align-items: center; gap: 8px;">
                            <span class="dashicons dashicons-lock" style="color: #826200;"></span>
                            <strong>Components Locked</strong>
                        </p>
                        <p style="margin: 8px 0 0 0; color: #666;">
                            Components cannot be modified after a kit/build is created. This ensures data integrity for stock movements, order history, and audit trails.
                            To use different components, create a new kit/build product.
                        </p>
                    </div>
                    <?php else: ?>
                    <p class="description">Add the products that make up this kit or build. Stock for components will be deducted when kit units are created.</p>
                    <?php endif; ?>

                    <div class="ggmc-kit-components-list" id="kit-components-list">
                        <?php if (!empty($existing_components)): ?>
                            <?php foreach ($existing_components as $comp): ?>
                            <div class="ggmc-kit-component-row kit-component-row <?php echo $components_locked ? 'components-locked' : ''; ?>" data-product-id="<?php echo esc_attr($comp->component_product_id); ?>">
                                <span class="component-name"><?php echo esc_html($comp->product_name); ?><?php echo $comp->sku ? ' (' . esc_html($comp->sku) . ')' : ''; ?></span>
                                <input type="hidden" name="kit_components[product_id][]" value="<?php echo esc_attr($comp->component_product_id); ?>" />
                                <label>Qty:</label>
                                <input type="number" name="kit_components[quantity][]" value="<?php echo esc_attr($comp->quantity); ?>" min="1" class="component-qty" data-price="<?php echo esc_attr($comp->price); ?>" data-stock="<?php echo esc_attr($comp->stock); ?>" <?php echo $components_locked ? 'readonly disabled' : ''; ?> />
                                <span class="component-stock">(Stock: <?php echo esc_html($comp->stock); ?>)</span>
                                <?php if (!$components_locked): ?>
                                <span class="component-remove dashicons dashicons-no-alt" title="Remove"></span>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>

                    <?php if (!$components_locked): ?>
                    <div class="ggmc-kit-add-component">
                        <select id="kit-component-select" style="width: 300px;">
                            <option value="">Select a product to add...</option>
                        </select>
                        <input type="number" id="kit-component-qty" value="1" min="1" style="width: 60px;" />
                        <button type="button" class="button" id="add-kit-component">Add Component</button>
                    </div>
                    <?php endif; ?>

                    <div class="ggmc-kit-stats" id="kit-stats" <?php echo empty($existing_components) ? 'style="display: none;"' : ''; ?>>
                        <p><strong>Calculated Price:</strong> <span class="stat-value" id="kit-calc-price">$0.00</span></p>
                        <p><strong>Maximum Creatable:</strong> <span class="stat-value" id="kit-max-creatable">0 units</span></p>
                        <p class="description" id="kit-limiting-factor"></p>
                    </div>

                    <?php if ($existing_kit && !empty($existing_components)): ?>
                    <!-- Stock Management Section -->
                    <div class="ggmc-stock-management">
                        <h4>Stock Management</h4>
                        <p><strong>Current Kit Stock:</strong> <?php echo esc_html($product->stock); ?> units</p>

                        <div class="ggmc-stock-action">
                            <label><strong>Create Stock:</strong></label>
                            <input type="number" id="create-stock-qty" value="1" min="1" style="width: 60px;" />
                            <button type="button" class="button" id="create-kit-stock">Create Kit Units</button>
                            <label style="margin-left: 15px;">
                                <input type="checkbox" id="override-stock-limit" /> Override stock limits
                            </label>
                        </div>
                        <p class="description">Creates kit units by deducting component stock.</p>

                        <?php if ($existing_kit->kit_type === 'kit'): ?>
                        <div class="ggmc-stock-action" style="margin-top: 15px;">
                            <label><strong>Breakdown Stock:</strong></label>
                            <input type="number" id="breakdown-stock-qty" value="1" min="1" max="<?php echo esc_attr($product->stock); ?>" style="width: 60px;" />
                            <button type="button" class="button" id="breakdown-kit-stock">Breakdown Kit Units</button>
                        </div>
                        <p class="description">Breaks down kit units, returning components to stock. Only available for Kits (not Builds).</p>
                        <?php else: ?>
                        <p class="description ggmc-stock-warning"><span class="dashicons dashicons-info"></span> Build products cannot be broken down - they represent a permanent manufacturing process.</p>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

                <!-- Gift Card Settings Section (shown when gift_card selected) -->
                <?php
                $gift_card_activated = GGM_Commerce_Helpers::is_product_type_available('gift_card');
                $current_gift_card_value = $product->gift_card_value ?? '';
                $current_gift_card_type = $product->gift_card_type ?? 'fixed';
                $current_gift_card_single_use = $product->gift_card_single_use ?? 0;
                $current_gift_card_valid_days = $product->gift_card_valid_days ?? '';
                $current_gift_card_code_prefix = $product->gift_card_code_prefix ?? 'GC';
                ?>
                <div class="ggmc-product-section" id="gift-card-section" data-section="gift-card-settings" <?php echo $current_product_type !== 'gift_card' ? 'style="display: none;"' : ''; ?>>
                    <h2><?php esc_html_e( 'Gift Card Settings', 'ggm-commerce' ); ?></h2>
                    <p class="description"><?php esc_html_e( 'Configure the voucher that will be generated when this gift card is purchased.', 'ggm-commerce' ); ?></p>

                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="gift_card_value"><?php esc_html_e( 'Voucher Value', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" step="0.01" min="0" name="gift_card_value" id="gift_card_value" value="<?php echo esc_attr( $current_gift_card_value ); ?>" style="width: 150px;" />
                                <p class="description"><?php esc_html_e( 'The value of the voucher that will be generated. Leave empty to use the product price.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_type"><?php esc_html_e( 'Voucher Type', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <select name="gift_card_type" id="gift_card_type" style="width: 200px;">
                                    <option value="fixed" <?php selected( $current_gift_card_type, 'fixed' ); ?>><?php esc_html_e( 'Fixed Amount', 'ggm-commerce' ); ?></option>
                                    <option value="percentage" <?php selected( $current_gift_card_type, 'percentage' ); ?>><?php esc_html_e( 'Percentage', 'ggm-commerce' ); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e( 'Fixed amount creates a voucher worth a set value. Percentage creates a % discount voucher.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_single_use"><?php esc_html_e( 'Single Use', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="gift_card_single_use" id="gift_card_single_use" value="1" <?php checked( $current_gift_card_single_use, 1 ); ?> />
                                    <?php esc_html_e( 'Voucher can only be used once (full value applied)', 'ggm-commerce' ); ?>
                                </label>
                                <p class="description"><?php esc_html_e( 'If unchecked, partial use is allowed and remaining balance carries forward.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_valid_days"><?php esc_html_e( 'Valid For (Days)', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" min="0" name="gift_card_valid_days" id="gift_card_valid_days" value="<?php echo esc_attr( $current_gift_card_valid_days ); ?>" style="width: 100px;" />
                                <p class="description"><?php esc_html_e( 'Number of days the voucher is valid after purchase. Leave empty for no expiration.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="gift_card_code_prefix"><?php esc_html_e( 'Code Prefix', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="text" maxlength="10" name="gift_card_code_prefix" id="gift_card_code_prefix" value="<?php echo esc_attr( $current_gift_card_code_prefix ); ?>" style="width: 100px;" />
                                <p class="description"><?php esc_html_e( 'Prefix for generated voucher codes (e.g., GC-XXXX).', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                    </table>

                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary"><?php esc_html_e( 'Update Product', 'ggm-commerce' ); ?></button>
                    </div>
                </div>

                <!-- Subscription Settings Section -->
                <?php
                $subscriptions_activated = class_exists( 'GGM_Commerce_Subscriptions' ) && GGM_Commerce_Subscriptions::is_activated();
                $current_is_subscription = ! empty( $product->is_subscription ) ? 1 : 0;
                $current_sub_period      = ! empty( $product->subscription_period ) ? $product->subscription_period : 'month';
                $current_sub_interval    = ! empty( $product->subscription_interval ) ? $product->subscription_interval : 1;
                $current_trial_length    = isset( $product->subscription_trial_length ) ? $product->subscription_trial_length : 0;
                $current_trial_period    = ! empty( $product->subscription_trial_period ) ? $product->subscription_trial_period : 'day';
                $current_sign_up_fee     = isset( $product->subscription_sign_up_fee ) ? $product->subscription_sign_up_fee : '0.00';
                $current_sub_length      = isset( $product->subscription_length ) ? $product->subscription_length : 0;
                ?>
                <div class="ggmc-product-section" data-section="subscription-settings">
                    <h2>
                        <?php esc_html_e( 'Subscription Settings', 'ggm-commerce' ); ?>
                        <?php if ( ! $subscriptions_activated ) : ?>
                            <span class="dashicons dashicons-lock" style="color: #0F766E;" title="<?php esc_attr_e( 'Premium Feature', 'ggm-commerce' ); ?>"></span>
                        <?php endif; ?>
                    </h2>
                    <?php if ( $subscriptions_activated ) : ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><?php esc_html_e( 'Enable Subscription', 'ggm-commerce' ); ?></th>
                            <td>
                                <label>
                                    <input type="checkbox" name="is_subscription" id="is_subscription" value="1" <?php checked( $current_is_subscription ); ?>>
                                    <?php esc_html_e( 'This is a subscription product', 'ggm-commerce' ); ?>
                                </label>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" <?php echo ! $current_is_subscription ? 'style="display:none;"' : ''; ?>>
                            <th scope="row"><label><?php esc_html_e( 'Billing Cycle', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <?php esc_html_e( 'Every', 'ggm-commerce' ); ?>
                                <input type="number" name="subscription_interval" id="subscription_interval" value="<?php echo esc_attr( $current_sub_interval ); ?>" min="1" max="365" style="width: 60px;">
                                <select name="subscription_period" id="subscription_period">
                                    <?php foreach ( GGM_Commerce_Subscriptions::get_billing_periods() as $value => $label ) : ?>
                                        <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current_sub_period, $value ); ?>><?php echo esc_html( $label ); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" <?php echo ! $current_is_subscription ? 'style="display:none;"' : ''; ?>>
                            <th scope="row"><label><?php esc_html_e( 'Free Trial', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" name="subscription_trial_length" id="subscription_trial_length" value="<?php echo esc_attr( $current_trial_length ); ?>" min="0" style="width: 60px;">
                                <select name="subscription_trial_period" id="subscription_trial_period">
                                    <option value="day" <?php selected( $current_trial_period, 'day' ); ?>><?php esc_html_e( 'day(s)', 'ggm-commerce' ); ?></option>
                                    <option value="week" <?php selected( $current_trial_period, 'week' ); ?>><?php esc_html_e( 'week(s)', 'ggm-commerce' ); ?></option>
                                    <option value="month" <?php selected( $current_trial_period, 'month' ); ?>><?php esc_html_e( 'month(s)', 'ggm-commerce' ); ?></option>
                                </select>
                                <p class="description"><?php esc_html_e( 'Set to 0 for no trial period.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" <?php echo ! $current_is_subscription ? 'style="display:none;"' : ''; ?>>
                            <th scope="row"><label for="subscription_sign_up_fee"><?php esc_html_e( 'Sign-up Fee', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" name="subscription_sign_up_fee" id="subscription_sign_up_fee" value="<?php echo esc_attr( $current_sign_up_fee ); ?>" min="0" step="0.01" style="width: 100px;">
                                <p class="description"><?php esc_html_e( 'One-time fee charged on first payment. Leave as 0 for none.', 'ggm-commerce' ); ?></p>
                            </td>
                        </tr>
                        <tr class="ggmc-subscription-options" <?php echo ! $current_is_subscription ? 'style="display:none;"' : ''; ?>>
                            <th scope="row"><label for="subscription_length"><?php esc_html_e( 'Subscription Length', 'ggm-commerce' ); ?></label></th>
                            <td>
                                <input type="number" name="subscription_length" id="subscription_length" value="<?php echo esc_attr( $current_sub_length ); ?>" min="0" style="width: 60px;">
                                <span><?php esc_html_e( 'billing cycles (0 = until cancelled)', 'ggm-commerce' ); ?></span>
                            </td>
                        </tr>
                    </table>
                    <script>
                    (function() {
                        var cb = document.getElementById('is_subscription');
                        if (cb) {
                            cb.addEventListener('change', function() {
                                var rows = document.querySelectorAll('.ggmc-subscription-options');
                                for (var i = 0; i < rows.length; i++) {
                                    rows[i].style.display = this.checked ? '' : 'none';
                                }
                            });
                        }
                    })();
                    </script>
                    <?php else : ?>
                    <p style="padding: 12px; color: #666;">
                        <?php esc_html_e( 'Subscription billing is a premium feature. Activate it in your license settings to enable recurring billing for this product.', 'ggm-commerce' ); ?>
                    </p>
                    <?php endif; ?>
                </div>

                <script>
                (function($) {
                    var availableProducts = <?php
                        // Get available simple products for component selection (exclude current product)
                        global $wpdb;
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $simple_products = $wpdb->get_results($wpdb->prepare(
                            "SELECT id, name, sku, price, stock
                             FROM {$wpdb->prefix}ggmc_products
                             WHERE (product_type = 'simple' OR product_type IS NULL OR product_type = '')
                             AND status = 'active'
                             AND id != %d
                             ORDER BY name ASC",
                            $product_id
                        ));
                        echo wp_json_encode($simple_products ?: array());
                    ?>;

                    var componentCount = <?php echo count($existing_components); ?>;
                    var productId = <?php echo intval($product_id); ?>;
                    var kitId = <?php echo $existing_kit ? intval($existing_kit->id) : 0; ?>;
                    var ajaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
                    var nonce = '<?php echo esc_js(wp_create_nonce('ggmc_kit_stock_action')); ?>';
                    var componentsLocked = <?php echo $components_locked ? 'true' : 'false'; ?>;

                    // Toggle kit and gift card section visibility based on product type
                    function toggleKitSection() {
                        var productType = $('#product_type').val();
                        if (productType === 'kit' || productType === 'build') {
                            $('#kit-components-section').slideDown();
                        } else {
                            $('#kit-components-section').slideUp();
                        }
                        // Toggle gift card section
                        if (productType === 'gift_card') {
                            $('#gift-card-section').slideDown();
                        } else {
                            $('#gift-card-section').slideUp();
                        }
                    }

                    // Populate product dropdown
                    function populateProductDropdown() {
                        var $select = $('#kit-component-select');
                        $select.empty();
                        $select.append('<option value="">Select a product to add...</option>');

                        // Get currently added product IDs
                        var addedIds = [];
                        $('#kit-components-list .kit-component-row').each(function() {
                            addedIds.push(parseInt($(this).data('product-id')));
                        });

                        $.each(availableProducts, function(i, product) {
                            if (addedIds.indexOf(parseInt(product.id)) === -1) {
                                var label = product.name;
                                if (product.sku) label += ' (' + product.sku + ')';
                                label += ' - $' + parseFloat(product.price).toFixed(2);
                                label += ' [Stock: ' + product.stock + ']';
                                $select.append('<option value="' + product.id + '" data-price="' + product.price + '" data-stock="' + product.stock + '">' + label + '</option>');
                            }
                        });
                    }

                    // Add component row
                    function addComponent(productId, productName, qty, price, stock) {
                        var $row = $('<div class="ggmc-kit-component-row kit-component-row" data-product-id="' + productId + '">');
                        $row.append('<span class="component-name">' + productName + '</span>');
                        $row.append('<input type="hidden" name="kit_components[product_id][]" value="' + productId + '" />');
                        $row.append('<label>Qty:</label>');
                        $row.append('<input type="number" name="kit_components[quantity][]" value="' + qty + '" min="1" class="component-qty" data-price="' + price + '" data-stock="' + stock + '" />');
                        $row.append('<span class="component-stock">(Stock: ' + stock + ')</span>');
                        $row.append('<span class="component-remove dashicons dashicons-no-alt" title="Remove"></span>');

                        $('#kit-components-list').append($row);
                        componentCount++;
                        updateKitStats();
                        populateProductDropdown();
                    }

                    // Update kit statistics
                    function updateKitStats() {
                        var totalPrice = 0;
                        var maxCreatable = Infinity;
                        var limitingProduct = '';

                        $('#kit-components-list .kit-component-row').each(function() {
                            var $row = $(this);
                            var $qty = $row.find('.component-qty');
                            var price = parseFloat($qty.data('price')) || 0;
                            var stock = parseInt($qty.data('stock')) || 0;
                            var qty = parseInt($qty.val()) || 1;

                            totalPrice += price * qty;

                            if (qty > 0) {
                                var possible = Math.floor(stock / qty);
                                if (possible < maxCreatable) {
                                    maxCreatable = possible;
                                    limitingProduct = $row.find('.component-name').text();
                                }
                            }
                        });

                        if (componentCount > 0) {
                            $('#kit-stats').show();
                            $('#kit-calc-price').text('$' + totalPrice.toFixed(2));
                            if (maxCreatable === Infinity) maxCreatable = 0;
                            $('#kit-max-creatable').text(maxCreatable + ' units');
                            if (limitingProduct && maxCreatable < 100) {
                                $('#kit-limiting-factor').text('Limited by: ' + limitingProduct).show();
                            } else {
                                $('#kit-limiting-factor').hide();
                            }
                        } else {
                            $('#kit-stats').hide();
                        }
                    }

                    $(document).ready(function() {
                        // Initial setup
                        toggleKitSection();
                        populateProductDropdown();
                        updateKitStats();

                        // Product type change
                        $('#product_type').on('change', toggleKitSection);

                        // Add component button (only works when not locked)
                        $('#add-kit-component').on('click', function() {
                            if (componentsLocked) return;

                            var $select = $('#kit-component-select');
                            var productId = $select.val();
                            if (!productId) return;

                            var $option = $select.find('option:selected');
                            var productName = $option.text().split(' - ')[0];
                            var price = $option.data('price');
                            var stock = $option.data('stock');
                            var qty = parseInt($('#kit-component-qty').val()) || 1;

                            addComponent(productId, productName, qty, price, stock);
                            $('#kit-component-qty').val(1);
                        });

                        // Remove component (only works when not locked)
                        $(document).on('click', '.component-remove', function() {
                            if (componentsLocked) return;

                            $(this).closest('.kit-component-row').remove();
                            componentCount--;
                            updateKitStats();
                            populateProductDropdown();
                        });

                        // Update stats when quantity changes (only when not locked)
                        $(document).on('change', '.component-qty', function() {
                            if (componentsLocked) return false;
                            updateKitStats();
                        });

                        // Create kit stock
                        $('#create-kit-stock').on('click', function() {
                            var qty = parseInt($('#create-stock-qty').val()) || 1;
                            var override = $('#override-stock-limit').is(':checked');

                            if (!confirm('Create ' + qty + ' kit units? This will deduct component stock.')) return;

                            $.post(ajaxUrl, {
                                action: 'ggmc_create_kit_stock',
                                nonce: nonce,
                                kit_id: kitId,
                                quantity: qty,
                                override: override ? 1 : 0
                            }, function(response) {
                                if (response.success) {
                                    alert('Kit stock created successfully!');
                                    location.reload();
                                } else {
                                    alert('Error: ' + response.data.message);
                                }
                            });
                        });

                        // Breakdown kit stock
                        $('#breakdown-kit-stock').on('click', function() {
                            var qty = parseInt($('#breakdown-stock-qty').val()) || 1;

                            if (!confirm('Breakdown ' + qty + ' kit units? Components will be returned to stock.')) return;

                            $.post(ajaxUrl, {
                                action: 'ggmc_breakdown_kit_stock',
                                nonce: nonce,
                                kit_id: kitId,
                                quantity: qty
                            }, function(response) {
                                if (response.success) {
                                    alert('Kit stock broken down successfully!');
                                    location.reload();
                                } else {
                                    alert('Error: ' + response.data.message);
                                }
                            });
                        });
                    });
                })(jQuery);
                </script>

                <!-- Section 2: Description -->
                <div class="ggmc-product-section" data-section="description">
                    <h2>Description</h2>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="product_description">Full Description</label></th>
                            <td>
                                <?php wp_editor($product->description ?? '', 'product_description', array('textarea_rows' => 8)); ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="short_description">Short Description</label></th>
                            <td><textarea name="short_description" id="short_description" rows="3" cols="50"><?php echo esc_textarea($product->short_description ?? ''); ?></textarea></td>
                        </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

                <!-- Section 3: Pricing, Inventory & Specifications -->
                <div class="ggmc-product-section" data-section="pricing" data-section-group="pricing-inventory-specs">
                    <h2>Pricing, Inventory & Specifications</h2>
                    <?php
                    // Get tax settings for price label
                    $tax = ggm_commerce_tax();
                    $tax_enabled = $tax->is_enabled();
                    $prices_include_tax = $tax->prices_include_tax();
                    $tax_label = $tax->get_label();
                    $price_tax_hint = '';
                    if ($tax_enabled) {
                        // Prices are always stored inclusive of tax
                        $price_tax_hint = sprintf(
                            /* translators: %s: tax label (e.g., "VAT", "GST") */
                            __('(incl. %s)', 'ggm-commerce'),
                            $tax_label
                        );
                    }
                    // Get tax rates for dropdown
                    $tax_rates = $tax_enabled ? $tax->get_tax_rates() : [];
                    $default_tax_rate = $tax_enabled ? $tax->get_default_tax_rate() : null;
                    $product_tax_rate_id = isset($product->tax_rate_id) ? $product->tax_rate_id : ($default_tax_rate ? $default_tax_rate->id : null);
                    ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="product_price"><?php esc_html_e('Price', 'ggm-commerce'); ?> <?php if ($price_tax_hint): ?><span class="description" style="font-weight: normal;"><?php echo esc_html($price_tax_hint); ?></span><?php endif; ?></label></th>
                            <td><input name="product_price" type="number" step="0.01" id="product_price" value="<?php echo esc_attr($product->price ?? ''); ?>" class="small-text" required /></td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_sale_price"><?php esc_html_e('Sale Price', 'ggm-commerce'); ?> <?php if ($price_tax_hint): ?><span class="description" style="font-weight: normal;"><?php echo esc_html($price_tax_hint); ?></span><?php endif; ?></label></th>
                            <td><input name="product_sale_price" type="number" step="0.01" id="product_sale_price" value="<?php echo esc_attr($product->sale_price ?? ''); ?>" class="small-text" /></td>
                        </tr>
                        <?php if ($tax_enabled && !empty($tax_rates)): ?>
                        <tr>
                            <th scope="row"><label for="tax_rate_id"><?php echo esc_html($tax_label); ?> <?php esc_html_e('Rate', 'ggm-commerce'); ?></label></th>
                            <td>
                                <select name="tax_rate_id" id="tax_rate_id">
                                    <?php foreach ($tax_rates as $rate): ?>
                                        <option value="<?php echo esc_attr($rate->id); ?>" <?php selected($product_tax_rate_id, $rate->id); ?>>
                                            <?php echo esc_html($rate->name); ?> (<?php echo esc_html(number_format($rate->rate, 2)); ?>%)
                                            <?php if ($rate->is_default): ?>(<?php esc_html_e('Default', 'ggm-commerce'); ?>)<?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <tr>
                            <th scope="row"><label for="manage_stock">Manage Stock</label></th>
                            <td>
                                <label>
                                    <input name="manage_stock" type="checkbox" id="manage_stock" value="1" <?php checked(!empty($product->manage_stock)); ?> />
                                    Enable stock management for this product
                                </label>
                                <p class="description">When disabled, this product can be purchased without stock limits.</p>
                            </td>
                        </tr>
                        <tr class="ggmc-stock-fields">
                            <th scope="row"><label for="stock_quantity">Stock Quantity</label></th>
                            <td><input name="stock_quantity" type="number" id="stock_quantity" value="<?php echo esc_attr($product->stock ?? '0'); ?>" class="small-text" /></td>
                        </tr>
                        <tr class="ggmc-stock-fields">
                            <th scope="row"><label for="low_stock_threshold">Low Stock Threshold</label></th>
                            <td>
                                <input name="low_stock_threshold" type="number" id="low_stock_threshold" value="<?php echo esc_attr($product->low_stock_threshold ?? '10'); ?>" class="small-text" min="0" />
                                <p class="description">You will be notified when stock falls to this level.</p>
                            </td>
                        </tr>
                        <tr class="ggmc-stock-fields">
                            <th scope="row"><label for="restock_date">Expected Restock Date</label></th>
                            <td>
                                <input name="restock_date" type="date" id="restock_date" value="<?php echo esc_attr($product->restock_date ?? ''); ?>" class="regular-text" />
                                <p class="description">Optional. Shown to customers when the product is out of stock.</p>
                            </td>
                        </tr>
                        <script>
                        (function() {
                            var cb = document.getElementById('manage_stock');
                            function toggleStockFields() {
                                var rows = document.querySelectorAll('.ggmc-stock-fields');
                                for (var i = 0; i < rows.length; i++) {
                                    rows[i].style.display = cb.checked ? '' : 'none';
                                }
                            }
                            cb.addEventListener('change', toggleStockFields);
                            toggleStockFields();
                        })();
                        </script>
                        <tr>
                            <th scope="row"><label for="product_weight">Weight</label></th>
                            <td>
                                <?php
                                $units_options = get_option('ggm_commerce_units_options', []);
                                $weight_unit = isset($units_options['weight_unit']) ? $units_options['weight_unit'] : 'kg';
                                ?>
                                <input name="product_weight" type="number" step="0.01" id="product_weight" value="<?php echo esc_attr($product->weight ?? ''); ?>" class="small-text" />
                                <span class="description"><?php echo esc_html($weight_unit); ?></span>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="product_dimensions">Dimensions (L × W × H)</label></th>
                            <td>
                                <?php
                                $dimension_unit = isset($units_options['dimension_unit']) ? $units_options['dimension_unit'] : 'cm';
                                ?>
                                <input name="product_length" type="number" step="0.01" id="product_length" value="<?php echo esc_attr($product->length ?? ''); ?>" class="small-text" placeholder="Length" />
                                <span>×</span>
                                <input name="product_width" type="number" step="0.01" id="product_width" value="<?php echo esc_attr($product->width ?? ''); ?>" class="small-text" placeholder="Width" />
                                <span>×</span>
                                <input name="product_height" type="number" step="0.01" id="product_height" value="<?php echo esc_attr($product->height ?? ''); ?>" class="small-text" placeholder="Height" />
                                <span class="description"><?php echo esc_html($dimension_unit); ?></span>
                            </td>
                        </tr>
                    <?php
                    // Custom Attributes section - Premium feature
                    $attributes_activated = GGM_Commerce_License::instance()->is_widget_activated('custom-attributes');
                    ?>
                    <tr>
                        <th scope="row">
                            <label>Custom Attributes</label>
                            <?php if (!$attributes_activated): ?>
                                <span class="dashicons dashicons-lock" style="color: #0F766E; margin-left: 5px;" title="Premium Feature"></span>
                            <?php endif; ?>
                        </th>
                        <td>
                            <?php if ($attributes_activated): ?>
                                <?php
                                $attributes_manager = GGM_Commerce_Attributes::get_instance();
                                $all_attributes = $attributes_manager->get_all_attributes();
                                $attribute_groups = $attributes_manager->get_attribute_groups();
                                $product_attributes = $attributes_manager->get_product_attributes($product_id);
                                $product_attr_ids = array_map(function($pa) { return $pa->attribute_id; }, $product_attributes);
                                ?>
                                <div class="ggmc-custom-attributes-section">
                                    <div class="ggmc-attribute-actions" style="margin-bottom: 15px;">
                                        <select id="add-single-attribute" style="width: 200px;">
                                            <option value="">-- Add Attribute --</option>
                                            <?php foreach ($all_attributes as $attr): ?>
                                                <?php if (!in_array($attr->id, $product_attr_ids)): ?>
                                                <option value="<?php echo esc_attr($attr->id); ?>"
                                                        data-type="<?php echo esc_attr($attr->attribute_type); ?>"
                                                        data-options="<?php echo esc_attr($attr->options); ?>"
                                                        data-unit="<?php echo esc_attr($attr->unit); ?>"
                                                        data-name="<?php echo esc_attr($attr->name); ?>">
                                                    <?php echo esc_html($attr->name); ?>
                                                </option>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if (!empty($attribute_groups)): ?>
                                        <select id="add-from-group" style="width: 200px; margin-left: 10px;">
                                            <option value="">-- Add from Group --</option>
                                            <?php foreach ($attribute_groups as $group): ?>
                                                <option value="<?php echo esc_attr($group->id); ?>">
                                                    <?php echo esc_html($group->name); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php endif; ?>
                                    </div>
                                    <div id="custom-attributes-container">
                                        <?php if (!empty($product_attributes)): ?>
                                            <?php foreach ($product_attributes as $index => $pa):
                                                $attr = $attributes_manager->get_attribute($pa->attribute_id);
                                                if (!$attr) continue;
                                            ?>
                                            <div class="ggmc-attribute-row" data-attribute-id="<?php echo esc_attr($pa->attribute_id); ?>" style="margin-bottom: 10px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">
                                                <div style="display: grid; grid-template-columns: auto 150px 1fr auto auto; gap: 10px; align-items: center;">
                                                    <span class="dashicons dashicons-menu ggmc-drag-handle" style="cursor: grab; color: #999;"></span>
                                                    <input type="hidden" name="custom_attributes[<?php echo esc_attr($index); ?>][attribute_id]" value="<?php echo esc_attr($pa->attribute_id); ?>" />
                                                    <input type="hidden" name="custom_attributes[<?php echo esc_attr($index); ?>][display_order]" class="attr-order" value="<?php echo esc_attr($index); ?>" />
                                                    <label style="font-weight: 500;"><?php echo esc_html($attr->name); ?></label>
                                                    <?php if ($attr->attribute_type === 'select' && !empty($attr->options)):
                                                        $options = json_decode($attr->options, true);
                                                    ?>
                                                    <select name="custom_attributes[<?php echo esc_attr($index); ?>][value]" style="width: 200px;">
                                                        <option value="">-- Select --</option>
                                                        <?php foreach ($options as $option): ?>
                                                            <option value="<?php echo esc_attr($option); ?>" <?php selected($pa->attribute_value, $option); ?>>
                                                                <?php echo esc_html($option); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <?php elseif ($attr->attribute_type === 'number'): ?>
                                                    <input type="number" step="any" name="custom_attributes[<?php echo esc_attr($index); ?>][value]" value="<?php echo esc_attr($pa->attribute_value); ?>" style="width: 150px;" />
                                                    <?php else: ?>
                                                    <input type="text" name="custom_attributes[<?php echo esc_attr($index); ?>][value]" value="<?php echo esc_attr($pa->attribute_value); ?>" style="width: 200px;" />
                                                    <?php endif; ?>
                                                    <?php if (!empty($attr->unit)): ?>
                                                    <span class="attr-unit" style="color: #666;"><?php echo esc_html($attr->unit); ?></span>
                                                    <?php else: ?>
                                                    <span class="attr-unit"></span>
                                                    <?php endif; ?>
                                                    <button type="button" class="button remove-attribute-btn" data-attribute-id="<?php echo esc_attr($pa->attribute_id); ?>">&times;</button>
                                                </div>
                                            </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                    <?php if (empty($all_attributes)): ?>
                                    <p class="description" style="color: #999;">
                                        No custom attributes defined yet. <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes')); ?>">Create attributes</a> first.
                                    </p>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <div class="ggmc-premium-notice">
                                    <strong>Premium Feature</strong>
                                    <p>Add custom attributes like specifications, dimensions, and more to your products.</p>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>" class="button">Activate Custom Attributes</a>
                                </div>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php
                    // Barcode section - Premium feature
                    $barcode_activated = GGM_Commerce_License::instance()->is_widget_activated('barcode');
                    ?>
                    <tr>
                        <th scope="row">
                            <label>Product Barcodes</label>
                            <?php if (!$barcode_activated): ?>
                                <span class="dashicons dashicons-lock" style="color: #0F766E; margin-left: 5px;" title="Premium Feature"></span>
                            <?php endif; ?>
                        </th>
                        <td>
                            <?php if ($barcode_activated): ?>
                                <?php
                                $barcode_manager = GGM_Commerce_Barcode::get_instance();
                                $barcodes = $barcode_manager->get_product_barcodes($product_id);
                                $barcode_types = $barcode_manager->get_barcode_types();
                                ?>
                                <div id="barcodes-container">
                                    <?php if (!empty($barcodes)): ?>
                                        <?php foreach ($barcodes as $index => $barcode): ?>
                                            <div class="barcode-row" data-barcode-id="<?php echo esc_attr($barcode->id); ?>" style="margin-bottom: 10px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">
                                                <input type="hidden" name="barcodes[<?php echo esc_attr($index); ?>][id]" value="<?php echo esc_attr($barcode->id); ?>" />
                                                <div style="display: grid; grid-template-columns: 2fr 1fr auto auto; gap: 10px; align-items: center;">
                                                    <input type="text" name="barcodes[<?php echo esc_attr($index); ?>][value]" value="<?php echo esc_attr($barcode->barcode_value); ?>" class="regular-text" placeholder="Barcode value" />
                                                    <select name="barcodes[<?php echo esc_attr($index); ?>][type]">
                                                        <?php foreach ($barcode_types as $type_key => $type_label): ?>
                                                            <option value="<?php echo esc_attr($type_key); ?>" <?php selected($barcode->barcode_type, $type_key); ?>>
                                                                <?php echo esc_html($type_label); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <label style="white-space: nowrap;">
                                                        <input type="checkbox" name="barcodes[<?php echo esc_attr($index); ?>][is_primary]" value="1" <?php checked($barcode->is_primary, 1); ?> />
                                                        Primary
                                                    </label>
                                                    <button type="button" class="button remove-barcode-button">Remove</button>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                                <button type="button" id="add-barcode-button" class="button" <?php echo count($barcodes) >= 3 ? 'disabled' : ''; ?>>
                                    <span class="dashicons dashicons-plus-alt" style="vertical-align: middle;"></span> Add Barcode
                                </button>
                                <p class="description">Add up to 3 barcodes per product. Check "Primary" to set the main barcode for packing lists and invoices.</p>
                            <?php else: ?>
                                <div class="ggmc-premium-notice">
                                    <strong>Premium Feature</strong>
                                    <p>Add EAN, UPC, QR codes and other barcodes to your products.</p>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>" class="button">Activate Barcode Feature</a>
                                </div>
                            <?php endif; ?>
                        </td>
                    </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

                <!-- Section 4: Product Images -->
                <div class="ggmc-product-section" data-section="images">
                    <h2>Product Images</h2>
                    <table class="form-table">
                    <tr>
                        <th scope="row"><label for="main_image">Main Image</label></th>
                        <td>
                            <div class="ggmc-image-upload">
                                <input type="hidden" name="main_image_id" id="main_image_id" value="<?php echo esc_attr($product->image_id ?? ''); ?>" />
                                <div id="main_image_preview" class="image-preview">
                                    <?php if (!empty($product->image_id)): 
                                        $image_url = wp_get_attachment_image_url($product->image_id, 'medium');
                                        if ($image_url): ?>
                                            <div class="image-item" data-id="<?php echo esc_attr($product->image_id); ?>">
                                                <img src="<?php echo esc_url($image_url); ?>" alt="Main Product Image" />
                                                <span class="remove-single-image" data-id="<?php echo esc_attr($product->image_id); ?>">&times;</span>
                                            </div>
                                        <?php endif;
                                    endif; ?>
                                </div>
                                <button type="button" class="button upload-image-button" data-target="main_image">Choose Main Image</button>
                                <button type="button" class="button remove-image-button" data-target="main_image" style="<?php echo empty($product->image_id) ? 'display: none;' : ''; ?>">Remove Image</button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="gallery_images">Gallery Images</label></th>
                        <td>
                            <div class="ggmc-gallery-upload">
                                <input type="hidden" name="gallery_image_ids" id="gallery_image_ids" value="<?php echo esc_attr($product->gallery_ids ?? ''); ?>" />
                                <div id="gallery_images_preview" class="gallery-preview">
                                    <?php 
                                    if (!empty($product->gallery_ids)) {
                                        $gallery_ids = explode(',', $product->gallery_ids);
                                        foreach ($gallery_ids as $image_id) {
                                            $image_id = trim($image_id);
                                            if (!empty($image_id)) {
                                                $image_url = wp_get_attachment_image_url($image_id, 'medium');
                                                if ($image_url): ?>
                                                    <div class="image-item" data-id="<?php echo esc_attr($image_id); ?>">
                                                        <img src="<?php echo esc_url($image_url); ?>" alt="Gallery Image" />
                                                        <span class="remove-single-image" data-id="<?php echo esc_attr($image_id); ?>">&times;</span>
                                                    </div>
                                                <?php endif;
                                            }
                                        }
                                    }
                                    ?>
                                </div>
                                <button type="button" class="button upload-gallery-button" data-target="gallery_images">Add Gallery Images</button>
                                <button type="button" class="button remove-all-gallery-button" data-target="gallery_images" style="<?php echo empty($product->gallery_ids) ? 'display: none;' : ''; ?>">Remove All</button>
                                <?php if ($kits_activated && in_array($current_product_type, array('kit', 'build'), true)): ?>
                                <button type="button" class="button populate-gallery-from-components" id="populate-gallery-from-components" data-include-gallery="false" title="Add primary images from kit/build components to the gallery">
                                    <span class="dashicons dashicons-format-image" style="vertical-align: middle; margin-top: -2px;"></span>
                                    Primary Images
                                </button>
                                <button type="button" class="button populate-gallery-from-components" id="populate-all-from-components" data-include-gallery="true" title="Add primary and gallery images from all kit/build components">
                                    <span class="dashicons dashicons-images-alt2" style="vertical-align: middle; margin-top: -2px;"></span>
                                    All Component Images
                                </button>
                                <?php endif; ?>
                                <p class="description">Hold Ctrl/Cmd to select multiple images</p>
                            </div>
                        </td>
                    </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

                <!-- Section 5: Categories & Tags -->
                <div class="ggmc-product-section" data-section="categories">
                    <h2>Categories & Tags</h2>
                    <table class="form-table">
                    <tr>
                        <th scope="row"><label for="product_categories">Categories</label></th>
                        <td>
                            <?php
                            $taxonomy = GGM_Commerce_Taxonomy::get_instance();
                            $categories = $taxonomy->get_categories();
                            $product_categories = $taxonomy->get_product_categories($product_id);
                            $product_category_ids = array_map(function($cat) { return $cat->id; }, $product_categories);
                            ?>
                            <select name="product_categories[]" id="product_categories" multiple size="6" style="width: 300px;">
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo esc_attr($category->id); ?>" <?php selected(in_array($category->id, $product_category_ids), true); ?>>
                                        <?php echo esc_html($category->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">Hold Ctrl/Cmd to select multiple categories. Defaults to "Uncategorised" if none selected.</p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="product_tags">Tags</label></th>
                        <td>
                            <?php
                            $tags = $taxonomy->get_tags();
                            $product_tags = $taxonomy->get_product_tags($product_id);
                            $product_tag_ids = array_map(function($tag) { return $tag->id; }, $product_tags);
                            ?>
                            <select name="product_tags[]" id="product_tags" multiple size="6" style="width: 300px;">
                                <?php foreach ($tags as $tag): ?>
                                    <option value="<?php echo esc_attr($tag->id); ?>" <?php selected(in_array($tag->id, $product_tag_ids), true); ?>>
                                        <?php echo esc_html($tag->name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <p class="description">Hold Ctrl/Cmd to select multiple tags. Optional.</p>
                        </td>
                    </tr>
                    </table>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

                <?php
                // Section 6: Product Variations (Premium Feature)
                $variations_activated = GGM_Commerce_License::instance()->is_widget_activated('product-variations');
                ?>
                <div class="ggmc-product-section" data-section="variations">
                    <h2>
                        Product Variations
                        <?php if (!$variations_activated): ?>
                            <span class="dashicons dashicons-lock" style="color: #0F766E; margin-left: 5px;" title="Premium Feature"></span>
                        <?php endif; ?>
                    </h2>
                    <?php if ($variations_activated): ?>
                        <?php
                        $variations_manager = GGM_Commerce_Variations::instance();
                        $has_variations = $variations_manager->product_has_variations($product_id);
                        $product_config = $variations_manager->get_product_variation_config($product_id);
                        $all_attributes = $variations_manager->get_variation_types();
                        $product_variations = $has_variations ? $variations_manager->get_variations($product_id) : array();

                        // Get current stock mode and variation mode from product
                        global $wpdb;
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $product_modes = $wpdb->get_row($wpdb->prepare(
                            "SELECT variation_stock_mode, variation_mode FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
                            $product_id
                        ), ARRAY_A);
                        $stock_mode = ! empty( $product_modes['variation_stock_mode'] ) ? $product_modes['variation_stock_mode'] : 'parent';
                        $variation_mode = ! empty( $product_modes['variation_mode'] ) ? $product_modes['variation_mode'] : 'combined';
                        ?>
                        <table class="form-table">
                            <tr>
                                <th scope="row"><label for="has_variations">Enable Variations</label></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="has_variations" id="has_variations" value="1" <?php checked($has_variations); ?>>
                                        This product has variations (e.g., different colors, sizes)
                                    </label>
                                </td>
                            </tr>
                            <tr class="variations-options" <?php echo !$has_variations ? 'style="display:none;"' : ''; ?>>
                                <th scope="row"><label for="variation_attributes">Variations</label></th>
                                <td>
                                    <?php if (empty($all_attributes)): ?>
                                        <p><em>No variations defined yet.</em>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-variation-attributes')); ?>">Create some first</a>.</p>
                                    <?php else: ?>
                                        <?php
                                        $selected_attr_ids = array_column($product_config, 'variation_type_id');
                                        ?>
                                        <select name="variation_attributes[]" id="variation_attributes" multiple size="5" style="width: 300px;">
                                            <?php foreach ($all_attributes as $attr): ?>
                                                <option value="<?php echo esc_attr($attr['id']); ?>" <?php selected(in_array($attr['id'], $selected_attr_ids)); ?>>
                                                    <?php echo esc_html($attr['name']); ?> (<?php echo count($attr['options']); ?> options)
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">Select which variations apply to this product. Hold Ctrl/Cmd to select multiple.</p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr class="variations-options" <?php echo !$has_variations ? 'style="display:none;"' : ''; ?>>
                                <th scope="row"><label for="variation_mode">Variation Mode</label></th>
                                <td>
                                    <select name="variation_mode" id="variation_mode">
                                        <option value="combined" <?php selected($variation_mode, 'combined'); ?>>Combined (e.g., Color + Size = unique SKU)</option>
                                        <option value="independent" <?php selected($variation_mode, 'independent'); ?>>Independent (e.g., RAM + Storage are separate)</option>
                                    </select>
                                    <p class="description">
                                        <strong>Combined:</strong> Creates a matrix of all combinations with individual stock (best for clothing where each Color/Size combo is tracked separately).<br>
                                        <strong>Independent:</strong> Each option adds to the base price separately (best for computers where RAM and Storage choices don't affect each other).
                                    </p>
                                </td>
                            </tr>
                            <tr class="variations-options" <?php echo !$has_variations ? 'style="display:none;"' : ''; ?>>
                                <th scope="row"><label for="variation_stock_mode">Stock Management</label></th>
                                <td>
                                    <select name="variation_stock_mode" id="variation_stock_mode">
                                        <option value="parent" <?php selected($stock_mode, 'parent'); ?>>Use parent product stock</option>
                                        <option value="variation" <?php selected($stock_mode, 'variation'); ?>>Track stock per variation</option>
                                    </select>
                                    <p class="description">Choose whether to track stock at the product level or individually for each variation.</p>
                                </td>
                            </tr>
                        </table>

                        <?php if ($has_variations && !empty($product_config)): ?>
                            <?php
                            // For Independent mode, get per-product option configurations
                            $is_independent_mode = ($variation_mode === 'independent');
                            $currency_options = get_option('ggm_commerce_currency_options', array());
                            $currency_symbol = isset($currency_options['symbol']) ? $currency_options['symbol'] : '£';
                            ?>

                            <!-- INDEPENDENT MODE: Per-Product Option Configuration -->
                            <div id="independent-mode-options" style="padding: 0 20px 20px; <?php echo !$is_independent_mode ? 'display:none;' : ''; ?>" data-product-id="<?php echo esc_attr($product_id); ?>">
                                <h3>Variation Options</h3>
                                <p class="description" style="margin-bottom: 15px;">
                                    Configure which options are available for this product and their price modifiers.
                                    Price modifiers are added to the base product price. Use negative values for "downgrade" options.
                                    Use the <strong>Remove</strong> button to disable options customers shouldn't see.
                                </p>
                                <?php
                                $variations_manager = GGM_Commerce_Variations::instance();
                                foreach ($product_config as $attr):
                                    $attr_id = $attr['variation_type_id'];
                                    // Initialize options if not yet set
                                    $variations_manager->initialize_product_variation_options($product_id, $attr_id);
                                    // Get ONLY the options that exist for this product (not all global options)
                                    $product_attr_options = $variations_manager->get_variation_options_for_product($product_id, $attr_id);
                                    // Get missing options for the "Add" dropdown
                                    $missing_options = $variations_manager->get_missing_variation_options($product_id, $attr_id);
                                ?>
                                    <div class="independent-attribute-section" style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;" data-attribute-id="<?php echo esc_attr($attr_id); ?>">
                                        <h4 style="margin: 0 0 10px; padding-bottom: 10px; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;">
                                            <span><?php echo esc_html($attr['name']); ?></span>
                                            <button type="button" class="button button-small remove-variation-attribute" data-attribute-id="<?php echo esc_attr($attr_id); ?>" title="Remove this attribute from product">
                                                <span class="dashicons dashicons-no-alt" style="vertical-align: middle;"></span>
                                                Remove Attribute
                                            </button>
                                        </h4>
                                        <?php if (empty($product_attr_options)): ?>
                                            <p class="description" style="color: #d63638; margin: 10px 0;">
                                                <strong>No options available.</strong> Add options using the dropdown below.
                                            </p>
                                        <?php else: ?>
                                            <table class="wp-list-table widefat striped independent-options-table" style="margin: 0;">
                                                <thead>
                                                    <tr>
                                                        <th>Option</th>
                                                        <th style="width: 140px;">Price Modifier</th>
                                                        <th style="width: 70px;">Default</th>
                                                        <th style="width: 100px;">Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($product_attr_options as $opt): ?>
                                                        <tr data-option-value="<?php echo esc_attr($opt['option_value']); ?>">
                                                            <td>
                                                                <strong><?php echo esc_html($opt['option_value']); ?></strong>
                                                            </td>
                                                            <td>
                                                                <div style="display: flex; align-items: center;">
                                                                    <span style="margin-right: 5px;"><?php echo esc_html($currency_symbol); ?></span>
                                                                    <input type="number" step="0.01"
                                                                           name="independent_options[<?php echo esc_attr($attr_id); ?>][<?php echo esc_attr($opt['option_value']); ?>][modifier]"
                                                                           value="<?php echo esc_attr($opt['price_modifier']); ?>"
                                                                           style="width: 90px;"
                                                                           placeholder="0.00">
                                                                </div>
                                                            </td>
                                                            <td style="text-align: center;">
                                                                <input type="radio"
                                                                       name="independent_options[<?php echo esc_attr($attr_id); ?>][default]"
                                                                       value="<?php echo esc_attr($opt['option_value']); ?>"
                                                                       <?php checked(!empty($opt['is_default'])); ?>>
                                                            </td>
                                                            <td style="text-align: center;">
                                                                <button type="button"
                                                                        class="button button-small remove-independent-option"
                                                                        data-product-id="<?php echo esc_attr($product_id); ?>"
                                                                        data-attribute-id="<?php echo esc_attr($attr_id); ?>"
                                                                        data-option-value="<?php echo esc_attr($opt['option_value']); ?>"
                                                                        title="Remove this option">
                                                                    <span class="dashicons dashicons-trash" style="vertical-align: middle;"></span>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        <?php endif; ?>

                                        <!-- Add Missing Options -->
                                        <div class="add-missing-options-wrapper" style="margin-top: 10px; display: flex; gap: 10px; align-items: center;">
                                            <?php if (!empty($missing_options)): ?>
                                                <select class="add-missing-option-select" data-attribute-id="<?php echo esc_attr($attr_id); ?>">
                                                    <option value="">+ Add option...</option>
                                                    <?php foreach ($missing_options as $missing): ?>
                                                        <option value="<?php echo esc_attr($missing['value']); ?>"
                                                                data-modifier="<?php echo esc_attr($missing['price_modifier']); ?>">
                                                            <?php echo esc_html($missing['value']); ?>
                                                            <?php if ($missing['price_modifier'] != 0): ?>
                                                                (<?php echo $missing['price_modifier'] >= 0 ? '+' : ''; ?><?php echo esc_html($currency_symbol . number_format($missing['price_modifier'], 2)); ?>)
                                                            <?php endif; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <?php if (count($missing_options) > 1): ?>
                                                    <button type="button" class="button button-small add-all-missing-options"
                                                            data-product-id="<?php echo esc_attr($product_id); ?>"
                                                            data-attribute-id="<?php echo esc_attr($attr_id); ?>">
                                                        Add All (<?php echo count($missing_options); ?>)
                                                    </button>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="description" style="color: #00a32a;">
                                                    <span class="dashicons dashicons-yes-alt" style="vertical-align: middle;"></span>
                                                    All options added
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                                <p class="description">
                                    <strong>Note:</strong> In Independent mode, each attribute selection adds its modifier to the base price.
                                    No variation matrix is created - options are stored at order time.
                                </p>
                            </div>

                            <!-- COMBINED MODE: Variations Matrix -->
                            <div id="combined-mode-variations" style="padding: 0 20px 20px; <?php echo $is_independent_mode ? 'display:none;' : ''; ?>">
                                <h3>Variations (<?php echo count($product_variations); ?>)</h3>
                                <?php if (empty($product_variations)): ?>
                                    <p><em>No variations created yet.</em></p>
                                    <button type="button" class="button" id="generate-variations-btn">Generate All Variations</button>
                                    <p class="description">This will create variations for all possible combinations of the selected attributes.</p>
                                <?php else: ?>
                                    <div style="margin-bottom: 15px; display: flex; gap: 10px; align-items: center;">
                                        <button type="button" class="button" id="autogenerate-skus-btn">
                                            <span class="dashicons dashicons-randomize" style="vertical-align: middle; margin-right: 3px;"></span>
                                            Auto-Generate SKUs
                                        </button>
                                        <span class="description" style="margin: 0;">Generate SKUs based on product SKU + attribute codes</span>
                                    </div>
                                    <table class="wp-list-table widefat striped" style="margin-bottom: 15px;">
                                        <thead>
                                            <tr>
                                                <th>Variations</th>
                                                <th>SKU</th>
                                                <th>Price</th>
                                                <th>Price Type</th>
                                                <th>Stock</th>
                                                <th>Image</th>
                                                <th title="Pre-select this variation on page load">Default</th>
                                                <th style="width: 120px;">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="variations-table-body">
                                            <tr class="no-default-row">
                                                <td colspan="7" style="text-align: right; padding-right: 20px; color: #666;">
                                                    <em>No default (customer must choose)</em>
                                                </td>
                                                <td>
                                                    <input type="radio" name="default_variation" value="0"
                                                           <?php checked( ! array_filter( $product_variations, function( $v ) { return ! empty( $v['is_default'] ); } ) ); ?>>
                                                </td>
                                                <td></td>
                                            </tr>
                                            <?php foreach ($product_variations as $variation):
                                                $var_price_type = isset($variation['price_type']) ? $variation['price_type'] : 'absolute';
                                            ?>
                                                <tr data-variation-id="<?php echo esc_attr($variation['id']); ?>">
                                                    <td>
                                                        <?php
                                                        $attr_labels = array();
                                                        foreach ($variation['attributes'] as $attr) {
                                                            $attr_labels[] = '<strong>' . esc_html($attr['attribute_name']) . ':</strong> ' . esc_html($attr['attribute_value']);
                                                        }
                                                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped above
                                                        echo implode(', ', $attr_labels);
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <input type="text" name="variations[<?php echo esc_attr($variation['id']); ?>][sku]"
                                                               value="<?php echo esc_attr($variation['sku']); ?>" style="width: 100px;">
                                                    </td>
                                                    <td>
                                                        <input type="number" step="0.01" name="variations[<?php echo esc_attr($variation['id']); ?>][price]"
                                                               value="<?php echo esc_attr($variation['price']); ?>" style="width: 80px;" placeholder="Parent">
                                                    </td>
                                                    <td>
                                                        <select name="variations[<?php echo esc_attr($variation['id']); ?>][price_type]" style="width: 90px;">
                                                            <option value="absolute" <?php selected($var_price_type, 'absolute'); ?>>Absolute</option>
                                                            <option value="modifier" <?php selected($var_price_type, 'modifier'); ?>>+/- Base</option>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <?php if ($stock_mode === 'variation'): ?>
                                                            <input type="number" name="variations[<?php echo esc_attr($variation['id']); ?>][stock]"
                                                                   value="<?php echo esc_attr($variation['stock']); ?>" style="width: 60px;">
                                                        <?php else: ?>
                                                            <span style="color: #999;">Parent</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($variation['image_id']): ?>
                                                            <?php $img_url = wp_get_attachment_image_url($variation['image_id'], 'thumbnail'); ?>
                                                            <img src="<?php echo esc_url($img_url); ?>" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;">
                                                        <?php else: ?>
                                                            <span style="color: #999;">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <input type="radio" name="default_variation" value="<?php echo esc_attr($variation['id']); ?>"
                                                               <?php checked($variation['is_default'], 1); ?>>
                                                    </td>
                                                    <td>
                                                        <button type="button" class="button button-small edit-variation-btn"
                                                                data-variation-id="<?php echo esc_attr($variation['id']); ?>"
                                                                title="Edit variation details">
                                                            <span class="dashicons dashicons-edit" style="vertical-align: middle; line-height: 1.4;"></span>
                                                        </button>
                                                        <button type="button" class="button button-small delete-variation-btn"
                                                                data-variation-id="<?php echo esc_attr($variation['id']); ?>"
                                                                title="Delete this variation"
                                                                style="color: #b32d2e;">
                                                            <span class="dashicons dashicons-trash" style="vertical-align: middle; line-height: 1.4;"></span>
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                    <button type="button" class="button" id="generate-variations-btn">Add Missing Variations</button>
                                <?php endif; ?>
                            </div><!-- end combined-mode-variations -->
                        <?php endif; ?><!-- end has_variations -->

                        <script>
                        jQuery(document).ready(function($) {
                            var $hasVariations = $('#has_variations');
                            var $productType = $('#product_type');
                            var $variationAttrs = $('#variation_attributes');
                            var $variationsRow = $hasVariations.closest('tr');
                            var $variationMode = $('#variation_mode');
                            var $stockMode = $('#variation_stock_mode');

                            // Handle variation mode change (Combined vs Independent)
                            function handleVariationModeChange() {
                                var mode = $variationMode.val();
                                var isIndependent = (mode === 'independent');

                                // Toggle the view between Combined and Independent
                                $('#combined-mode-variations').toggle(!isIndependent);
                                $('#independent-mode-options').toggle(isIndependent);

                                // For Independent mode, force stock to parent and disable the dropdown
                                if (isIndependent) {
                                    $stockMode.val('parent').prop('disabled', true);
                                    $stockMode.closest('tr').find('.description').html(
                                        'Independent mode always uses parent product stock. ' +
                                        '<em>(Variation-level stock is only available in Combined mode)</em>'
                                    );
                                } else {
                                    $stockMode.prop('disabled', false);
                                    $stockMode.closest('tr').find('.description').html(
                                        'Choose whether to track stock at the product level or individually for each variation.'
                                    );
                                }
                            }

                            $variationMode.on('change', handleVariationModeChange);
                            // Initialize on page load
                            handleVariationModeChange();

                            // Auto-enable variations when product type is 'variable'
                            function handleProductTypeChange() {
                                var isVariable = $productType.val() === 'variable';

                                if (isVariable) {
                                    // Hide the "Enable Variations" row - it's implied by the product type
                                    $variationsRow.hide();
                                    // Auto-check the checkbox
                                    $hasVariations.prop('checked', true).trigger('change');
                                } else {
                                    // Show the checkbox row for non-variable products
                                    $variationsRow.show();
                                }
                            }

                            // Toggle variation options visibility
                            $hasVariations.on('change', function() {
                                $('.variations-options').toggle(this.checked);
                                updateGenerateButton();
                                // Also update mode-specific views
                                if (this.checked) {
                                    handleVariationModeChange();
                                }
                            });

                            // Show/hide generate button based on variation selection
                            function updateGenerateButton() {
                                var hasVariationsEnabled = $hasVariations.is(':checked');
                                var selectedCount = $variationAttrs.find('option:selected').length;
                                var $dynamicBtn = $('#generate-variations-dynamic');

                                if (hasVariationsEnabled && selectedCount > 0) {
                                    if ($dynamicBtn.length === 0) {
                                        // Create dynamic button if it doesn't exist (for unsaved products)
                                        var $btnHtml = '<div id="generate-variations-dynamic" style="padding: 15px 20px; background: #f6f7f7; border-top: 1px solid #ddd; margin-top: 10px;">' +
                                            '<p style="margin: 0 0 10px;"><strong>' + selectedCount + ' variation type(s) selected.</strong> Save the product first, then generate variations.</p>' +
                                            '<button type="submit" name="submit" class="button button-primary">Save &amp; Continue</button>' +
                                            '</div>';
                                        $('.variations-options').last().closest('table').after($btnHtml);
                                    } else {
                                        $dynamicBtn.find('p strong').text(selectedCount + ' variation type(s) selected.');
                                        $dynamicBtn.show();
                                    }
                                } else if ($dynamicBtn.length > 0) {
                                    $dynamicBtn.hide();
                                }
                            }

                            // Listen for product type changes
                            $productType.on('change', handleProductTypeChange);

                            // Listen for variation attribute selection changes
                            $variationAttrs.on('change', updateGenerateButton);

                            // Initial state
                            handleProductTypeChange();
                            updateGenerateButton();

                            // Generate variations button
                            $('#generate-variations-btn').on('click', function() {
                                if (confirm('This will generate variations for all attribute combinations. Continue?')) {
                                    $.post(ajaxurl, {
                                        action: 'ggmc_generate_variations',
                                        product_id: <?php echo intval($product_id); ?>,
                                        nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                    }, function(response) {
                                        if (response.success) {
                                            location.reload();
                                        } else {
                                            alert('Error: ' + response.data);
                                        }
                                    });
                                }
                            });

                            // Delete variation button
                            $(document).on('click', '.delete-variation-btn', function() {
                                var $btn = $(this);
                                var variationId = $btn.data('variation-id');
                                var $row = $btn.closest('tr');

                                if (!confirm('Are you sure you want to delete this variation? This cannot be undone.')) {
                                    return;
                                }

                                $btn.prop('disabled', true);

                                $.post(ajaxurl, {
                                    action: 'ggmc_delete_product_variation',
                                    variation_id: variationId,
                                    nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                }, function(response) {
                                    if (response.success) {
                                        $row.fadeOut(300, function() {
                                            $(this).remove();
                                            // Update variation count in heading
                                            var remainingCount = $('#variations-table-body tr').length;
                                            $('h3:contains("Variations")').first().text('Variations (' + remainingCount + ')');
                                        });
                                    } else {
                                        alert('Error: ' + response.data);
                                        $btn.prop('disabled', false);
                                    }
                                });
                            });

                            // Remove variation attribute button
                            $(document).on('click', '.remove-variation-attribute', function() {
                                var $btn = $(this);
                                var attrId = $btn.data('attribute-id');
                                var attrName = $btn.closest('.independent-attribute-section').find('h4 span').first().text();

                                if (!confirm('Remove "' + attrName + '" from this product? You will need to save the product to apply this change.')) {
                                    return;
                                }

                                // Remove from the multi-select dropdown
                                $('#variation_attributes option[value="' + attrId + '"]').prop('selected', false);

                                // Hide the attribute section
                                $btn.closest('.independent-attribute-section').fadeOut(300, function() {
                                    $(this).remove();
                                });

                                // Show a notice that save is needed
                                if ($('.ggmc-save-notice').length === 0) {
                                    $('#independent-mode-options').prepend(
                                        '<div class="ggmc-save-notice notice notice-warning inline" style="margin: 0 0 15px;"><p><strong>Changes pending:</strong> Click "Update Product" to save your changes.</p></div>'
                                    );
                                }
                            });

                            // =========================================
                            // INDEPENDENT MODE OPTION MANAGEMENT
                            // =========================================

                            // Remove individual option (AJAX - immediate)
                            $(document).on('click', '.remove-independent-option', function() {
                                var $btn = $(this);
                                var $row = $btn.closest('tr');
                                var $section = $btn.closest('.independent-attribute-section');
                                var productId = $btn.data('product-id');
                                var attrId = $btn.data('attribute-id');
                                var optionValue = $btn.data('option-value');

                                if (!confirm('Remove "' + optionValue + '"? Customers will no longer be able to select this option.')) {
                                    return;
                                }

                                $btn.prop('disabled', true);

                                $.post(ajaxurl, {
                                    action: 'ggmc_remove_independent_option',
                                    product_id: productId,
                                    attribute_id: attrId,
                                    option_value: optionValue,
                                    nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                }, function(response) {
                                    if (response.success) {
                                        // Remove the row
                                        $row.fadeOut(300, function() {
                                            $(this).remove();

                                            // Check if table is now empty
                                            var $tbody = $section.find('.independent-options-table tbody');
                                            if ($tbody.find('tr').length === 0) {
                                                $section.find('.independent-options-table').replaceWith(
                                                    '<p class="description" style="color: #d63638; margin: 10px 0;">' +
                                                    '<strong>No options available.</strong> Add options using the dropdown below.</p>'
                                                );
                                            }
                                        });

                                        // Update the default radio if needed
                                        if (response.data.default_changed && response.data.new_default) {
                                            $section.find('input[type="radio"][value="' + response.data.new_default + '"]').prop('checked', true);
                                        }

                                        // Update the "Add Missing Options" dropdown
                                        updateMissingOptionsDropdown($section, attrId, response.data.missing_options);
                                    } else {
                                        alert('Error: ' + response.data);
                                        $btn.prop('disabled', false);
                                    }
                                });
                            });

                            // Add option from dropdown
                            $(document).on('change', '.add-missing-option-select', function() {
                                var $select = $(this);
                                var optionValue = $select.val();
                                if (!optionValue) return;

                                var $section = $select.closest('.independent-attribute-section');
                                var productId = $('#independent-mode-options').data('product-id');
                                var attrId = $select.data('attribute-id');
                                var modifier = $select.find('option:selected').data('modifier') || 0;

                                $select.prop('disabled', true);

                                $.post(ajaxurl, {
                                    action: 'ggmc_add_independent_option',
                                    product_id: productId,
                                    attribute_id: attrId,
                                    option_value: optionValue,
                                    modifier: modifier,
                                    nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                }, function(response) {
                                    if (response.success) {
                                        // Reload the page to show new option (simplest approach)
                                        location.reload();
                                    } else {
                                        alert('Error: ' + response.data);
                                        $select.prop('disabled', false);
                                        $select.val('');
                                    }
                                });
                            });

                            // Add all missing options
                            $(document).on('click', '.add-all-missing-options', function() {
                                var $btn = $(this);
                                var productId = $btn.data('product-id');
                                var attrId = $btn.data('attribute-id');

                                $btn.prop('disabled', true).text('Adding...');

                                $.post(ajaxurl, {
                                    action: 'ggmc_add_all_missing_options',
                                    product_id: productId,
                                    attribute_id: attrId,
                                    nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                }, function(response) {
                                    if (response.success) {
                                        // Reload to show all new options
                                        location.reload();
                                    } else {
                                        alert('Error: ' + response.data);
                                        $btn.prop('disabled', false).text('Add All');
                                    }
                                });
                            });

                            // Helper function to update the missing options dropdown
                            function updateMissingOptionsDropdown($section, attrId, missingOptions) {
                                var $wrapper = $section.find('.add-missing-options-wrapper');
                                var currencySymbol = '<?php echo esc_js($currency_symbol); ?>';

                                if (!missingOptions || missingOptions.length === 0) {
                                    $wrapper.html(
                                        '<span class="description" style="color: #00a32a;">' +
                                        '<span class="dashicons dashicons-yes-alt" style="vertical-align: middle;"></span> ' +
                                        'All options added</span>'
                                    );
                                    return;
                                }

                                var selectHtml = '<select class="add-missing-option-select" data-attribute-id="' + attrId + '">';
                                selectHtml += '<option value="">+ Add option...</option>';
                                $.each(missingOptions, function(i, opt) {
                                    var modifierText = '';
                                    if (opt.price_modifier != 0) {
                                        var sign = opt.price_modifier >= 0 ? '+' : '';
                                        modifierText = ' (' + sign + currencySymbol + parseFloat(opt.price_modifier).toFixed(2) + ')';
                                    }
                                    selectHtml += '<option value="' + opt.value + '" data-modifier="' + opt.price_modifier + '">' +
                                                  opt.value + modifierText + '</option>';
                                });
                                selectHtml += '</select>';

                                var html = selectHtml;
                                if (missingOptions.length > 1) {
                                    var productId = $('#independent-mode-options').data('product-id');
                                    html += ' <button type="button" class="button button-small add-all-missing-options" ' +
                                            'data-product-id="' + productId + '" data-attribute-id="' + attrId + '">' +
                                            'Add All (' + missingOptions.length + ')</button>';
                                }

                                $wrapper.html(html);
                            }

                            // Auto-generate SKUs button
                            $('#autogenerate-skus-btn').on('click', function() {
                                var $btn = $(this);

                                if (!confirm('This will overwrite all existing variation SKUs. Continue?')) {
                                    return;
                                }

                                $btn.prop('disabled', true).text('Generating...');

                                $.post(ajaxurl, {
                                    action: 'ggmc_autogenerate_variation_skus',
                                    product_id: <?php echo intval($product_id); ?>,
                                    nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                }, function(response) {
                                    if (response.success) {
                                        location.reload();
                                    } else {
                                        alert('Error: ' + response.data);
                                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-randomize" style="vertical-align: middle; margin-right: 3px;"></span> Auto-Generate SKUs');
                                    }
                                });
                            });

                            // Edit variation button - open modal
                            $(document).on('click', '.edit-variation-btn', function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                var variationId = $(this).data('variation-id');
                                openEditVariationModal(variationId);
                            });

                            // Edit variation modal
                            function openEditVariationModal(variationId) {
                                // Load variation details via AJAX
                                $.post(ajaxurl, {
                                    action: 'ggmc_get_variation_details',
                                    variation_id: variationId,
                                    nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                }, function(response) {
                                    if (response.success) {
                                        showEditModal(response.data);
                                    } else {
                                        alert('Error loading variation: ' + response.data);
                                    }
                                }).fail(function(jqXHR, textStatus, errorThrown) {
                                    alert('AJAX request failed: ' + textStatus);
                                });
                            }

                            function showEditModal(variation) {
                                // Build attribute labels
                                var attrLabels = [];
                                if (variation.attributes) {
                                    variation.attributes.forEach(function(attr) {
                                        attrLabels.push(attr.attribute_name + ': ' + attr.attribute_value);
                                    });
                                }

                                var modalHtml = '<div id="edit-variation-modal" class="ggmc-modal-overlay">' +
                                    '<div class="ggmc-modal" style="max-width: 500px;">' +
                                    '<div class="ggmc-modal-header">' +
                                    '<h2>Edit Variation</h2>' +
                                    '<button type="button" class="ggmc-modal-close">&times;</button>' +
                                    '</div>' +
                                    '<div class="ggmc-modal-body">' +
                                    '<p style="margin-bottom: 15px; color: #666;"><strong>' + attrLabels.join(', ') + '</strong></p>' +
                                    '<table class="form-table" style="margin: 0;">' +
                                    '<tr><th style="width: 120px;"><label>SKU</label></th><td><input type="text" id="modal-sku" value="' + (variation.sku || '') + '" class="regular-text"></td></tr>' +
                                    '<tr><th><label>Price</label></th><td><input type="number" step="0.01" id="modal-price" value="' + (variation.price || '') + '" placeholder="Use parent price" style="width: 120px;"></td></tr>' +
                                    '<tr><th><label>Sale Price</label></th><td><input type="number" step="0.01" id="modal-sale-price" value="' + (variation.sale_price || '') + '" placeholder="Optional" style="width: 120px;"></td></tr>' +
                                    '<tr><th><label>Price Type</label></th><td><select id="modal-price-type"><option value="absolute"' + (variation.price_type === 'absolute' ? ' selected' : '') + '>Absolute</option><option value="modifier"' + (variation.price_type === 'modifier' ? ' selected' : '') + '>+/- Base</option></select></td></tr>' +
                                    '<tr><th><label>Stock</label></th><td><input type="number" id="modal-stock" value="' + (variation.stock || '') + '" placeholder="Use parent stock" style="width: 80px;"></td></tr>' +
                                    '<tr><th><label>Image</label></th><td>' +
                                    '<div id="modal-image-preview" style="margin-bottom: 10px;">' + (variation.image_url ? '<img src="' + variation.image_url + '" style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;">' : '<span style="color: #999;">No image</span>') + '</div>' +
                                    '<input type="hidden" id="modal-image-id" value="' + (variation.image_id || '') + '">' +
                                    '<button type="button" class="button" id="modal-select-image">Select Image</button> ' +
                                    '<button type="button" class="button" id="modal-remove-image"' + (!variation.image_id ? ' style="display:none;"' : '') + '>Remove</button>' +
                                    '</td></tr>' +
                                    '</table>' +
                                    '</div>' +
                                    '<div class="ggmc-modal-footer">' +
                                    '<button type="button" class="button" id="modal-cancel">Cancel</button> ' +
                                    '<button type="button" class="button button-primary" id="modal-save" data-variation-id="' + variation.id + '">Save Changes</button>' +
                                    '</div>' +
                                    '</div>' +
                                    '</div>';

                                $('body').append(modalHtml);

                                // Modal close handlers
                                $('#edit-variation-modal').on('click', '.ggmc-modal-close, #modal-cancel', function() {
                                    $('#edit-variation-modal').remove();
                                });

                                $('#edit-variation-modal').on('click', function(e) {
                                    if ($(e.target).hasClass('ggmc-modal-overlay')) {
                                        $('#edit-variation-modal').remove();
                                    }
                                });

                                // Image selection
                                $('#modal-select-image').on('click', function() {
                                    var frame = wp.media({
                                        title: 'Select Variation Image',
                                        button: { text: 'Use this image' },
                                        multiple: false
                                    });

                                    frame.on('select', function() {
                                        var attachment = frame.state().get('selection').first().toJSON();
                                        $('#modal-image-id').val(attachment.id);
                                        $('#modal-image-preview').html('<img src="' + attachment.sizes.thumbnail.url + '" style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;">');
                                        $('#modal-remove-image').show();
                                    });

                                    frame.open();
                                });

                                $('#modal-remove-image').on('click', function() {
                                    $('#modal-image-id').val('');
                                    $('#modal-image-preview').html('<span style="color: #999;">No image</span>');
                                    $(this).hide();
                                });

                                // Save handler
                                $('#modal-save').on('click', function() {
                                    var $btn = $(this);
                                    var variationId = $btn.data('variation-id');

                                    $btn.prop('disabled', true).text('Saving...');

                                    $.post(ajaxurl, {
                                        action: 'ggmc_update_variation',
                                        variation_id: variationId,
                                        sku: $('#modal-sku').val(),
                                        price: $('#modal-price').val(),
                                        sale_price: $('#modal-sale-price').val(),
                                        price_type: $('#modal-price-type').val(),
                                        stock: $('#modal-stock').val(),
                                        image_id: $('#modal-image-id').val(),
                                        nonce: '<?php echo esc_attr( wp_create_nonce('ggmc_variations') ); ?>'
                                    }, function(response) {
                                        if (response.success) {
                                            location.reload();
                                        } else {
                                            alert('Error: ' + response.data);
                                            $btn.prop('disabled', false).text('Save Changes');
                                        }
                                    });
                                });
                            }
                        });
                        </script>

                    <?php else: ?>
                        <div style="padding: 20px;">
                            <div class="ggmc-premium-notice">
                                <span class="dashicons dashicons-lock" style="font-size: 24px; margin-bottom: 10px;"></span>
                                <p><strong>Product Variations</strong> is a premium feature.</p>
                                <p>Add color, size, material options with per-variation pricing, stock, and gallery images.</p>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>" class="button">
                                    Activate Feature
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

                <?php
                // Section 7: Downloads & Virtual Product (Premium Feature)
                $downloads_activated = GGM_Commerce_License::instance()->is_widget_activated('downloads');
                ?>
                <div class="ggmc-product-section" data-section="downloads">
                    <h2>
                        Downloads & Virtual Product
                        <?php if (!$downloads_activated): ?>
                            <span class="dashicons dashicons-lock" style="color: #0F766E; margin-left: 5px;" title="Premium Feature"></span>
                        <?php endif; ?>
                    </h2>
                    <?php if ($downloads_activated): ?>
                        <?php
                        $virtual_helper = GGM_Commerce_Virtual_Products::instance();
                        $settings = $virtual_helper->get_product_settings($product_id);
                        $downloads_manager = GGM_Commerce_Downloads::instance();
                        $product_downloads = $downloads_manager->get_product_downloads($product_id);
                        ?>
                        <table class="form-table">
                            <tr>
                                <th scope="row">Product Type</th>
                                <td>
                                    <label style="margin-right: 20px;">
                                        <input type="checkbox" name="is_virtual" value="1" <?php checked($settings['is_virtual']); ?>>
                                        Virtual product (no shipping required)
                                    </label>
                                    <br><br>
                                    <label>
                                        <input type="checkbox" name="is_downloadable" id="is_downloadable" value="1" <?php checked($settings['is_downloadable']); ?>>
                                        Downloadable product
                                    </label>
                                    <p class="description">Virtual products don't require shipping. Downloadable products have files customers can download after purchase.</p>
                                </td>
                            </tr>
                            <tr class="downloadable-options" <?php echo !$settings['is_downloadable'] ? 'style="display:none;"' : ''; ?>>
                                <th scope="row"><label for="download_access_mode">Access Control</label></th>
                                <td>
                                    <select name="download_access_mode" id="download_access_mode">
                                        <option value="unlimited" <?php selected($settings['download_access_mode'], 'unlimited'); ?>>Unlimited downloads</option>
                                        <option value="limited" <?php selected($settings['download_access_mode'], 'limited'); ?>>Limited downloads (per file)</option>
                                        <option value="license" <?php selected($settings['download_access_mode'], 'license'); ?>>Requires license key</option>
                                    </select>
                                    <p class="description">How customers can access their downloads after purchase.</p>
                                </td>
                            </tr>
                        </table>

                        <div class="downloadable-options" <?php echo !$settings['is_downloadable'] ? 'style="display:none;"' : ''; ?>>
                            <div style="padding: 0 20px 20px;">
                                <h3>Downloadable Files</h3>
                                <table class="wp-list-table widefat striped" id="downloads-table" style="margin-bottom: 15px;">
                                    <thead>
                                        <tr>
                                            <th style="width: 30%;">File Name</th>
                                            <th style="width: 35%;">File URL</th>
                                            <th style="width: 10%;">Limit</th>
                                            <th style="width: 10%;">Expiry (days)</th>
                                            <th style="width: 15%;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($product_downloads)): ?>
                                            <tr class="no-downloads">
                                                <td colspan="5"><em>No downloadable files added yet.</em></td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($product_downloads as $index => $download): ?>
                                                <tr>
                                                    <td>
                                                        <input type="hidden" name="downloads[<?php echo intval( $index ); ?>][id]" value="<?php echo esc_attr($download['id']); ?>">
                                                        <input type="text" name="downloads[<?php echo intval( $index ); ?>][name]"
                                                               value="<?php echo esc_attr($download['name']); ?>" class="regular-text" required>
                                                    </td>
                                                    <td>
                                                        <input type="url" name="downloads[<?php echo intval( $index ); ?>][file_url]"
                                                               value="<?php echo esc_attr($download['file_url']); ?>" class="regular-text" required>
                                                        <button type="button" class="button button-small upload-download-btn">Browse</button>
                                                    </td>
                                                    <td>
                                                        <input type="number" name="downloads[<?php echo intval( $index ); ?>][download_limit]"
                                                               value="<?php echo esc_attr($download['download_limit']); ?>"
                                                               style="width: 60px;" min="-1" title="-1 = unlimited">
                                                    </td>
                                                    <td>
                                                        <input type="number" name="downloads[<?php echo intval( $index ); ?>][access_expiry_days]"
                                                               value="<?php echo esc_attr($download['access_expiry_days']); ?>"
                                                               style="width: 60px;" min="-1" title="-1 = never expires">
                                                    </td>
                                                    <td>
                                                        <button type="button" class="button button-small button-link-delete remove-download-btn">Remove</button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                                <button type="button" class="button" id="add-download-btn">Add File</button>
                                <p class="description">Limit: -1 for unlimited. Expiry: -1 for never expires.</p>
                            </div>
                        </div>

                        <script>
                        jQuery(document).ready(function($) {
                            var downloadIndex = <?php echo count($product_downloads); ?>;

                            $('#is_downloadable').on('change', function() {
                                $('.downloadable-options').toggle(this.checked);
                            });

                            $('#add-download-btn').on('click', function() {
                                var row = '<tr>' +
                                    '<td><input type="text" name="downloads[' + downloadIndex + '][name]" class="regular-text" placeholder="File name" required></td>' +
                                    '<td><input type="url" name="downloads[' + downloadIndex + '][file_url]" class="regular-text" placeholder="File URL" required> ' +
                                    '<button type="button" class="button button-small upload-download-btn">Browse</button></td>' +
                                    '<td><input type="number" name="downloads[' + downloadIndex + '][download_limit]" value="-1" style="width: 60px;" min="-1"></td>' +
                                    '<td><input type="number" name="downloads[' + downloadIndex + '][access_expiry_days]" value="-1" style="width: 60px;" min="-1"></td>' +
                                    '<td><button type="button" class="button button-small button-link-delete remove-download-btn">Remove</button></td>' +
                                    '</tr>';
                                $('#downloads-table tbody .no-downloads').remove();
                                $('#downloads-table tbody').append(row);
                                downloadIndex++;
                            });

                            $(document).on('click', '.remove-download-btn', function() {
                                $(this).closest('tr').remove();
                                if ($('#downloads-table tbody tr').length === 0) {
                                    $('#downloads-table tbody').append('<tr class="no-downloads"><td colspan="5"><em>No downloadable files added yet.</em></td></tr>');
                                }
                            });

                            $(document).on('click', '.upload-download-btn', function() {
                                var $input = $(this).prev('input');
                                var frame = wp.media({
                                    title: 'Select Download File',
                                    button: { text: 'Use this file' },
                                    multiple: false
                                });
                                frame.on('select', function() {
                                    var attachment = frame.state().get('selection').first().toJSON();
                                    $input.val(attachment.url);
                                });
                                frame.open();
                            });
                        });
                        </script>
                    <?php else: ?>
                        <div style="padding: 20px;">
                            <div class="ggmc-premium-notice">
                                <span class="dashicons dashicons-lock" style="font-size: 24px; margin-bottom: 10px;"></span>
                                <p><strong>Digital Downloads</strong> is a premium feature.</p>
                                <p>Sell downloadable products with secure delivery, download limits, and license keys.</p>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>" class="button">
                                    Activate Feature
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                    <div class="ggmc-section-footer">
                        <button type="submit" name="submit" class="button button-primary">Update Product</button>
                    </div>
                </div>

            </form>
        </div>

        
        <script>
        jQuery(document).ready(function($) {
            // WordPress media uploader
            var mediaUploader;
            var galleryUploader;
            
            // Main image uploader
            $('.upload-image-button').click(function(e) {
                e.preventDefault();
                
                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }
                
                mediaUploader = wp.media({
                    title: 'Choose Main Product Image',
                    button: {
                        text: 'Choose Image'
                    },
                    multiple: false
                });
                
                mediaUploader.on('select', function() {
                    var attachment = mediaUploader.state().get('selection').first().toJSON();
                    $('#main_image_id').val(attachment.id);
                    
                    var imageHtml = '<div class="image-item" data-id="' + attachment.id + '">' +
                                   '<img src="' + attachment.url + '" alt="Main Product Image" />' +
                                   '<span class="remove-single-image" data-id="' + attachment.id + '">&times;</span>' +
                                   '</div>';
                    
                    $('#main_image_preview').html(imageHtml);
                    $('.remove-image-button[data-target="main_image"]').show();
                });
                
                mediaUploader.open();
            });
            
            // Gallery images uploader
            $('.upload-gallery-button').click(function(e) {
                e.preventDefault();
                
                if (galleryUploader) {
                    galleryUploader.open();
                    return;
                }
                
                galleryUploader = wp.media({
                    title: 'Choose Gallery Images',
                    button: {
                        text: 'Add to Gallery'
                    },
                    multiple: true
                });
                
                galleryUploader.on('select', function() {
                    var attachments = galleryUploader.state().get('selection').toJSON();
                    var currentIds = $('#gallery_image_ids').val();
                    var idsArray = currentIds ? currentIds.split(',') : [];
                    
                    $.each(attachments, function(index, attachment) {
                        if (idsArray.indexOf(attachment.id.toString()) === -1) {
                            idsArray.push(attachment.id);
                            
                            var imageHtml = '<div class="image-item" data-id="' + attachment.id + '">' +
                                           '<img src="' + attachment.url + '" alt="Gallery Image" />' +
                                           '<span class="remove-single-image" data-id="' + attachment.id + '">&times;</span>' +
                                           '</div>';
                            
                            $('#gallery_images_preview').append(imageHtml);
                        }
                    });
                    
                    $('#gallery_image_ids').val(idsArray.join(','));
                    $('.remove-all-gallery-button[data-target="gallery_images"]').show();
                });
                
                galleryUploader.open();
            });
            
            // Remove single main image
            $(document).on('click', '.remove-image-button[data-target="main_image"]', function() {
                $('#main_image_id').val('');
                $('#main_image_preview').empty();
                $(this).hide();
            });
            
            // Remove single gallery image
            $(document).on('click', '.remove-single-image', function() {
                var imageId = $(this).data('id').toString();
                var currentIds = $('#gallery_image_ids').val();
                var idsArray = currentIds ? currentIds.split(',') : [];
                var index = idsArray.indexOf(imageId);

                if (index > -1) {
                    idsArray.splice(index, 1);
                }

                $('#gallery_image_ids').val(idsArray.join(','));
                $(this).parent().remove();

                if (idsArray.length === 0) {
                    $('.remove-all-gallery-button[data-target="gallery_images"]').hide();
                }
            });

            // Remove all gallery images
            $(document).on('click', '.remove-all-gallery-button[data-target="gallery_images"]', function() {
                $('#gallery_image_ids').val('');
                $('#gallery_images_preview').empty();
                $(this).hide();
            });

            // Populate gallery from kit/build components (handles both buttons)
            $('.populate-gallery-from-components').click(function(e) {
                e.preventDefault();

                var $button = $(this);
                var originalText = $button.html();
                var includeGallery = $button.data('include-gallery') === true;

                // Get component product IDs from the kit components list
                var componentIds = [];
                $('#kit-components-list .kit-component-row').each(function() {
                    var productId = $(this).data('product-id');
                    if (productId) {
                        componentIds.push(productId);
                    }
                });

                if (componentIds.length === 0) {
                    alert('No components found. Please add components to the kit/build first.');
                    return;
                }

                $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin" style="animation: spin 1s linear infinite;"></span> Loading...');

                // AJAX call to get component images
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'ggmc_get_component_images',
                        product_ids: componentIds,
                        include_gallery: includeGallery ? 1 : 0,
                        nonce: '<?php echo esc_js(wp_create_nonce('ggmc_get_component_images')); ?>'
                    },
                    success: function(response) {
                        if (response.success && response.data.images) {
                            var currentIds = $('#gallery_image_ids').val();
                            var idsArray = currentIds ? currentIds.split(',').filter(function(id) { return id !== ''; }) : [];
                            var addedCount = 0;

                            $.each(response.data.images, function(index, image) {
                                if (idsArray.indexOf(image.id.toString()) === -1) {
                                    idsArray.push(image.id);
                                    addedCount++;

                                    var imageHtml = '<div class="image-item" data-id="' + image.id + '">' +
                                                   '<img src="' + image.url + '" alt="Component Image" />' +
                                                   '<span class="remove-single-image" data-id="' + image.id + '">&times;</span>' +
                                                   '</div>';

                                    $('#gallery_images_preview').append(imageHtml);
                                }
                            });

                            $('#gallery_image_ids').val(idsArray.join(','));

                            if (idsArray.length > 0) {
                                $('.remove-all-gallery-button[data-target="gallery_images"]').show();
                            }

                            if (addedCount > 0) {
                                var imageType = includeGallery ? 'image(s) (primary + gallery)' : 'primary image(s)';
                                alert(addedCount + ' ' + imageType + ' added from components.');
                            } else {
                                alert('No new images to add. Component images may already be in the gallery or components have no images.');
                            }
                        } else {
                            alert(response.data.message || 'Failed to fetch component images.');
                        }
                    },
                    error: function() {
                        alert('Error fetching component images. Please try again.');
                    },
                    complete: function() {
                        $button.prop('disabled', false).html(originalText);
                    }
                });
            });

            <?php if ($barcode_activated): ?>
            // Barcode management
            var barcodeIndex = <?php echo count($barcodes); ?>;
            var barcodeTypes = <?php echo wp_json_encode($barcode_types); ?>;

            // Add barcode button
            $('#add-barcode-button').click(function(e) {
                e.preventDefault();

                if ($('.barcode-row').length >= 3) {
                    alert('Maximum 3 barcodes per product');
                    return;
                }

                var typesOptions = '';
                $.each(barcodeTypes, function(key, label) {
                    typesOptions += '<option value="' + key + '">' + label + '</option>';
                });

                var barcodeHtml = '<div class="barcode-row" style="margin-bottom: 10px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">' +
                    '<input type="hidden" name="barcodes[' + barcodeIndex + '][id]" value="0" />' +
                    '<div style="display: grid; grid-template-columns: 2fr 1fr auto auto; gap: 10px; align-items: center;">' +
                        '<input type="text" name="barcodes[' + barcodeIndex + '][value]" value="" class="regular-text" placeholder="Barcode value" />' +
                        '<select name="barcodes[' + barcodeIndex + '][type]">' + typesOptions + '</select>' +
                        '<label style="white-space: nowrap;"><input type="checkbox" name="barcodes[' + barcodeIndex + '][is_primary]" value="1" /> Primary</label>' +
                        '<button type="button" class="button remove-barcode-button">Remove</button>' +
                    '</div>' +
                '</div>';

                $('#barcodes-container').append(barcodeHtml);
                barcodeIndex++;

                if ($('.barcode-row').length >= 3) {
                    $('#add-barcode-button').prop('disabled', true);
                }
            });

            // Remove barcode button
            $(document).on('click', '.remove-barcode-button', function() {
                $(this).closest('.barcode-row').remove();

                if ($('.barcode-row').length < 3) {
                    $('#add-barcode-button').prop('disabled', false);
                }
            });

            // Ensure only one primary barcode
            $(document).on('change', 'input[name$="[is_primary]"]', function() {
                if ($(this).is(':checked')) {
                    $('input[name$="[is_primary]"]').not(this).prop('checked', false);
                }
            });
            <?php endif; // End barcode JS ?>

            <?php if (GGM_Commerce_License::instance()->is_widget_activated('custom-attributes')):
                $attributes_manager = GGM_Commerce_Attributes::get_instance();
                $product_attributes = $attributes_manager->get_product_attributes($product_id);
            ?>
            // Custom Attributes Management (Edit Product Page)
            var attributeIndex = <?php echo count($product_attributes); ?>;
            var groupAttributes = <?php echo wp_json_encode($attributes_manager->get_group_attributes_map_v2()); ?>;

            // Add single attribute
            $('#add-single-attribute').on('change', function() {
                var $selected = $(this).find('option:selected');
                var attrId = $selected.val();
                if (!attrId) return;

                var attrName = $selected.data('name');
                var attrType = $selected.data('type');
                var attrOptions = $selected.data('options');
                var attrUnit = $selected.data('unit') || '';

                addAttributeRow(attrId, attrName, attrType, attrOptions, attrUnit);

                // Remove from dropdown and reset
                $selected.remove();
                $(this).val('');
            });

            // Add from group
            $('#add-from-group').on('change', function() {
                var groupId = $(this).val();
                if (!groupId || !groupAttributes[groupId]) return;

                var attrs = groupAttributes[groupId];
                attrs.forEach(function(attr) {
                    // Check if attribute already exists
                    if ($('.ggmc-attribute-row[data-attribute-id="' + attr.id + '"]').length === 0) {
                        addAttributeRow(attr.id, attr.name, attr.attribute_type, attr.options, attr.unit || '');
                        // Remove from single attribute dropdown
                        $('#add-single-attribute option[value="' + attr.id + '"]').remove();
                    }
                });

                $(this).val('');
            });

            // Add attribute row helper
            function addAttributeRow(attrId, attrName, attrType, attrOptions, attrUnit) {
                var valueInput = '';
                if (attrType === 'select' && attrOptions) {
                    var options = typeof attrOptions === 'string' ? JSON.parse(attrOptions) : attrOptions;
                    if (Array.isArray(options) && options.length > 0) {
                        valueInput = '<select name="custom_attributes[' + attributeIndex + '][value]" style="width: 200px;"><option value="">-- Select --</option>';
                        options.forEach(function(opt) {
                            valueInput += '<option value="' + escapeHtml(opt) + '">' + escapeHtml(opt) + '</option>';
                        });
                        valueInput += '</select>';
                    } else {
                        valueInput = '<input type="text" name="custom_attributes[' + attributeIndex + '][value]" value="" style="width: 200px;" />';
                    }
                } else if (attrType === 'number') {
                    valueInput = '<input type="number" step="any" name="custom_attributes[' + attributeIndex + '][value]" value="" style="width: 150px;" />';
                } else {
                    valueInput = '<input type="text" name="custom_attributes[' + attributeIndex + '][value]" value="" style="width: 200px;" />';
                }

                var unitSpan = attrUnit ? '<span class="attr-unit" style="color: #666;">' + escapeHtml(attrUnit) + '</span>' : '<span class="attr-unit"></span>';

                var rowHtml = '<div class="ggmc-attribute-row" data-attribute-id="' + attrId + '" style="margin-bottom: 10px; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">' +
                    '<div style="display: grid; grid-template-columns: auto 150px 1fr auto auto; gap: 10px; align-items: center;">' +
                        '<span class="dashicons dashicons-menu ggmc-drag-handle" style="cursor: grab; color: #999;"></span>' +
                        '<input type="hidden" name="custom_attributes[' + attributeIndex + '][attribute_id]" value="' + attrId + '" />' +
                        '<input type="hidden" name="custom_attributes[' + attributeIndex + '][display_order]" class="attr-order" value="' + attributeIndex + '" />' +
                        '<label style="font-weight: 500;">' + escapeHtml(attrName) + '</label>' +
                        valueInput +
                        unitSpan +
                        '<button type="button" class="button remove-attribute-btn" data-attribute-id="' + attrId + '">&times;</button>' +
                    '</div>' +
                '</div>';

                $('#custom-attributes-container').append(rowHtml);
                attributeIndex++;
                updateAttributeOrder();
            }

            // Remove attribute
            $(document).on('click', '.remove-attribute-btn', function(e) {
                e.preventDefault();
                e.stopPropagation();

                var $row = $(this).closest('.ggmc-attribute-row');
                $row.remove();
                updateAttributeOrder();
            });

            // Update display order values
            function updateAttributeOrder() {
                $('#custom-attributes-container .ggmc-attribute-row').each(function(index) {
                    $(this).find('.attr-order').val(index);
                });
            }

            // Helper function to escape HTML
            function escapeHtml(text) {
                if (!text) return '';
                var div = document.createElement('div');
                div.appendChild(document.createTextNode(text));
                return div.innerHTML;
            }

            // Make sortable if jQuery UI is available
            if ($.fn.sortable) {
                $('#custom-attributes-container').sortable({
                    handle: '.ggmc-drag-handle',
                    update: function() {
                        updateAttributeOrder();
                    }
                });
            }
            <?php endif; // End premium check for custom attributes JS ?>

            // Product Type visibility controller
            var productTypeSections = <?php echo wp_json_encode(GGM_Commerce_Helpers::get_product_types()); ?>;

            function updateSectionVisibility() {
                var selectedType = $('#product_type').val();
                var typeConfig = productTypeSections[selectedType];

                if (!typeConfig) {
                    typeConfig = productTypeSections['simple'];
                }

                var visibleSections = typeConfig.sections || [];

                // Show/hide sections based on product type
                $('[data-section]').each(function() {
                    var sectionKey = $(this).data('section');
                    if (visibleSections.indexOf(sectionKey) !== -1) {
                        $(this).slideDown(200);
                    } else {
                        $(this).slideUp(200);
                    }
                });

                // Check if premium type is selected but not available
                var selectedOption = $('#product_type option:selected');
                var isAvailable = selectedOption.data('available') === true || selectedOption.data('available') === 'true';

                if (!isAvailable) {
                    // Show premium upgrade prompt
                    $('#product-type-description').html(
                        '<span style="color: #d63638;">This product type requires premium activation. ' +
                        '<a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>">Activate Premium Features</a></span>'
                    );
                } else {
                    $('#product-type-description').text('<?php echo esc_js(__('Select the type of product. Premium types show 🔒 if not activated.', 'ggm-commerce')); ?>');
                }
            }

            // Bind change event to product type dropdown
            $('#product_type').on('change', updateSectionVisibility);

            // Initial visibility update (only if dropdown exists)
            if ($('#product_type').length) {
                updateSectionVisibility();
            }
        });
        </script>
        <?php
    }

    /**
     * Hide submenu items with CSS
     */
    public function hide_submenu_items() {
        echo '<style>
            #toplevel_page_ggmc-plugin .wp-submenu a[href="admin.php?page=ggmc-general"],
            #toplevel_page_ggmc-plugin .wp-submenu a[href="admin.php?page=ggmc-test-data"],
            #toplevel_page_ggmc-plugin .wp-submenu a[href="admin.php?page=ggmc-default-styles"],
            #menu-settings .wp-submenu a[href="options.php?page=ggmc-add-product"],
            #menu-settings .wp-submenu a[href="options.php?page=ggmc-edit-product"] {
                display: none !important;
            }
        </style>';
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        // Only load on our plugin pages (check for both ggm-commerce and ggmc- prefixes)
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Initialization timing check not form processing
        $is_ggmc_page = strpos($hook, 'ggm-commerce') !== false ||
                        strpos($hook, 'ggmc-') !== false ||
                        (isset($_GET['page']) && (
                            strpos($_GET['page'], 'ggm-commerce') !== false ||
                            strpos($_GET['page'], 'ggmc-') !== false
                        ));

        // Brand variables (colors, fonts) - loaded on all GGM pages including WP dashboard widget
        wp_enqueue_style(
            'ggmc-admin-variables',
            plugins_url('assets/css/admin-variables.css', dirname(__FILE__)),
            array(),
            filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/css/admin-variables.css')
        );

        // Load admin styles on the WordPress dashboard for the shop widget
        if ($hook === 'index.php') {
            wp_enqueue_style(
                'ggmc-admin',
                plugins_url('assets/css/admin.css', dirname(__FILE__)),
                array('ggmc-admin-variables'),
                filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/css/admin.css')
            );
        }

        if ($is_ggmc_page) {
            // Enqueue WordPress media library
            wp_enqueue_media();

            // Enqueue jQuery (usually already loaded in admin)
            wp_enqueue_script('jquery');

            // Admin styles (shared across all GGM admin pages)
            wp_enqueue_style(
                'ggmc-admin',
                plugins_url('assets/css/admin.css', dirname(__FILE__)),
                array('ggmc-admin-variables'),
                filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/css/admin.css')
            );

            // Settings page stylesheet (sidebar navigation + help panel)
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page identification, not form processing
            if (isset($_GET['page']) && $_GET['page'] === 'ggmc-settings') {
                wp_enqueue_style(
                    'ggmc-admin-settings',
                    plugins_url('assets/css/admin-settings.css', dirname(__FILE__)),
                    array('ggmc-admin'),
                    filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/css/admin-settings.css')
                );
            }

            // Enqueue Elementor icons for consistent styling across plugin pages
            if (defined('ELEMENTOR_ASSETS_URL')) {
                wp_enqueue_style(
                    'elementor-icons',
                    ELEMENTOR_ASSETS_URL . 'lib/eicons/css/elementor-icons.min.css',
                    array(),
                    defined('ELEMENTOR_VERSION') ? ELEMENTOR_VERSION : '1.0.0'
                );
            }

            // Load WordPress color picker on Widget Controls page
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page identification, not form processing
            if (isset($_GET['page']) && $_GET['page'] === 'ggm-commerce-settings' && isset($_GET['tab']) && $_GET['tab'] === 'widget-controls') {
                wp_enqueue_style('wp-color-picker');
                wp_enqueue_script('wp-color-picker');
            }

            // Load WordPress color picker on Variation Attributes page (for color swatches)
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page identification, not form processing
            if (isset($_GET['page']) && $_GET['page'] === 'ggmc-variation-attributes') {
                wp_enqueue_style('wp-color-picker');
                wp_enqueue_script('wp-color-picker');
            }

            // Load Font Awesome and icon picker on attributes page
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page identification, not form processing
            if (isset($_GET['page']) && $_GET['page'] === 'ggmc-attributes') {
                wp_enqueue_style(
                    'font-awesome',
                    'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css',
                    array(),
                    '6.5.1'
                );

                // Icon picker CSS
                wp_enqueue_style(
                    'ggmc-icon-picker',
                    plugins_url('assets/css/icon-picker.css', dirname(__FILE__)),
                    array('font-awesome'),
                    '1.0.0'
                );

                // Icon picker JS
                wp_enqueue_script(
                    'ggmc-icon-picker',
                    plugins_url('assets/js/icon-picker.js', dirname(__FILE__)),
                    array('jquery'),
                    '1.0.0',
                    true
                );

                // Localize script with AJAX URL and nonce
                wp_localize_script(
                    'ggmc-icon-picker',
                    'ggmcIconPicker',
                    array(
                        'ajaxUrl' => admin_url('admin-ajax.php'),
                        'nonce'   => wp_create_nonce('ggmc_icon_picker'),
                    )
                );
            }

            // Add inline styles for product type badges and kit management
            wp_add_inline_style('wp-admin', $this->get_kit_admin_styles());

            // Load bulk actions script on products, categories, tags, attributes, and variation attributes pages
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page identification, not form processing
            $bulk_action_pages = array('ggmc-products', 'ggmc-categories', 'ggmc-tags', 'ggmc-attributes', 'ggmc-variation-attributes');
            if (isset($_GET['page']) && in_array($_GET['page'], $bulk_action_pages, true)) {
                wp_enqueue_script(
                    'ggmc-bulk-actions',
                    plugins_url('assets/js/bulk-actions.js', dirname(__FILE__)),
                    array('jquery'),
                    '1.0.0',
                    true
                );
            }

            // Load import/export scripts on products page
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page identification, not form processing
            if (isset($_GET['page']) && $_GET['page'] === 'ggmc-products') {
                // Import/export CSS
                wp_enqueue_style(
                    'ggmc-import-export',
                    plugins_url('assets/css/import-export.css', dirname(__FILE__)),
                    array(),
                    '1.0.0'
                );

                // Import/export JS
                wp_enqueue_script(
                    'ggmc-import-export',
                    plugins_url('assets/js/import-export.js', dirname(__FILE__)),
                    array('jquery'),
                    '1.0.0',
                    true
                );

                // Get product count and selected IDs for localization
                global $wpdb;
                $product_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_products WHERE status != 'trash'");

                // Get field mapper for available fields
                require_once plugin_dir_path(__FILE__) . 'import-export/class-field-mapper.php';
                $field_mapper = new GGM_Commerce_Field_Mapper();

                // Localize script
                wp_localize_script(
                    'ggmc-import-export',
                    'ggmcImportExport',
                    array(
                        'ajaxUrl' => admin_url('admin-ajax.php'),
                        'nonce' => wp_create_nonce('ggmc_import_export'),
                        'productCount' => $product_count,
                        'selectedCount' => 0, // Will be updated via JS
                        'selectedIds' => array(),
                        'availableFields' => $field_mapper->get_available_fields(),
                        'strings' => array(
                            'exportTitle' => __('Export Products', 'ggm-commerce'),
                            'importTitle' => __('Import Products', 'ggm-commerce'),
                            'exportFormat' => __('Export Format', 'ggm-commerce'),
                            'simpleFormat' => __('Simple (Single CSV)', 'ggm-commerce'),
                            'simpleFormatDesc' => __('Single CSV file with JSON for complex data', 'ggm-commerce'),
                            'advancedFormat' => __('Advanced (Multiple Files)', 'ggm-commerce'),
                            'advancedFormatDesc' => __('ZIP with separate CSVs for products, variations, etc.', 'ggm-commerce'),
                            'whatToExport' => __('What to Export', 'ggm-commerce'),
                            'allProducts' => __('All products', 'ggm-commerce'),
                            'selectedOnly' => __('Selected products only', 'ggm-commerce'),
                            'includeData' => __('Include', 'ggm-commerce'),
                            'categories' => __('Categories & Tags', 'ggm-commerce'),
                            'tags' => __('Tags', 'ggm-commerce'),
                            'attributes' => __('Custom Attributes', 'ggm-commerce'),
                            'variations' => __('Variations', 'ggm-commerce'),
                            'barcodes' => __('Barcodes', 'ggm-commerce'),
                            'kits' => __('Kit/Build Components', 'ggm-commerce'),
                            'downloads' => __('Downloadable Files', 'ggm-commerce'),
                            'downloadTemplate' => __('Download Template', 'ggm-commerce'),
                            'exportProducts' => __('Export Products', 'ggm-commerce'),
                            'exporting' => __('Exporting...', 'ggm-commerce'),
                            'exportError' => __('Export failed. Please try again.', 'ggm-commerce'),
                            'templateError' => __('Failed to generate template.', 'ggm-commerce'),
                            'step' => __('Step', 'ggm-commerce'),
                            'upload' => __('Upload', 'ggm-commerce'),
                            'mapFields' => __('Map Fields', 'ggm-commerce'),
                            'import' => __('Import', 'ggm-commerce'),
                            'dragDrop' => __('Drag & drop CSV file here or click to browse', 'ggm-commerce'),
                            'fileHint' => __('Supported: .csv files up to 10MB', 'ggm-commerce'),
                            'fileFormat' => __('File Format', 'ggm-commerce'),
                            'autoDetect' => __('Auto-detect', 'ggm-commerce'),
                            'autoDetectDesc' => __('Automatically detect Goose Commerce or WooCommerce format', 'ggm-commerce'),
                            'wooFormat' => __('WooCommerce Export', 'ggm-commerce'),
                            'wooFormatDesc' => __('Standard WooCommerce product export format', 'ggm-commerce'),
                            'needTemplate' => __('Need a template?', 'ggm-commerce'),
                            'downloadTemplateLink' => __('Download Blank Template', 'ggm-commerce'),
                            'cancel' => __('Cancel', 'ggm-commerce'),
                            'next' => __('Next', 'ggm-commerce'),
                            'back' => __('Back', 'ggm-commerce'),
                            'invalidFileType' => __('Please select a CSV file.', 'ggm-commerce'),
                            'fileTooLarge' => __('File size exceeds 10MB limit.', 'ggm-commerce'),
                            'uploadError' => __('Failed to upload file. Please try again.', 'ggm-commerce'),
                            'fileInfo' => __('File', 'ggm-commerce'),
                            'rowsDetected' => __('rows detected', 'ggm-commerce'),
                            'totalColumns' => __('Total Columns', 'ggm-commerce'),
                            'mapped' => __('Mapped', 'ggm-commerce'),
                            'skipped' => __('Skipped', 'ggm-commerce'),
                            'csvColumn' => __('CSV Column', 'ggm-commerce'),
                            'productField' => __('Goose Commerce Field', 'ggm-commerce'),
                            'status' => __('Status', 'ggm-commerce'),
                            'skipColumn' => __('-- Skip this column --', 'ggm-commerce'),
                            'preview' => __('Preview (first 3 rows)', 'ggm-commerce'),
                            'saveMapping' => __('Save this mapping for future imports', 'ggm-commerce'),
                            'nameRequired' => __('Product Name field must be mapped.', 'ggm-commerce'),
                            'readyToImport' => __('Ready to import', 'ggm-commerce'),
                            'products' => __('products', 'ggm-commerce'),
                            'duplicateHandling' => __('Duplicate Handling (when SKU already exists)', 'ggm-commerce'),
                            'skipDuplicates' => __('Skip duplicates', 'ggm-commerce'),
                            'skipDuplicatesDesc' => __('Keep existing products, skip duplicates', 'ggm-commerce'),
                            'updateExisting' => __('Update existing products', 'ggm-commerce'),
                            'updateExistingDesc' => __('Update existing products with new data', 'ggm-commerce'),
                            'createNew' => __('Create new', 'ggm-commerce'),
                            'createNewDesc' => __('Create new products (duplicate SKUs allowed)', 'ggm-commerce'),
                            'imageHandling' => __('Image Handling', 'ggm-commerce'),
                            'downloadImages' => __('Download images from URLs', 'ggm-commerce'),
                            'dataHandling' => __('Create Missing Data', 'ggm-commerce'),
                            'createCategories' => __('Create missing categories automatically', 'ggm-commerce'),
                            'createTags' => __('Create missing tags automatically', 'ggm-commerce'),
                            'createAttributes' => __('Create missing attributes automatically', 'ggm-commerce'),
                            'warningBackup' => __('This operation cannot be undone. Consider exporting your current products first as a backup.', 'ggm-commerce'),
                            'startImport' => __('Start Import', 'ggm-commerce'),
                            'importing' => __('Importing Products...', 'ggm-commerce'),
                            'created' => __('Created', 'ggm-commerce'),
                            'updated' => __('Updated', 'ggm-commerce'),
                            'skippedStat' => __('Skipped', 'ggm-commerce'),
                            'errors' => __('Errors', 'ggm-commerce'),
                            'currentItem' => __('Currently processing', 'ggm-commerce'),
                            'row' => __('Row', 'ggm-commerce'),
                            'importComplete' => __('Import Complete', 'ggm-commerce'),
                            'done' => __('Done', 'ggm-commerce'),
                            'importError' => __('Import failed. Please try again.', 'ggm-commerce'),
                            'confirmCancel' => __('Import is in progress. Are you sure you want to cancel?', 'ggm-commerce'),
                        )
                    )
                );
            }
        }
    }

    /**
     * Get admin styles for kits feature.
     *
     * @return string CSS styles.
     */
    private function get_kit_admin_styles() {
        return '
            /* Product Type Badges */
            .ggmc-product-type-badge {
                display: inline-block;
                font-size: 10px;
                font-weight: 600;
                text-transform: uppercase;
                padding: 2px 6px;
                border-radius: 3px;
                margin-left: 8px;
                vertical-align: middle;
            }
            .ggmc-type-kit {
                background: #e7f7ed;
                color: #00a32a;
                border: 1px solid #00a32a;
            }
            .ggmc-type-build {
                background: #e6f4f3;
                color: #0073aa;
                border: 1px solid #0073aa;
            }
            .ggmc-type-variable {
                background: #fef7e7;
                color: #996800;
                border: 1px solid #996800;
            }
            .ggmc-type-virtual {
                background: #f3e8ff;
                color: #7c3aed;
                border: 1px solid #7c3aed;
            }
            .ggmc-type-digital {
                background: #fce7f3;
                color: #be185d;
                border: 1px solid #be185d;
            }

            /* Stock Status Badges */
            .ggmc-stock-badge {
                display: inline-block;
                font-size: 12px;
                font-weight: 600;
                padding: 2px 8px;
                border-radius: 3px;
            }
            .ggmc-stock-in {
                background: #edfaef;
                color: #00a32a;
            }
            .ggmc-stock-low {
                background: #fcf9e8;
                color: #996800;
            }
            .ggmc-stock-out {
                background: #fcf0f1;
                color: #d63638;
            }
            .ggmc-stock-unmanaged {
                background: #f0f0f1;
                color: #8c8f94;
            }

            /* Kit Components Section */
            .ggmc-kit-components-section {
                margin-top: 15px;
            }
            .ggmc-kit-components-list {
                border: 1px solid #c3c4c7;
                border-radius: 4px;
                margin-top: 10px;
            }
            .ggmc-kit-component-row {
                display: flex;
                align-items: center;
                gap: 10px;
                padding: 10px 15px;
                border-bottom: 1px solid #e2e4e7;
            }
            .ggmc-kit-component-row:last-child {
                border-bottom: none;
            }
            .ggmc-kit-component-row .component-name {
                flex: 1;
            }
            .ggmc-kit-component-row .component-qty {
                width: 60px;
            }
            .ggmc-kit-component-row .component-stock {
                color: #666;
                font-size: 12px;
            }
            .ggmc-kit-component-row .component-remove {
                color: #b32d2e;
                cursor: pointer;
            }
            .ggmc-kit-add-component {
                padding: 10px 15px;
                background: #f6f7f7;
                display: flex;
                gap: 10px;
                align-items: center;
            }
            .ggmc-kit-stats {
                background: #e6f4f3;
                border: 1px solid #c8d9ea;
                padding: 12px 15px;
                border-radius: 4px;
                margin-top: 15px;
            }
            .ggmc-kit-stats p {
                margin: 5px 0;
            }
            .ggmc-kit-stats .stat-value {
                font-weight: bold;
                color: #1E293B;
            }

            /* Stock Management */
            .ggmc-stock-management {
                background: #f6f7f7;
                border: 1px solid #c3c4c7;
                padding: 15px 20px;
                border-radius: 4px;
                margin-top: 15px;
            }
            .ggmc-stock-management h4 {
                margin: 0 0 10px 0;
                font-size: 13px;
            }
            .ggmc-stock-action {
                display: flex;
                gap: 10px;
                align-items: center;
                margin-bottom: 10px;
            }
            .ggmc-stock-warning {
                color: #dba617;
                font-size: 12px;
            }
        ';
    }

    /**
     * AJAX handler to apply default styles to all widgets
     */
    public function ajax_apply_all_defaults() {
        // Check nonce exists
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(['message' => 'Missing security token']);
            return;
        }

        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!wp_verify_nonce($_POST['nonce'], 'ggm_commerce_default_styles')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        try {
            // Enable defaults by deleting the "cleared" option
            // When ggm_commerce_defaults_cleared is false/not set, defaults are enabled
            delete_option('ggm_commerce_defaults_cleared');

            // Verify the option was actually deleted
            $saved_value = get_option('ggm_commerce_defaults_cleared', 'not_set');

            if ($saved_value !== 'not_set') {
                wp_send_json_error([
                    'message' => 'Failed to save setting. Please try again.',
                    'debug' => ['saved_value' => $saved_value]
                ]);
                return;
            }

            wp_send_json_success([
                'message' => 'Professional default styling enabled for NEW widgets.'
            ]);

        } catch (Exception $e) {
            wp_send_json_error(['message' => 'Error enabling defaults: ' . $e->getMessage()]);
        }
    }

    /**
     * Convert widget name to class name
     */
    private function get_widget_class_name($widget_name) {
        // Convert ggmc-product-name to GGM_Commerce_Widget_Product_Name
        $parts = explode('-', $widget_name);
        array_shift($parts); // Remove 'ggm-commerce'
        
        $class_parts = ['Elecommerce', 'Widget'];
        foreach ($parts as $part) {
            $class_parts[] = ucfirst($part);
        }
        
        return implode('_', $class_parts);
    }

    /**
     * AJAX handler to remove all default styles from widgets
     */
    public function ajax_remove_all_defaults() {
        // Check nonce exists
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(['message' => 'Missing security token']);
            return;
        }

        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!wp_verify_nonce($_POST['nonce'], 'ggm_commerce_default_styles')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        try {
            // Disable defaults by setting the "cleared" option to true
            // When ggm_commerce_defaults_cleared is true, defaults are disabled
            $result = update_option('ggm_commerce_defaults_cleared', true);

            // Verify the option was actually saved
            $saved_value = get_option('ggm_commerce_defaults_cleared', false);

            if ($saved_value !== true) {
                wp_send_json_error([
                    'message' => 'Failed to save setting. Please try again.',
                    'debug' => [
                        'update_result' => $result,
                        'saved_value' => $saved_value
                    ]
                ]);
                return;
            }

            wp_send_json_success([
                'message' => 'Default styling disabled for NEW widgets. They will now inherit from Site Settings.'
            ]);

        } catch (Exception $e) {
            wp_send_json_error(['message' => 'Error disabling defaults: ' . $e->getMessage()]);
        }
    }

    /**
     * AJAX handler to update floating comparison bar setting
     */
    public function ajax_update_floating_bar() {
        // Check nonce - properly sanitize input
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'ggm_commerce_floating_bar')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get the enabled parameter - check for both '1' string and truthy values
        $enabled = isset($_POST['enabled']) && ($_POST['enabled'] === '1' || $_POST['enabled'] === 'true' || $_POST['enabled'] === true) ? '1' : '0';

        // Get current widget controls and update floating bar setting
        $widget_controls = get_option('ggm_commerce_widget_controls', array());
        $widget_controls['show_floating_bar'] = $enabled;
        $update_result = update_option('ggm_commerce_widget_controls', $widget_controls);

        wp_send_json_success([
            'message' => $enabled === '1' ? 'Floating comparison bar enabled' : 'Floating comparison bar disabled',
            'enabled' => $enabled,
            'saved' => $update_result
        ]);
    }

    /**
     * AJAX handler to update widget prioritization setting
     */
    public function ajax_update_widgets_prioritized() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!wp_verify_nonce($_POST['nonce'], 'ggm_commerce_widgets_prioritized')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get the enabled parameter
        $enabled = isset($_POST['enabled']) && $_POST['enabled'] === '1' ? '1' : '0';

        // Get current widget controls and update prioritization setting
        $widget_controls = get_option('ggm_commerce_widget_controls', array());
        $widget_controls['widgets_prioritized'] = $enabled;
        update_option('ggm_commerce_widget_controls', $widget_controls);

        wp_send_json_success([
            'message' => $enabled === '1' ? 'Goose Commerce widgets will appear at the top of the Elementor panel' : 'Goose Commerce widgets will appear in normal alphabetical order',
            'enabled' => $enabled
        ]);
    }

    /**
     * AJAX handler to save comparison bar styling settings
     */
    public function ajax_save_compare_bar_styles() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ggm_commerce_compare_bar_styles')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get current widget controls
        $widget_controls = get_option('ggm_commerce_widget_controls', array());

        // Sanitize max products (integer 2-10)
        if (isset($_POST['comparison_max_products'])) {
            $widget_controls['comparison_max_products'] = min(10, max(2, absint($_POST['comparison_max_products'])));
        }

        // Sanitize and save color settings
        $color_fields = array(
            'compare_bar_bg_start',
            'compare_bar_bg_end',
            'compare_bar_text_color',
            'compare_bar_button_bg',
            'compare_bar_button_text',
        );

        foreach ($color_fields as $field) {
            if (isset($_POST[$field])) {
                $widget_controls[$field] = sanitize_hex_color($_POST[$field]);
            }
        }

        // Sanitize border radius (integer 0-50)
        if (isset($_POST['compare_bar_border_radius'])) {
            $widget_controls['compare_bar_border_radius'] = min(50, max(0, absint($_POST['compare_bar_border_radius'])));
        }

        // Sanitize comparison message text fields
        $comparison_message_fields = array(
            'msg_added_to_compare',
            'msg_removed_from_compare',
            'msg_max_compare',
        );

        foreach ($comparison_message_fields as $field) {
            if (isset($_POST[$field])) {
                $widget_controls[$field] = sanitize_text_field(wp_unslash($_POST[$field]));
            }
        }

        update_option('ggm_commerce_widget_controls', $widget_controls);

        wp_send_json_success([
            'message' => 'Product comparison settings saved successfully',
        ]);
    }

    /**
     * AJAX handler to save notification settings
     */
    public function ajax_save_notification_settings() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ggm_commerce_notification_settings')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get current widget controls
        $widget_controls = get_option('ggm_commerce_widget_controls', array());

        // Sanitize enabled toggle
        $widget_controls['notifications_enabled'] = isset($_POST['notifications_enabled']) && $_POST['notifications_enabled'] === '1' ? '1' : '0';

        // Sanitize position (whitelist)
        $valid_positions = array('top-right', 'top-left', 'bottom-right', 'bottom-left');
        if (isset($_POST['notifications_position']) && in_array($_POST['notifications_position'], $valid_positions, true)) {
            $widget_controls['notifications_position'] = sanitize_text_field($_POST['notifications_position']);
        }

        // Sanitize duration (integer 1000-10000 ms)
        if (isset($_POST['notifications_duration'])) {
            $widget_controls['notifications_duration'] = min(10000, max(1000, absint($_POST['notifications_duration'])));
        }

        // Sanitize color settings
        if (isset($_POST['notifications_bg_color'])) {
            $widget_controls['notifications_bg_color'] = sanitize_hex_color($_POST['notifications_bg_color']);
        }
        if (isset($_POST['notifications_text_color'])) {
            $widget_controls['notifications_text_color'] = sanitize_hex_color($_POST['notifications_text_color']);
        }

        // Sanitize border radius (integer 0-24)
        if (isset($_POST['notifications_border_radius'])) {
            $widget_controls['notifications_border_radius'] = min(24, max(0, absint($_POST['notifications_border_radius'])));
        }

        // Sanitize cart message text fields
        $cart_message_fields = array(
            'msg_added_to_cart',
            'msg_select_options',
            'msg_error',
        );

        foreach ($cart_message_fields as $field) {
            if (isset($_POST[$field])) {
                $widget_controls[$field] = sanitize_text_field(wp_unslash($_POST[$field]));
            }
        }

        update_option('ggm_commerce_widget_controls', $widget_controls);

        wp_send_json_success([
            'message' => 'Cart notification settings saved successfully',
        ]);
    }

    /**
     * AJAX handler to save notification message text
     */
    public function ajax_save_notification_messages() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ggm_commerce_notification_messages')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get current widget controls
        $widget_controls = get_option('ggm_commerce_widget_controls', array());

        // Sanitize and save message text fields
        $message_fields = array(
            'msg_added_to_cart',
            'msg_select_options',
            'msg_added_to_compare',
            'msg_removed_from_compare',
            'msg_max_compare',
            'msg_error',
        );

        foreach ($message_fields as $field) {
            if (isset($_POST[$field])) {
                // Allow empty values (will use defaults), sanitize text
                $widget_controls[$field] = sanitize_text_field(wp_unslash($_POST[$field]));
            }
        }

        update_option('ggm_commerce_widget_controls', $widget_controls);

        wp_send_json_success([
            'message' => 'Notification messages saved successfully',
        ]);
    }

    /**
     * AJAX handler to save wishlist settings
     */
    public function ajax_save_wishlist_settings() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ggm_commerce_wishlist_settings')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get current widget controls
        $widget_controls = get_option('ggm_commerce_widget_controls', array());

        // Sanitize max wishlists (integer 1-20)
        if (isset($_POST['wishlist_max_lists'])) {
            $widget_controls['wishlist_max_lists'] = min(20, max(1, absint($_POST['wishlist_max_lists'])));
        }

        // Sanitize sharing enabled toggle
        $widget_controls['wishlist_sharing_enabled'] = isset($_POST['wishlist_sharing_enabled']) && $_POST['wishlist_sharing_enabled'] === '1' ? '1' : '0';

        update_option('ggm_commerce_widget_controls', $widget_controls);

        wp_send_json_success([
            'message' => 'Wishlist settings saved successfully',
        ]);
    }

    /**
     * AJAX handler to update "Powered by Goose" branding setting
     */
    public function ajax_update_powered_by() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ggm_commerce_powered_by')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Verify unlimited license
        $license = GGM_Commerce_License::instance();
        if (!$license->is_license_valid() || $license->get_widget_limit() !== 0) {
            wp_send_json_error(['message' => 'Unlimited plan required to change branding settings']);
            return;
        }

        // Save setting
        $widget_controls = get_option('ggm_commerce_widget_controls', array());
        $widget_controls['powered_by_disabled'] = isset($_POST['disabled']) && $_POST['disabled'] === '1' ? '1' : '0';
        update_option('ggm_commerce_widget_controls', $widget_controls);

        wp_send_json_success([
            'message' => $widget_controls['powered_by_disabled'] === '1'
                ? '"Powered by Goose" footer hidden'
                : '"Powered by Goose" footer is now showing',
        ]);
    }

    /**
     * AJAX handler to toggle multiple billing addresses
     */
    public function ajax_toggle_multiple_billing() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!wp_verify_nonce($_POST['nonce'], 'ggm_commerce_address_settings')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get the enable parameter
        $enable = isset($_POST['enable']) && $_POST['enable'] === 'yes';

        // Update the option
        update_option('ggm_commerce_allow_multiple_billing', $enable);

        wp_send_json_success([
            'message' => $enable ? 'Multiple billing addresses enabled' : 'Multiple billing addresses disabled',
            'enabled' => $enable
        ]);
    }

    /**
     * AJAX handler to toggle multiple shipping addresses
     */
    public function ajax_toggle_multiple_shipping() {
        // Check nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!wp_verify_nonce($_POST['nonce'], 'ggm_commerce_address_settings')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        // Get the enable parameter
        $enable = isset($_POST['enable']) && $_POST['enable'] === 'yes';

        // Update the option
        update_option('ggm_commerce_allow_multiple_shipping', $enable);

        wp_send_json_success([
            'message' => $enable ? 'Multiple shipping addresses enabled' : 'Multiple shipping addresses disabled',
            'enabled' => $enable
        ]);
    }

    /**
     * Apply default styles to all instances of a widget type
     */
    private function apply_defaults_to_widget_instances($widget_class, $defaults) {
        global $wpdb;

        // Get the widget name
        if (class_exists($widget_class)) {
            $widget_instance = new $widget_class();
            $widget_name = $widget_instance->get_name();
        } else {
            return;
        }

        // Find all posts with Elementor data containing this widget
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $posts = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT post_id, meta_value FROM {$wpdb->postmeta}
                WHERE meta_key = '_elementor_data'
                AND meta_value LIKE %s",
                '%' . $widget_name . '%'
            )
        );

        foreach ($posts as $post) {
            $elementor_data = json_decode($post->meta_value, true);
            if ($elementor_data) {
                $updated_data = $this->update_widget_settings_recursive($elementor_data, $widget_name, $defaults);
                if ($updated_data !== $elementor_data) {
                    update_post_meta($post->post_id, '_elementor_data', wp_slash(wp_json_encode($updated_data)));

                    // Clear Elementor cache for this post
                    if (class_exists('\Elementor\Plugin')) {
                        \Elementor\Plugin::$instance->files_manager->clear_cache();
                    }
                }
            }
        }
    }

    /**
     * Remove default styles from all instances of a widget type
     */
    private function remove_defaults_from_widget_instances($widget_class) {
        global $wpdb;
        

        // Get the widget name
        if (class_exists($widget_class)) {
            $widget_instance = new $widget_class();
            $widget_name = $widget_instance->get_name();
            
            // Get the defaults to know which settings to remove
            if (method_exists($widget_class, 'get_static_default_styles')) {
                $defaults = $widget_class::get_static_default_styles();
            } else {
                return;
            }
        } else {
            return;
        }

        // Find all posts with Elementor data containing this widget
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $posts = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT post_id, meta_value FROM {$wpdb->postmeta}
                WHERE meta_key = '_elementor_data'
                AND meta_value LIKE %s",
                '%' . $widget_name . '%'
            )
        );

        foreach ($posts as $post) {
            $elementor_data = json_decode($post->meta_value, true);
            if ($elementor_data) {
                $updated_data = $this->remove_widget_settings_recursive($elementor_data, $widget_name, array_keys($defaults));
                if ($updated_data !== $elementor_data) {
                    update_post_meta($post->post_id, '_elementor_data', wp_slash(wp_json_encode($updated_data)));

                    // Clear Elementor cache for this post
                    if (class_exists('\Elementor\Plugin')) {
                        \Elementor\Plugin::$instance->files_manager->clear_cache();
                    }
                }
            }
        }
    }

    /**
     * Recursively update widget settings in Elementor data
     */
    private function update_widget_settings_recursive($data, $widget_name, $defaults) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if ($key === 'widgetType' && $value === $widget_name) {
                    // This is our widget, update its settings
                    if (isset($data['settings'])) {
                        $data['settings'] = array_merge($data['settings'], $defaults);
                    } else {
                        $data['settings'] = $defaults;
                    }
                } elseif (is_array($value)) {
                    $data[$key] = $this->update_widget_settings_recursive($value, $widget_name, $defaults);
                }
            }
        }
        return $data;
    }

    /**
     * Recursively remove widget settings from Elementor data
     */
    private function remove_widget_settings_recursive($data, $widget_name, $settings_to_remove) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if ($key === 'widgetType' && $value === $widget_name) {
                    // This is our widget, remove default settings
                    if (isset($data['settings'])) {
                        foreach ($settings_to_remove as $setting_key) {
                            unset($data['settings'][$setting_key]);
                        }
                    }
                } elseif (is_array($value)) {
                    $data[$key] = $this->remove_widget_settings_recursive($value, $widget_name, $settings_to_remove);
                }
            }
        }
        return $data;
    }

    /**
     * Categories management page
     */
    public function categories_page() {
        global $title, $wpdb;
        $title = 'Categories';

        $taxonomy = GGM_Commerce_Taxonomy::get_instance();

        // Handle form submissions
        $message = '';
        $message_type = '';

        if (isset($_POST['action'])) {
            check_admin_referer('ggmc_category_action');

            switch ($_POST['action']) {
                case 'add':
                    $result = $taxonomy->create_category($_POST);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Category added successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'edit':
                    $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;
                    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Data sanitized in update_category method
                    $result = $taxonomy->update_category($category_id, isset($_POST) ? wp_unslash($_POST) : []);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Category updated successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'delete':
                    $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;
                    $target_category_id = isset($_POST['target_category_id']) ? intval(wp_unslash($_POST['target_category_id'])) : null;
                    $result = $taxonomy->delete_category($category_id, $target_category_id);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        // Get the name of the target category for the message
                        $target_name = 'the default category';
                        if ($target_category_id) {
                            $target_cat = $taxonomy->get_category($target_category_id);
                            if ($target_cat) {
                                $target_name = esc_html($target_cat->name);
                            }
                        }
                        $message = 'Category deleted. Products moved to ' . $target_name . '.';
                        $message_type = 'success';
                    }
                    break;

                case 'bulk_remove':
                    $category_id = isset($_POST['category_id']) ? intval(wp_unslash($_POST['category_id'])) : 0;
                    $uncategorised = $taxonomy->get_uncategorised_category();

                    // Find products that ONLY have this category (need to add uncategorised)
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $products_only_this = $wpdb->get_col($wpdb->prepare(
                        "SELECT pc.product_id FROM {$wpdb->prefix}ggmc_product_categories pc
                         WHERE pc.category_id = %d
                         AND NOT EXISTS (
                             SELECT 1 FROM {$wpdb->prefix}ggmc_product_categories pc2
                             WHERE pc2.product_id = pc.product_id AND pc2.category_id != %d
                         )",
                        $category_id,
                        $category_id
                    ));

                    // Add uncategorised to products that will be orphaned
                    foreach ($products_only_this as $product_id) {
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                        $wpdb->insert(
                            "{$wpdb->prefix}ggmc_product_categories",
                            ['product_id' => $product_id, 'category_id' => $uncategorised->id],
                            ['%d', '%d']
                        );
                    }

                    // Delete all relationships for this category
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->delete(
                        "{$wpdb->prefix}ggmc_product_categories",
                        ['category_id' => $category_id],
                        ['%d']
                    );

                    $message = 'Category removed from all products. Products moved to Uncategorised.';
                    $message_type = 'success';
                    break;
            }
        }

        // Get editing category if specified
        $editing_category = null;
        if (isset($_GET['edit'])) {
            $editing_category = $taxonomy->get_category(intval($_GET['edit']));
        }

        $categories = $taxonomy->get_categories(['status' => null]);

        ?>
        <div class="wrap">
            <?php self::page_title( 'Product Categories' ); ?>
            <a href="#" class="page-title-action" onclick="document.getElementById('add-category-form').style.display='block'; return false;">Add New</a>
            <hr class="wp-header-end">

            <!-- Import/Export Section -->
            <div class="ggmc-import-export-section" style="margin: 15px 0; padding: 15px; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px;">
                <div style="display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap;">
                    <div class="ggmc-export-section">
                        <strong style="display: block; margin-bottom: 8px;">Export Categories</strong>
                        <button type="button" class="button ggmc-export-btn" data-type="categories" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                            <span class="dashicons dashicons-download" style="margin-top: 4px;"></span> Export CSV
                        </button>
                        <button type="button" class="button ggmc-template-btn" data-type="categories" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                            <span class="dashicons dashicons-media-spreadsheet" style="margin-top: 4px;"></span> Download Template
                        </button>
                    </div>
                    <div class="ggmc-import-section">
                        <strong style="display: block; margin-bottom: 8px;">Import Categories</strong>
                        <form id="ggmc-import-categories-form" enctype="multipart/form-data" style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                            <input type="file" name="file" accept=".csv" required style="max-width: 200px;">
                            <select name="duplicate_handling">
                                <option value="skip">Skip existing</option>
                                <option value="update">Update existing</option>
                                <option value="create">Create new</option>
                            </select>
                            <label style="display: flex; align-items: center; gap: 5px;">
                                <input type="checkbox" name="download_images" value="1"> Download images
                            </label>
                            <button type="submit" class="button button-primary ggmc-import-btn" data-type="categories" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                <span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import
                            </button>
                        </form>
                        <div class="ggmc-import-progress" style="display: none; margin-top: 10px;">
                            <div class="ggmc-progress-bar" style="background: #e0e0e0; height: 20px; border-radius: 4px; overflow: hidden;">
                                <div class="ggmc-progress-fill" style="background: #0073aa; height: 100%; width: 0%; transition: width 0.3s;"></div>
                            </div>
                            <div class="ggmc-progress-text" style="margin-top: 5px; font-size: 12px; color: #666;"></div>
                        </div>
                        <div class="ggmc-import-result" style="display: none; margin-top: 10px; padding: 10px; border-radius: 4px;"></div>
                    </div>
                </div>
            </div>

            <?php if ($message): ?>
                <div class="notice notice-<?php echo esc_attr($message_type); ?> is-dismissible">
                    <p><?php echo esc_html($message); ?></p>
                </div>
            <?php endif; ?>

            <!-- Add Category Form -->
            <div id="add-category-form" style="<?php echo $editing_category ? 'display:none;' : 'display:none;'; ?> background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccc;">
                <h2>Add New Category</h2>
                <form method="post" action="">
                    <?php wp_nonce_field('ggmc_category_action'); ?>
                    <input type="hidden" name="action" value="add">

                    <table class="form-table">
                        <tr>
                            <th><label for="name">Name *</label></th>
                            <td><input type="text" id="name" name="name" class="regular-text" required></td>
                        </tr>
                        <tr>
                            <th><label for="slug">Slug</label></th>
                            <td><input type="text" id="slug" name="slug" class="regular-text">
                                <p class="description">Leave empty to auto-generate from name.</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="description">Description</label></th>
                            <td><textarea id="description" name="description" rows="3" class="large-text"></textarea></td>
                        </tr>
                        <tr>
                            <th><label for="add_image_id">Category Image</label></th>
                            <td>
                                <div class="ggmc-image-upload-wrapper">
                                    <input type="hidden" id="add_image_id" name="image_id" value="">
                                    <div id="add_image_preview" class="ggmc-image-preview" style="margin-bottom: 10px;"></div>
                                    <button type="button" class="button ggmc-upload-image-btn" data-target="add_image_id" data-preview="add_image_preview">Select Image</button>
                                    <button type="button" class="button ggmc-remove-image-btn" data-target="add_image_id" data-preview="add_image_preview" style="display: none;">Remove Image</button>
                                </div>
                                <p class="description">Image displayed on category archive pages.</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="status">Status</label></th>
                            <td>
                                <select id="status" name="status">
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </td>
                        </tr>
                    </table>

                    <p class="submit">
                        <button type="submit" class="button button-primary">Add Category</button>
                        <button type="button" class="button" onclick="document.getElementById('add-category-form').style.display='none';">Cancel</button>
                    </p>
                </form>
            </div>

            <!-- Edit Category Form -->
            <?php if ($editing_category): ?>
            <?php
            $edit_image_id = isset($editing_category->image_id) ? intval($editing_category->image_id) : 0;
            $edit_image_url = $edit_image_id ? wp_get_attachment_image_url($edit_image_id, 'thumbnail') : '';
            ?>
            <div id="edit-category-form" style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccc;">
                <h2>Edit Category</h2>
                <form method="post" action="">
                    <?php wp_nonce_field('ggmc_category_action'); ?>
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="category_id" value="<?php echo esc_attr($editing_category->id); ?>">

                    <table class="form-table">
                        <tr>
                            <th><label for="edit_name">Name *</label></th>
                            <td><input type="text" id="edit_name" name="name" class="regular-text" value="<?php echo esc_attr($editing_category->name); ?>" required></td>
                        </tr>
                        <tr>
                            <th><label for="edit_slug">Slug</label></th>
                            <td><input type="text" id="edit_slug" name="slug" class="regular-text" value="<?php echo esc_attr($editing_category->slug); ?>"></td>
                        </tr>
                        <tr>
                            <th><label for="edit_description">Description</label></th>
                            <td><textarea id="edit_description" name="description" rows="3" class="large-text"><?php echo esc_textarea($editing_category->description); ?></textarea></td>
                        </tr>
                        <tr>
                            <th><label for="edit_image_id">Category Image</label></th>
                            <td>
                                <div class="ggmc-image-upload-wrapper">
                                    <input type="hidden" id="edit_image_id" name="image_id" value="<?php echo esc_attr($edit_image_id); ?>">
                                    <div id="edit_image_preview" class="ggmc-image-preview" style="margin-bottom: 10px;">
                                        <?php if ($edit_image_url): ?>
                                            <img src="<?php echo esc_url($edit_image_url); ?>" style="max-width: 150px; height: auto; border: 1px solid #ddd; border-radius: 4px;">
                                        <?php endif; ?>
                                    </div>
                                    <button type="button" class="button ggmc-upload-image-btn" data-target="edit_image_id" data-preview="edit_image_preview">Select Image</button>
                                    <button type="button" class="button ggmc-remove-image-btn" data-target="edit_image_id" data-preview="edit_image_preview" style="<?php echo $edit_image_id ? '' : 'display: none;'; ?>">Remove Image</button>
                                </div>
                                <p class="description">Image displayed on category archive pages.</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="edit_status">Status</label></th>
                            <td>
                                <select id="edit_status" name="status">
                                    <option value="active" <?php selected($editing_category->status, 'active'); ?>>Active</option>
                                    <option value="inactive" <?php selected($editing_category->status, 'inactive'); ?>>Inactive</option>
                                </select>
                            </td>
                        </tr>
                    </table>

                    <p class="submit">
                        <button type="submit" class="button button-primary">Update Category</button>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-categories')); ?>" class="button">Cancel</a>
                    </p>
                </form>
            </div>
            <?php endif; ?>

            <!-- Categories Bulk Actions -->
            <form id="ggmc-categories-bulk-form" method="post">
                <?php wp_nonce_field('ggmc_bulk_categories_action', 'ggmc_categories_bulk_nonce'); ?>
                <div class="tablenav top" style="margin-bottom: 10px;">
                    <div class="alignleft actions bulkactions">
                        <label for="bulk-action-selector-categories" class="screen-reader-text">Select bulk action</label>
                        <select name="bulk_action" id="bulk-action-selector-categories">
                            <option value="">Bulk Actions</option>
                            <option value="delete">Delete</option>
                        </select>
                        <button type="button" id="ggmc-apply-categories-bulk-action" class="button action">Apply</button>
                        <span id="ggmc-categories-selected-count" style="margin-left: 10px; color: #64748b;"></span>
                    </div>
                </div>

                <!-- Categories List -->
                <table class="wp-list-table widefat fixed striped" id="ggmc-categories-table">
                    <thead>
                        <tr>
                            <td id="cb" class="manage-column column-cb check-column" style="width: 2.5em;">
                                <input type="checkbox" id="cb-select-all-categories" title="Select All" />
                            </td>
                            <th style="width: 60px;">Image</th>
                            <th style="width: 16%;">Name</th>
                            <th style="width: 11%;">Slug</th>
                            <th style="width: 22%;">Description</th>
                            <th style="width: 7%;">Products</th>
                            <th style="width: 7%;">Status</th>
                            <th style="width: 14%;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($categories): ?>
                            <?php foreach ($categories as $category): ?>
                            <?php
                            // Count products via relationship table
                            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                            $product_count = $wpdb->get_var($wpdb->prepare(
                                "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_product_categories WHERE category_id = %d",
                                $category->id
                            ));
                            $is_uncategorised = ($category->slug === 'uncategorised');

                            // Check if default category is set (allows deleting uncategorised)
                            $catalog_options = get_option('ggm_commerce_catalog_options');
                            $default_category_id = isset($catalog_options['default_category']) ? intval($catalog_options['default_category']) : 0;
                            $has_default = $default_category_id > 0;
                            $is_default = ($default_category_id === intval($category->id)) || ($is_uncategorised && !$has_default);
                            $can_delete = !$is_uncategorised || $has_default;

                            // Get category image
                            $cat_image_id = isset($category->image_id) ? intval($category->image_id) : 0;
                            $cat_image_url = $cat_image_id ? wp_get_attachment_image_url($cat_image_id, 'thumbnail') : '';
                            ?>
                            <tr data-category-id="<?php echo esc_attr($category->id); ?>">
                                <th scope="row" class="check-column">
                                    <?php if ($can_delete): ?>
                                        <input type="checkbox" name="category_ids[]" value="<?php echo esc_attr($category->id); ?>" class="ggmc-bulk-checkbox" />
                                    <?php endif; ?>
                                </th>
                                <td>
                                    <?php if ($cat_image_url): ?>
                                        <img src="<?php echo esc_url($cat_image_url); ?>" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px;">
                                    <?php else: ?>
                                        <span style="display: inline-block; width: 40px; height: 40px; background: #f0f0f0; border-radius: 4px; line-height: 40px; text-align: center; color: #999; font-size: 18px;">—</span>
                                    <?php endif; ?>
                                </td>
                                <td><strong><?php echo esc_html($category->name); ?></strong></td>
                                <td><?php echo esc_html($category->slug); ?></td>
                                <td><?php echo esc_html(wp_trim_words($category->description, 10, '...')); ?></td>
                                <td><?php echo intval($product_count); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo esc_attr($category->status); ?>">
                                        <?php echo esc_html(ucfirst($category->status)); ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 5px; flex-wrap: wrap; align-items: center;">
                                        <?php if (!$is_uncategorised): ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-categories&edit=' . $category->id)); ?>" class="button button-small">Edit</a>
                                        <?php endif; ?>

                                        <?php if (!$is_default && !$is_uncategorised): ?>
                                            <button type="button" class="button button-small ggmc-set-default-btn" data-category-id="<?php echo esc_attr($category->id); ?>" title="Set as default category for new products">Set Default</button>
                                        <?php endif; ?>

                                        <?php if ($can_delete): ?>
                                            <form method="post" style="display:inline; margin: 0;" onsubmit="return confirm('Remove this category from all products? Products will be moved to the default category.');">
                                                <?php wp_nonce_field('ggmc_category_action'); ?>
                                                <input type="hidden" name="action" value="bulk_remove">
                                                <input type="hidden" name="category_id" value="<?php echo esc_attr($category->id); ?>">
                                                <button type="submit" class="button button-small" style="white-space: nowrap;">Remove from Products</button>
                                            </form>

                                            <button type="button" class="button button-small button-link-delete ggmc-delete-category-btn"
                                                data-category-id="<?php echo esc_attr($category->id); ?>"
                                                data-category-name="<?php echo esc_attr($category->name); ?>"
                                                data-product-count="<?php echo esc_attr($product_count); ?>">Delete</button>
                                        <?php elseif ($is_default): ?>
                                            <span class="ggmc-default-badge">Default</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="8">No categories found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </form><!-- End categories bulk form -->

            <!-- Delete Category Modal -->
            <div id="ggmc-delete-category-modal" class="ggmc-modal" style="display: none;">
                <div class="ggmc-modal-backdrop"></div>
                <div class="ggmc-modal-content">
                    <div class="ggmc-modal-header">
                        <h3>Delete Category</h3>
                        <button type="button" class="ggmc-modal-close">&times;</button>
                    </div>
                    <form method="post" id="ggmc-delete-category-form">
                        <?php wp_nonce_field('ggmc_category_action'); ?>
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="category_id" id="ggmc-delete-category-id" value="">

                        <div class="ggmc-modal-body">
                            <p class="ggmc-delete-warning">
                                <strong>Warning:</strong> You are about to permanently delete the category "<span id="ggmc-delete-category-name"></span>".
                            </p>
                            <p id="ggmc-delete-product-info" style="display: none;">
                                This category has <strong><span id="ggmc-delete-product-count"></span></strong> product(s). Products that only belong to this category will be moved to the selected category below.
                            </p>

                            <div class="ggmc-form-field">
                                <label for="ggmc-target-category">Move products to:</label>
                                <select name="target_category_id" id="ggmc-target-category" class="regular-text">
                                    <?php
                                    // Get default category ID for modal dropdown
                                    $modal_default_cat_id = isset($catalog_options['default_category']) ? intval($catalog_options['default_category']) : 0;

                                    foreach ($categories as $cat):
                                        $cat_is_default = ($modal_default_cat_id === intval($cat->id)) || ($cat->slug === 'uncategorised' && $modal_default_cat_id <= 0);
                                        $default_label = $cat_is_default ? ' (Default)' : '';
                                    ?>
                                        <option value="<?php echo esc_attr($cat->id); ?>"
                                            <?php selected($cat_is_default); ?>
                                            data-is-default="<?php echo $cat_is_default ? '1' : '0'; ?>">
                                            <?php echo esc_html($cat->name . $default_label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>

                        <div class="ggmc-modal-footer">
                            <button type="button" class="button ggmc-modal-cancel">Cancel</button>
                            <button type="submit" class="button button-primary button-link-delete">Delete Category</button>
                        </div>
                    </form>
                </div>
            </div>


            <script>
            jQuery(document).ready(function($) {
                // Media library integration for category image upload
                var mediaFrame;

                // Upload image button click
                $(document).on('click', '.ggmc-upload-image-btn', function(e) {
                    e.preventDefault();

                    var button = $(this);
                    var targetInput = $('#' + button.data('target'));
                    var previewDiv = $('#' + button.data('preview'));
                    var removeBtn = button.siblings('.ggmc-remove-image-btn');

                    // Create media frame if it doesn't exist
                    mediaFrame = wp.media({
                        title: 'Select Category Image',
                        button: {
                            text: 'Use this image'
                        },
                        multiple: false
                    });

                    // Handle image selection
                    mediaFrame.on('select', function() {
                        var attachment = mediaFrame.state().get('selection').first().toJSON();
                        targetInput.val(attachment.id);

                        // Show preview
                        var imgUrl = attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
                        previewDiv.html('<img src="' + imgUrl + '" style="max-width: 150px; height: auto; border: 1px solid #ddd; border-radius: 4px;">');

                        // Show remove button
                        removeBtn.show();
                    });

                    mediaFrame.open();
                });

                // Remove image button click
                $(document).on('click', '.ggmc-remove-image-btn', function(e) {
                    e.preventDefault();

                    var button = $(this);
                    var targetInput = $('#' + button.data('target'));
                    var previewDiv = $('#' + button.data('preview'));

                    targetInput.val('');
                    previewDiv.html('');
                    button.hide();
                });

                // Set default category button click
                $(document).on('click', '.ggmc-set-default-btn', function(e) {
                    e.preventDefault();

                    var button = $(this);
                    var categoryId = button.data('category-id');

                    button.prop('disabled', true).text('Setting...');

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'ggmc_set_default_category',
                            category_id: categoryId,
                            nonce: '<?php echo esc_js(wp_create_nonce('ggmc_set_default_category')); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                // Reload page to show updated default badge
                                location.reload();
                            } else {
                                alert('Error: ' + response.data.message);
                                button.prop('disabled', false).text('Set Default');
                            }
                        },
                        error: function() {
                            alert('Failed to set default category. Please try again.');
                            button.prop('disabled', false).html('<span class="dashicons dashicons-star-empty" style="font-size: 14px; line-height: 1.6; width: 14px; height: 14px;"></span> Set Default');
                        }
                    });
                });

                // Delete category modal functionality
                var $modal = $('#ggmc-delete-category-modal');
                var $form = $('#ggmc-delete-category-form');
                var $categorySelect = $('#ggmc-target-category');
                var currentCategoryId = null;

                // Open modal when delete button is clicked
                $(document).on('click', '.ggmc-delete-category-btn', function(e) {
                    e.preventDefault();

                    var $btn = $(this);
                    currentCategoryId = $btn.data('category-id');
                    var categoryName = $btn.data('category-name');
                    var productCount = parseInt($btn.data('product-count'), 10);

                    // Set the category ID in the hidden field
                    $('#ggmc-delete-category-id').val(currentCategoryId);

                    // Set the category name in the modal
                    $('#ggmc-delete-category-name').text(categoryName);

                    // Show/hide product info based on count
                    if (productCount > 0) {
                        $('#ggmc-delete-product-count').text(productCount);
                        $('#ggmc-delete-product-info').show();
                    } else {
                        $('#ggmc-delete-product-info').hide();
                    }

                    // Remove the category being deleted from the dropdown and select default
                    $categorySelect.find('option').show();
                    $categorySelect.find('option[value="' + currentCategoryId + '"]').hide();

                    // Select the default category (or first available if current is default)
                    var $defaultOption = $categorySelect.find('option[data-is-default="1"]:visible');
                    if ($defaultOption.length) {
                        $categorySelect.val($defaultOption.val());
                    } else {
                        // Select first visible option
                        $categorySelect.val($categorySelect.find('option:visible').first().val());
                    }

                    // Show the modal
                    $modal.show();
                });

                // Close modal functions
                function closeModal() {
                    $modal.hide();
                    currentCategoryId = null;
                }

                // Close on X button, Cancel button, or backdrop click
                $modal.on('click', '.ggmc-modal-close, .ggmc-modal-cancel', closeModal);
                $modal.on('click', '.ggmc-modal-backdrop', closeModal);

                // Close on Escape key
                $(document).on('keydown', function(e) {
                    if (e.key === 'Escape' && $modal.is(':visible')) {
                        closeModal();
                    }
                });

                // Prevent modal content clicks from closing
                $modal.on('click', '.ggmc-modal-content', function(e) {
                    e.stopPropagation();
                });
            });
            </script>
        </div>
        <?php
    }

    /**
     * Tags management page
     */
    public function tags_page() {
        global $title, $wpdb;
        $title = 'Tags';

        $taxonomy = GGM_Commerce_Taxonomy::get_instance();

        // Handle form submissions
        $message = '';
        $message_type = '';

        if (isset($_POST['action'])) {
            check_admin_referer('ggmc_tag_action');

            switch ($_POST['action']) {
                case 'add':
                    $result = $taxonomy->create_tag($_POST);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Tag added successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'edit':
                    $tag_id = isset($_POST['tag_id']) ? intval(wp_unslash($_POST['tag_id'])) : 0;
                    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Data sanitized in update_tag method
                    $result = $taxonomy->update_tag($tag_id, isset($_POST) ? wp_unslash($_POST) : []);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Tag updated successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'delete':
                    $tag_id = isset($_POST['tag_id']) ? intval(wp_unslash($_POST['tag_id'])) : 0;
                    $result = $taxonomy->delete_tag($tag_id);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Tag deleted and removed from all products.';
                        $message_type = 'success';
                    }
                    break;

                case 'bulk_remove':
                    $tag_id = isset($_POST['tag_id']) ? intval(wp_unslash($_POST['tag_id'])) : 0;

                    // Remove tag from all products via junction table
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->delete(
                        "{$wpdb->prefix}ggmc_product_tags",
                        ['tag_id' => $tag_id],
                        ['%d']
                    );

                    $message = 'Tag removed from all products (tag still exists).';
                    $message_type = 'success';
                    break;
            }
        }

        // Get editing tag if specified
        $editing_tag = null;
        if (isset($_GET['edit'])) {
            $editing_tag = $taxonomy->get_tag(intval($_GET['edit']));
        }

        $tags = $taxonomy->get_tags();

        ?>
        <div class="wrap">
            <?php self::page_title( 'Product Tags' ); ?>
            <a href="#" class="page-title-action" onclick="document.getElementById('add-tag-form').style.display='block'; return false;">Add New</a>
            <hr class="wp-header-end">

            <!-- Import/Export Section -->
            <div class="ggmc-import-export-section" style="margin: 15px 0; padding: 15px; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px;">
                <div style="display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap;">
                    <div class="ggmc-export-section">
                        <strong style="display: block; margin-bottom: 8px;">Export Tags</strong>
                        <button type="button" class="button ggmc-export-btn" data-type="tags" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                            <span class="dashicons dashicons-download" style="margin-top: 4px;"></span> Export CSV
                        </button>
                        <button type="button" class="button ggmc-template-btn" data-type="tags" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                            <span class="dashicons dashicons-media-spreadsheet" style="margin-top: 4px;"></span> Download Template
                        </button>
                    </div>
                    <div class="ggmc-import-section">
                        <strong style="display: block; margin-bottom: 8px;">Import Tags</strong>
                        <form id="ggmc-import-tags-form" enctype="multipart/form-data" style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                            <input type="file" name="file" accept=".csv" required style="max-width: 200px;">
                            <select name="duplicate_handling">
                                <option value="skip">Skip existing</option>
                                <option value="update">Update existing</option>
                                <option value="create">Create new</option>
                            </select>
                            <button type="submit" class="button button-primary ggmc-import-btn" data-type="tags" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                <span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import
                            </button>
                        </form>
                        <div class="ggmc-import-progress" style="display: none; margin-top: 10px;">
                            <div class="ggmc-progress-bar" style="background: #e0e0e0; height: 20px; border-radius: 4px; overflow: hidden;">
                                <div class="ggmc-progress-fill" style="background: #0073aa; height: 100%; width: 0%; transition: width 0.3s;"></div>
                            </div>
                            <div class="ggmc-progress-text" style="margin-top: 5px; font-size: 12px; color: #666;"></div>
                        </div>
                        <div class="ggmc-import-result" style="display: none; margin-top: 10px; padding: 10px; border-radius: 4px;"></div>
                    </div>
                </div>
            </div>

            <?php if ($message): ?>
                <div class="notice notice-<?php echo esc_attr($message_type); ?> is-dismissible">
                    <p><?php echo esc_html($message); ?></p>
                </div>
            <?php endif; ?>

            <!-- Add Tag Form -->
            <div id="add-tag-form" style="<?php echo $editing_tag ? 'display:none;' : 'display:none;'; ?> background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccc;">
                <h2>Add New Tag</h2>
                <form method="post" action="">
                    <?php wp_nonce_field('ggmc_tag_action'); ?>
                    <input type="hidden" name="action" value="add">

                    <table class="form-table">
                        <tr>
                            <th><label for="name">Name *</label></th>
                            <td><input type="text" id="name" name="name" class="regular-text" required></td>
                        </tr>
                        <tr>
                            <th><label for="slug">Slug</label></th>
                            <td><input type="text" id="slug" name="slug" class="regular-text">
                                <p class="description">Leave empty to auto-generate from name.</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="description">Description</label></th>
                            <td><textarea id="description" name="description" rows="3" class="large-text"></textarea></td>
                        </tr>
                        <tr>
                            <th><label for="status">Status</label></th>
                            <td>
                                <select id="status" name="status">
                                    <option value="active" selected>Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </td>
                        </tr>
                    </table>

                    <p class="submit">
                        <button type="submit" class="button button-primary">Add Tag</button>
                        <button type="button" class="button" onclick="document.getElementById('add-tag-form').style.display='none';">Cancel</button>
                    </p>
                </form>
            </div>

            <!-- Edit Tag Form -->
            <?php if ($editing_tag): ?>
            <div id="edit-tag-form" style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccc;">
                <h2>Edit Tag</h2>
                <form method="post" action="">
                    <?php wp_nonce_field('ggmc_tag_action'); ?>
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="tag_id" value="<?php echo esc_attr($editing_tag->id); ?>">

                    <table class="form-table">
                        <tr>
                            <th><label for="edit_name">Name *</label></th>
                            <td><input type="text" id="edit_name" name="name" class="regular-text" value="<?php echo esc_attr($editing_tag->name); ?>" required></td>
                        </tr>
                        <tr>
                            <th><label for="edit_slug">Slug</label></th>
                            <td><input type="text" id="edit_slug" name="slug" class="regular-text" value="<?php echo esc_attr($editing_tag->slug); ?>"></td>
                        </tr>
                        <tr>
                            <th><label for="edit_description">Description</label></th>
                            <td><textarea id="edit_description" name="description" rows="3" class="large-text"><?php echo esc_textarea($editing_tag->description); ?></textarea></td>
                        </tr>
                        <tr>
                            <th><label for="edit_status">Status</label></th>
                            <td>
                                <select id="edit_status" name="status">
                                    <option value="active" <?php selected($editing_tag->status ?? 'active', 'active'); ?>>Active</option>
                                    <option value="inactive" <?php selected($editing_tag->status ?? 'active', 'inactive'); ?>>Inactive</option>
                                </select>
                            </td>
                        </tr>
                    </table>

                    <p class="submit">
                        <button type="submit" class="button button-primary">Update Tag</button>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-tags')); ?>" class="button">Cancel</a>
                    </p>
                </form>
            </div>
            <?php endif; ?>

            <!-- Tags Bulk Actions -->
            <form id="ggmc-tags-bulk-form" method="post">
                <?php wp_nonce_field('ggmc_bulk_tags_action', 'ggmc_tags_bulk_nonce'); ?>
                <div class="tablenav top" style="margin-bottom: 10px;">
                    <div class="alignleft actions bulkactions">
                        <label for="bulk-action-selector-tags" class="screen-reader-text">Select bulk action</label>
                        <select name="bulk_action" id="bulk-action-selector-tags">
                            <option value="">Bulk Actions</option>
                            <option value="delete">Delete</option>
                        </select>
                        <button type="button" id="ggmc-apply-tags-bulk-action" class="button action">Apply</button>
                        <span id="ggmc-tags-selected-count" style="margin-left: 10px; color: #64748b;"></span>
                    </div>
                </div>

                <!-- Tags List -->
                <table class="wp-list-table widefat fixed striped" id="ggmc-tags-table">
                    <thead>
                        <tr>
                            <td id="cb" class="manage-column column-cb check-column" style="width: 2.5em;">
                                <input type="checkbox" id="cb-select-all-tags" title="Select All" />
                            </td>
                            <th style="width: 16%;">Name</th>
                            <th style="width: 11%;">Slug</th>
                            <th style="width: 23%;">Description</th>
                            <th style="width: 9%;">Status</th>
                            <th style="width: 9%;">Products</th>
                            <th style="width: 23%;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($tags): ?>
                            <?php foreach ($tags as $tag): ?>
                                <?php
                                // Count products with this tag via junction table
                                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                $product_count = $wpdb->get_var($wpdb->prepare(
                                    "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_product_tags WHERE tag_id = %d",
                                    $tag->id
                                ));
                                $tag_status = $tag->status ?? 'active';
                                ?>
                                <tr data-tag-id="<?php echo esc_attr($tag->id); ?>">
                                    <th scope="row" class="check-column">
                                        <input type="checkbox" name="tag_ids[]" value="<?php echo esc_attr($tag->id); ?>" class="ggmc-bulk-checkbox" />
                                    </th>
                                <td><strong><?php echo esc_html($tag->name); ?></strong></td>
                                <td><?php echo esc_html($tag->slug); ?></td>
                                <td><?php echo esc_html($tag->description); ?></td>
                                <td><span class="status-badge status-<?php echo esc_attr($tag_status); ?>"><?php echo esc_html(ucfirst($tag_status)); ?></span></td>
                                <td><?php echo intval($product_count); ?></td>
                                <td>
                                    <div style="display: flex; gap: 5px; flex-wrap: nowrap;">
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-tags&edit=' . $tag->id)); ?>" class="button button-small">Edit</a>

                                        <form method="post" style="display:inline; margin: 0;" onsubmit="return confirm('Remove this tag from all products? Tag will still exist.');">
                                            <?php wp_nonce_field('ggmc_tag_action'); ?>
                                            <input type="hidden" name="action" value="bulk_remove">
                                            <input type="hidden" name="tag_id" value="<?php echo esc_attr($tag->id); ?>">
                                            <button type="submit" class="button button-small" style="white-space: nowrap;">Remove from Products</button>
                                        </form>

                                        <form method="post" style="display:inline; margin: 0;" onsubmit="return confirm('Delete this tag permanently? It will be removed from all products.');">
                                            <?php wp_nonce_field('ggmc_tag_action'); ?>
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="tag_id" value="<?php echo esc_attr($tag->id); ?>">
                                            <button type="submit" class="button button-small button-link-delete">Delete</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="7">No tags found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            </form><!-- End tags bulk form -->

        </div>
        <?php
    }

    /**
     * Attributes management page (Premium Feature)
     */
    public function attributes_page() {
        global $title, $wpdb;
        $title = 'Attributes';

        $attributes_manager = GGM_Commerce_Attributes::get_instance();
        $license = GGM_Commerce_License::instance();
        $is_premium_active = $license->is_widget_activated('custom-attributes');

        // Handle form submissions
        $message = '';
        $message_type = '';

        // Determine current tab (attributes or groups)
        $current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'attributes';
        $current_group_id = isset($_GET['group']) ? intval($_GET['group']) : 0;
        $current_group = $current_group_id ? $attributes_manager->get_attribute_group($current_group_id) : null;

        // Handle preset import (separate nonce)
        if ($is_premium_active && isset($_POST['action']) && $_POST['action'] === 'import_preset') {
            check_admin_referer('ggmc_import_preset');

            $preset_key = isset($_POST['preset_key']) ? sanitize_text_field($_POST['preset_key']) : '';
            $presets = $this->get_attribute_presets();

            if (isset($presets[$preset_key])) {
                $preset = $presets[$preset_key];
                $created_attributes = 0;
                $created_attribute_ids = array();

                // First, create all attributes
                foreach ($preset['attributes'] as $index => $attr_data) {
                    // Prepare the icon in JSON format
                    $icon_json = '';
                    if (!empty($attr_data['icon'])) {
                        $icon_json = wp_json_encode(array(
                            'value'   => $attr_data['icon'],
                            'library' => 'fa-solid',
                        ));
                    }

                    // Prepare attribute data
                    // Options can be a string (comma-separated) or array
                    $options_value = '';
                    if (isset($attr_data['options'])) {
                        if (is_array($attr_data['options'])) {
                            $options_value = implode(',', $attr_data['options']);
                        } else {
                            $options_value = $attr_data['options']; // Already a string
                        }
                    }

                    $new_attr_data = array(
                        'name'           => $attr_data['name'],
                        'attribute_type' => $attr_data['type'] ?? 'text',
                        'unit'           => $attr_data['unit'] ?? '',
                        'icon'           => $icon_json,
                        'options'        => $options_value,
                        'display_order'  => $index,
                        'status'         => 'active',
                    );

                    $result = $attributes_manager->create_attribute($new_attr_data);
                    if (!is_wp_error($result)) {
                        $created_attributes++;
                        $created_attribute_ids[] = $result;
                    }
                }

                // Now create the group
                $group_data = array(
                    'name'        => $preset['name'],
                    'description' => $preset['description'] ?? '',
                    'status'      => 'active',
                );

                $group_id = $attributes_manager->create_attribute_group($group_data);

                if (!is_wp_error($group_id) && !empty($created_attribute_ids)) {
                    // Associate attributes with the group
                    $attributes_manager->set_group_attributes($group_id, $created_attribute_ids);

                    $message = sprintf(
                        'Successfully imported "%s" preset: %d attributes created and added to new group.',
                        esc_html($preset['name']),
                        $created_attributes
                    );
                    $message_type = 'success';
                } elseif (is_wp_error($group_id)) {
                    $message = 'Attributes created but failed to create group: ' . $group_id->get_error_message();
                    $message_type = 'warning';
                } else {
                    $message = 'Preset imported but no attributes were created.';
                    $message_type = 'warning';
                }
            } else {
                $message = 'Invalid preset selected.';
                $message_type = 'error';
            }
        }

        if ($is_premium_active && isset($_POST['action']) && $_POST['action'] !== 'import_preset') {
            check_admin_referer('ggmc_attribute_action');

            switch ($_POST['action']) {
                case 'add_attribute':
                    $result = $attributes_manager->create_attribute(wp_unslash($_POST));
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Attribute created successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'edit_attribute':
                    $attribute_id = isset($_POST['attribute_id']) ? intval(wp_unslash($_POST['attribute_id'])) : 0;
                    $result = $attributes_manager->update_attribute($attribute_id, wp_unslash($_POST));
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Attribute updated successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'delete_attribute':
                    $attribute_id = isset($_POST['attribute_id']) ? intval(wp_unslash($_POST['attribute_id'])) : 0;
                    $result = $attributes_manager->delete_attribute($attribute_id);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Attribute deleted successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'add_group':
                    $result = $attributes_manager->create_attribute_group(wp_unslash($_POST));
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        // Handle attribute assignments
                        $group_id = $result;
                        if (!empty($_POST['group_attributes']) && is_array($_POST['group_attributes'])) {
                            $attr_ids = array_map('intval', $_POST['group_attributes']);
                            $attributes_manager->set_group_attributes($group_id, $attr_ids);
                        }
                        $message = 'Attribute group created successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'edit_group':
                    $group_id = isset($_POST['group_id']) ? intval(wp_unslash($_POST['group_id'])) : 0;
                    $result = $attributes_manager->update_attribute_group($group_id, wp_unslash($_POST));
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        // Handle attribute assignments
                        $attr_ids = !empty($_POST['group_attributes']) && is_array($_POST['group_attributes'])
                            ? array_map('intval', $_POST['group_attributes'])
                            : array();
                        $attributes_manager->set_group_attributes($group_id, $attr_ids);
                        $message = 'Attribute group updated successfully.';
                        $message_type = 'success';
                    }
                    break;

                case 'delete_group':
                    $group_id = isset($_POST['group_id']) ? intval(wp_unslash($_POST['group_id'])) : 0;
                    // First remove attribute associations (don't delete the attributes themselves)
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->delete("{$wpdb->prefix}ggmc_attribute_group_members", array('group_id' => $group_id), array('%d'));
                    $result = $attributes_manager->delete_attribute_group($group_id);
                    if (is_wp_error($result)) {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    } else {
                        $message = 'Attribute group deleted. Attributes were preserved.';
                        $message_type = 'success';
                        if ($current_group_id === $group_id) {
                            echo '<script>window.location.href = "' . esc_url(admin_url('admin.php?page=ggmc-attributes&tab=groups')) . '";</script>';
                            return;
                        }
                    }
                    break;
            }
        }

        // Get editing items
        $editing_attribute = null;
        if (isset($_GET['edit_attribute'])) {
            $editing_attribute = $attributes_manager->get_attribute(intval($_GET['edit_attribute']));
        }

        $editing_group = null;
        if (isset($_GET['edit_group'])) {
            $editing_group = $attributes_manager->get_attribute_group(intval($_GET['edit_group']));
        }

        // Get all data
        $all_attributes = $attributes_manager->get_all_attributes(array('status' => null));
        $all_groups = $attributes_manager->get_attribute_groups(array('status' => null));
        $attribute_types = $attributes_manager->get_attribute_types();

        ?>
        <div class="wrap ggmc-attributes-wrap">
            <?php self::page_title( 'Product Attributes' ); ?>
            <hr class="wp-header-end">

            <?php if (!$is_premium_active): ?>
                <div class="notice notice-warning">
                    <p><strong>Premium Feature:</strong> Custom Attributes requires activation. Go to <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-settings&tab=premium-components')); ?>">Settings &gt; Premium Components</a> to activate this feature.</p>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="notice notice-<?php echo esc_attr($message_type); ?> is-dismissible">
                    <p><?php echo esc_html($message); ?></p>
                </div>
            <?php endif; ?>

            <!-- Tabs Navigation -->
            <nav class="nav-tab-wrapper wp-clearfix">
                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=attributes')); ?>" class="nav-tab <?php echo $current_tab === 'attributes' ? 'nav-tab-active' : ''; ?>">
                    Attributes
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=groups')); ?>" class="nav-tab <?php echo $current_tab === 'groups' ? 'nav-tab-active' : ''; ?>">
                    Groups
                </a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=presets')); ?>" class="nav-tab <?php echo $current_tab === 'presets' ? 'nav-tab-active' : ''; ?>">
                    Presets
                </a>
            </nav>

            <div class="tab-content">

            <?php if ($current_tab === 'attributes'): ?>
                <!-- ==================== ATTRIBUTES TAB ==================== -->
                <p class="description">Create attributes first (e.g., Weight, Height, Color). Then organize them into groups for quick product data entry.</p>

                <!-- Import/Export Section for Attributes -->
                <?php if ($is_premium_active): ?>
                <div class="ggmc-import-export-section" style="margin: 15px 0; padding: 15px; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px;">
                    <div style="display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap;">
                        <div class="ggmc-export-section">
                            <strong style="display: block; margin-bottom: 8px;">Export Attributes</strong>
                            <button type="button" class="button ggmc-export-btn" data-type="attributes" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                <span class="dashicons dashicons-download" style="margin-top: 4px;"></span> Export CSV
                            </button>
                            <button type="button" class="button ggmc-template-btn" data-type="attributes" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                <span class="dashicons dashicons-media-spreadsheet" style="margin-top: 4px;"></span> Download Template
                            </button>
                        </div>
                        <div class="ggmc-import-section">
                            <strong style="display: block; margin-bottom: 8px;">Import Attributes</strong>
                            <form id="ggmc-import-attributes-form" enctype="multipart/form-data" style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                                <input type="file" name="file" accept=".csv" required style="max-width: 200px;">
                                <select name="duplicate_handling">
                                    <option value="skip">Skip existing</option>
                                    <option value="update">Update existing</option>
                                    <option value="create">Create new</option>
                                </select>
                                <label style="display: flex; align-items: center; gap: 5px;">
                                    <input type="checkbox" name="create_groups" value="1" checked> Auto-create groups
                                </label>
                                <button type="submit" class="button button-primary ggmc-import-btn" data-type="attributes" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                    <span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import
                                </button>
                            </form>
                            <div class="ggmc-import-progress" style="display: none; margin-top: 10px;">
                                <div class="ggmc-progress-bar" style="background: #e0e0e0; height: 20px; border-radius: 4px; overflow: hidden;">
                                    <div class="ggmc-progress-fill" style="background: #0073aa; height: 100%; width: 0%; transition: width 0.3s;"></div>
                                </div>
                                <div class="ggmc-progress-text" style="margin-top: 5px; font-size: 12px; color: #666;"></div>
                            </div>
                            <div class="ggmc-import-result" style="display: none; margin-top: 10px; padding: 10px; border-radius: 4px;"></div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($is_premium_active): ?>
                    <!-- Add Attribute Button -->
                    <p>
                        <a href="#" class="button button-primary" onclick="document.getElementById('add-attribute-form').style.display='block'; this.style.display='none'; return false;">
                            <span class="dashicons dashicons-plus-alt2" style="vertical-align: middle; margin-top: -2px;"></span> Add New Attribute
                        </a>
                    </p>

                    <!-- Add Attribute Form -->
                    <div id="add-attribute-form" style="display:none; background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4; border-radius: 4px;">
                        <h2 style="margin-top: 0;">Add New Attribute</h2>
                        <form method="post" action="">
                            <?php wp_nonce_field('ggmc_attribute_action'); ?>
                            <input type="hidden" name="action" value="add_attribute">

                            <table class="form-table">
                                <tr>
                                    <th><label for="attr_name">Attribute Name *</label></th>
                                    <td><input type="text" id="attr_name" name="name" class="regular-text" required placeholder="e.g., Weight, Energy Rating, Color"></td>
                                </tr>
                                <tr>
                                    <th><label for="attr_type">Data Type</label></th>
                                    <td>
                                        <select id="attr_type" name="attribute_type" onchange="ggmcToggleOptionsField(this)">
                                            <?php foreach ($attribute_types as $type_key => $type_label): ?>
                                                <option value="<?php echo esc_attr($type_key); ?>"><?php echo esc_html($type_label); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">Text for free-form input, Number for numeric values, Dropdown for predefined options.</p>
                                    </td>
                                </tr>
                                <tr class="ggmc-options-row" style="display:none;">
                                    <th><label for="attr_options">Dropdown Options</label></th>
                                    <td>
                                        <input type="text" id="attr_options" name="options" class="large-text" placeholder="Option 1, Option 2, Option 3">
                                        <p class="description">Comma-separated list of options (e.g., Red, Green, Blue or A, A+, A++, A+++)</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="attr_unit">Unit Suffix</label></th>
                                    <td>
                                        <input type="text" id="attr_unit" name="unit" class="small-text" placeholder="kg">
                                        <p class="description">Optional unit displayed after the value (e.g., kg, cm, dB, W)</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="attr_icon">Icon</label></th>
                                    <td>
                                        <div class="ggmc-icon-picker-wrapper">
                                            <span class="ggmc-icon-preview" id="attr_icon_preview">
                                                <span class="dashicons dashicons-image-rotate"></span>
                                            </span>
                                            <button type="button" class="ggmc-icon-picker-trigger">
                                                <span class="dashicons dashicons-admin-customizer"></span>
                                                Select Icon
                                            </button>
                                            <input type="hidden" id="attr_icon" name="icon" class="ggmc-icon-value">
                                        </div>
                                        <p class="description">Click to choose from Font Awesome icons or upload a custom SVG.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="attr_filterable">Filterable</label></th>
                                    <td>
                                        <label class="ggmc-toggle-switch">
                                            <input type="checkbox" id="attr_filterable" name="filterable" value="1">
                                            <span class="ggmc-toggle-slider"></span>
                                        </label>
                                        <p class="description">Allow this attribute to be used in product filter widgets.</p>
                                    </td>
                                </tr>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary">Create Attribute</button>
                                <button type="button" class="button" onclick="document.getElementById('add-attribute-form').style.display='none'; document.querySelector('a[onclick*=add-attribute-form]').style.display='';">Cancel</button>
                            </p>
                        </form>
                    </div>

                    <!-- Edit Attribute Form -->
                    <?php if ($editing_attribute): ?>
                    <div id="edit-attribute-form" style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4; border-radius: 4px;">
                        <h2 style="margin-top: 0;">Edit Attribute</h2>
                        <form method="post" action="">
                            <?php wp_nonce_field('ggmc_attribute_action'); ?>
                            <input type="hidden" name="action" value="edit_attribute">
                            <input type="hidden" name="attribute_id" value="<?php echo esc_attr($editing_attribute->id); ?>">

                            <table class="form-table">
                                <tr>
                                    <th><label for="edit_attr_name">Attribute Name *</label></th>
                                    <td><input type="text" id="edit_attr_name" name="name" class="regular-text" value="<?php echo esc_attr($editing_attribute->name); ?>" required></td>
                                </tr>
                                <tr>
                                    <th><label for="edit_attr_type">Data Type</label></th>
                                    <td>
                                        <select id="edit_attr_type" name="attribute_type" onchange="ggmcToggleOptionsField(this, 'edit')">
                                            <?php foreach ($attribute_types as $type_key => $type_label): ?>
                                                <option value="<?php echo esc_attr($type_key); ?>" <?php selected($editing_attribute->attribute_type, $type_key); ?>><?php echo esc_html($type_label); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                </tr>
                                <tr class="ggmc-options-row-edit" style="<?php echo $editing_attribute->attribute_type === 'select' ? '' : 'display:none;'; ?>">
                                    <th><label for="edit_attr_options">Dropdown Options</label></th>
                                    <td>
                                        <?php
                                        $options_value = '';
                                        if (!empty($editing_attribute->options)) {
                                            $options_array = json_decode($editing_attribute->options, true);
                                            if (is_array($options_array)) {
                                                $options_value = implode(', ', $options_array);
                                            }
                                        }
                                        ?>
                                        <input type="text" id="edit_attr_options" name="options" class="large-text" value="<?php echo esc_attr($options_value); ?>">
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="edit_attr_unit">Unit Suffix</label></th>
                                    <td><input type="text" id="edit_attr_unit" name="unit" class="small-text" value="<?php echo esc_attr($editing_attribute->unit); ?>"></td>
                                </tr>
                                <tr>
                                    <th><label for="edit_attr_icon">Icon</label></th>
                                    <td>
                                        <?php
                                        $current_icon = $editing_attribute->icon ?? '';
                                        // The current icon is stored as JSON or legacy class string.
                                        $icon_preview_html = '<span class="dashicons dashicons-image-rotate"></span>';
                                        if (!empty($current_icon)) {
                                            $decoded = json_decode($current_icon, true);
                                            if (is_array($decoded) && !empty($decoded['value'])) {
                                                if (!empty($decoded['library']) && $decoded['library'] === 'svg') {
                                                    $icon_preview_html = '<img src="' . esc_url($decoded['value']) . '" alt="Icon">';
                                                } else {
                                                    $icon_preview_html = '<i class="' . esc_attr($decoded['value']) . '"></i>';
                                                }
                                            } elseif (!is_array($decoded) && !empty($current_icon)) {
                                                // Legacy format - plain class string.
                                                $icon_preview_html = '<i class="' . esc_attr($current_icon) . '"></i>';
                                            }
                                        }
                                        ?>
                                        <div class="ggmc-icon-picker-wrapper">
                                            <span class="ggmc-icon-preview" id="edit_attr_icon_preview">
                                                <?php echo $icon_preview_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is escaped above ?>
                                            </span>
                                            <button type="button" class="ggmc-icon-picker-trigger">
                                                <span class="dashicons dashicons-admin-customizer"></span>
                                                Select Icon
                                            </button>
                                            <input type="hidden" id="edit_attr_icon" name="icon" class="ggmc-icon-value" value="<?php echo esc_attr($current_icon); ?>">
                                        </div>
                                        <p class="description">Click to choose from Font Awesome icons or upload a custom SVG.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="edit_attr_filterable">Filterable</label></th>
                                    <td>
                                        <label class="ggmc-toggle-switch">
                                            <input type="checkbox" id="edit_attr_filterable" name="filterable" value="1" <?php checked(!empty($editing_attribute->filterable), true); ?>>
                                            <span class="ggmc-toggle-slider"></span>
                                        </label>
                                        <p class="description">Allow this attribute to be used in product filter widgets.</p>
                                    </td>
                                </tr>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary">Update Attribute</button>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=attributes')); ?>" class="button">Cancel</a>
                            </p>
                        </form>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>

                <!-- Attributes Bulk Actions -->
                <?php if ($is_premium_active): ?>
                <form id="ggmc-attributes-bulk-form" method="post">
                    <?php wp_nonce_field('ggmc_bulk_attributes_action', 'ggmc_attrs_bulk_nonce'); ?>
                    <div class="tablenav top" style="margin-bottom: 10px;">
                        <div class="alignleft actions bulkactions">
                            <label for="bulk-action-selector-attrs" class="screen-reader-text">Select bulk action</label>
                            <select name="bulk_action" id="bulk-action-selector-attrs">
                                <option value="">Bulk Actions</option>
                                <option value="set_filterable">Set Filterable</option>
                                <option value="set_not_filterable">Set Not Filterable</option>
                                <option value="delete">Delete</option>
                            </select>
                            <button type="button" id="ggmc-apply-attrs-bulk-action" class="button action">Apply</button>
                            <span id="ggmc-attrs-selected-count" style="margin-left: 10px; color: #64748b;"></span>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Attributes List -->
                <table class="wp-list-table widefat fixed striped" id="ggmc-attributes-table">
                    <thead>
                        <tr>
                            <?php if ($is_premium_active): ?>
                            <td id="cb" class="manage-column column-cb check-column" style="width: 2.5em;">
                                <input type="checkbox" id="cb-select-all-attrs" title="Select All" />
                            </td>
                            <?php endif; ?>
                            <th style="width: 18%;">Attribute Name</th>
                            <th style="width: 10%;">Type</th>
                            <th style="width: 6%;">Unit</th>
                            <th style="width: 8%;">Icon</th>
                            <th style="width: 18%;">Options / Groups</th>
                            <th style="width: 9%;">Filterable</th>
                            <th style="width: 22%;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($all_attributes): ?>
                            <?php foreach ($all_attributes as $attr): ?>
                                <?php
                                $options_display = '';
                                if (!empty($attr->options)) {
                                    $opts = json_decode($attr->options, true);
                                    if (is_array($opts)) {
                                        $options_display = implode(', ', $opts);
                                    }
                                }
                                // Get groups this attribute belongs to
                                $attr_groups = $attributes_manager->get_attribute_groups_for_attribute($attr->id);
                                $groups_display = !empty($attr_groups) ? implode(', ', array_column($attr_groups, 'name')) : '<em>Not in any group</em>';
                                ?>
                                <tr data-attribute-id="<?php echo esc_attr($attr->id); ?>">
                                    <?php if ($is_premium_active): ?>
                                    <th scope="row" class="check-column">
                                        <input type="checkbox" name="attribute_ids[]" value="<?php echo esc_attr($attr->id); ?>" class="ggmc-bulk-checkbox" />
                                    </th>
                                    <?php endif; ?>
                                    <td><strong><?php echo esc_html($attr->name); ?></strong></td>
                                    <td><?php echo esc_html($attribute_types[$attr->attribute_type] ?? $attr->attribute_type); ?></td>
                                    <td><?php echo esc_html($attr->unit ?: '-'); ?></td>
                                    <td>
                                        <?php
                                        $icon_display = '';
                                        if (!empty($attr->icon)) {
                                            // Try to parse as JSON (new format).
                                            $decoded = json_decode($attr->icon, true);
                                            $icon_display = is_array($decoded) ? ($decoded['value'] ?? '') : $attr->icon;
                                        }
                                        if (!empty($icon_display)):
                                        ?>
                                            <i class="<?php echo esc_attr($icon_display); ?>" title="<?php echo esc_attr($icon_display); ?>"></i>
                                            <code style="font-size: 10px; margin-left: 4px;"><?php echo esc_html($icon_display); ?></code>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($attr->attribute_type === 'select' && $options_display): ?>
                                            <strong>Options:</strong> <?php echo esc_html($options_display); ?><br>
                                        <?php endif; ?>
                                        <strong>Groups:</strong> <?php echo wp_kses_post( $groups_display ); ?>
                                    </td>
                                    <td class="ggmc-filterable-column">
                                        <?php if ($is_premium_active): ?>
                                        <label class="ggmc-toggle-switch">
                                            <input type="checkbox" class="ggmc-filterable-toggle"
                                                   data-attribute-id="<?php echo esc_attr($attr->id); ?>"
                                                   <?php checked(!empty($attr->filterable), true); ?>>
                                            <span class="ggmc-toggle-slider"></span>
                                        </label>
                                        <?php else: ?>
                                        <span class="description">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($is_premium_active): ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=attributes&edit_attribute=' . $attr->id)); ?>" class="button button-small">Edit</a>
                                            <form method="post" style="display:inline;" onsubmit="return confirm('Delete this attribute? This will also remove it from all groups and products.');">
                                                <?php wp_nonce_field('ggmc_attribute_action'); ?>
                                                <input type="hidden" name="action" value="delete_attribute">
                                                <input type="hidden" name="attribute_id" value="<?php echo esc_attr($attr->id); ?>">
                                                <button type="submit" class="button button-small button-link-delete">Delete</button>
                                            </form>
                                        <?php else: ?>
                                            <span class="description">Premium required</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="<?php echo $is_premium_active ? '7' : '6'; ?>">No attributes created yet. <?php if ($is_premium_active): ?>Click "Add New Attribute" to create your first one.<?php endif; ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php if ($is_premium_active): ?>
                </form><!-- End attributes bulk form -->
                <?php endif; ?>

            <?php elseif ($current_tab === 'groups'): ?>
                <!-- ==================== GROUPS TAB ==================== -->
                <p class="description">Groups are collections of attributes. When adding attributes to a product, you can select a group to add all its attributes at once. An attribute can belong to multiple groups.</p>

                <!-- Import/Export Section for Attribute Groups -->
                <?php if ($is_premium_active): ?>
                <div class="ggmc-import-export-section" style="margin: 15px 0; padding: 15px; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px;">
                    <div style="display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap;">
                        <div class="ggmc-export-section">
                            <strong style="display: block; margin-bottom: 8px;">Export Attribute Groups</strong>
                            <button type="button" class="button ggmc-export-btn" data-type="attribute_groups" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                <span class="dashicons dashicons-download" style="margin-top: 4px;"></span> Export CSV
                            </button>
                            <button type="button" class="button ggmc-template-btn" data-type="attribute_groups" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                <span class="dashicons dashicons-media-spreadsheet" style="margin-top: 4px;"></span> Download Template
                            </button>
                        </div>
                        <div class="ggmc-import-section">
                            <strong style="display: block; margin-bottom: 8px;">Import Attribute Groups</strong>
                            <form id="ggmc-import-attribute-groups-form" enctype="multipart/form-data" style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                                <input type="file" name="file" accept=".csv" required style="max-width: 200px;">
                                <select name="duplicate_handling">
                                    <option value="skip">Skip existing</option>
                                    <option value="update">Update existing</option>
                                    <option value="create">Create new</option>
                                </select>
                                <button type="submit" class="button button-primary ggmc-import-btn" data-type="groups" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                                    <span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import
                                </button>
                            </form>
                            <div class="ggmc-import-progress" style="display: none; margin-top: 10px;">
                                <div class="ggmc-progress-bar" style="background: #e0e0e0; height: 20px; border-radius: 4px; overflow: hidden;">
                                    <div class="ggmc-progress-fill" style="background: #0073aa; height: 100%; width: 0%; transition: width 0.3s;"></div>
                                </div>
                                <div class="ggmc-progress-text" style="margin-top: 5px; font-size: 12px; color: #666;"></div>
                            </div>
                            <div class="ggmc-import-result" style="display: none; margin-top: 10px; padding: 10px; border-radius: 4px;"></div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($is_premium_active): ?>
                    <!-- Add Group Button -->
                    <p>
                        <a href="#" class="button button-primary" onclick="document.getElementById('add-group-form').style.display='block'; this.style.display='none'; return false;">
                            <span class="dashicons dashicons-plus-alt2" style="vertical-align: middle; margin-top: -2px;"></span> Add New Group
                        </a>
                    </p>

                    <!-- Add Group Form -->
                    <div id="add-group-form" style="display:none; background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4; border-radius: 4px;">
                        <h2 style="margin-top: 0;">Add New Group</h2>
                        <form method="post" action="">
                            <?php wp_nonce_field('ggmc_attribute_action'); ?>
                            <input type="hidden" name="action" value="add_group">

                            <table class="form-table">
                                <tr>
                                    <th><label for="group_name">Group Name *</label></th>
                                    <td><input type="text" id="group_name" name="name" class="regular-text" required placeholder="e.g., Dimensions, Electrical, Appliance Specs"></td>
                                </tr>
                                <tr>
                                    <th><label for="group_description">Description</label></th>
                                    <td><textarea id="group_description" name="description" rows="2" class="large-text" placeholder="What types of products use this group?"></textarea></td>
                                </tr>
                                <tr>
                                    <th><label>Include Attributes</label></th>
                                    <td>
                                        <?php if ($all_attributes): ?>
                                            <div style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; background: #f9f9f9;">
                                                <?php foreach ($all_attributes as $attr): ?>
                                                    <label style="display: block; margin-bottom: 5px;">
                                                        <input type="checkbox" name="group_attributes[]" value="<?php echo esc_attr($attr->id); ?>">
                                                        <?php echo esc_html($attr->name); ?>
                                                        <span style="color: #666;">(<?php echo esc_html($attribute_types[$attr->attribute_type] ?? $attr->attribute_type); ?><?php echo $attr->unit ? ', ' . esc_html($attr->unit) : ''; ?>)</span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            <p class="description">No attributes available. <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=attributes')); ?>">Create attributes first</a>.</p>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary">Create Group</button>
                                <button type="button" class="button" onclick="document.getElementById('add-group-form').style.display='none'; document.querySelector('a[onclick*=add-group-form]').style.display='';">Cancel</button>
                            </p>
                        </form>
                    </div>

                    <!-- Edit Group Form -->
                    <?php if ($editing_group): ?>
                    <?php $group_attr_ids = array_column($attributes_manager->get_group_attributes($editing_group->id, array('status' => null)), 'id'); ?>
                    <div id="edit-group-form" style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4; border-radius: 4px;">
                        <h2 style="margin-top: 0;">Edit Group: <?php echo esc_html($editing_group->name); ?></h2>
                        <form method="post" action="">
                            <?php wp_nonce_field('ggmc_attribute_action'); ?>
                            <input type="hidden" name="action" value="edit_group">
                            <input type="hidden" name="group_id" value="<?php echo esc_attr($editing_group->id); ?>">

                            <table class="form-table">
                                <tr>
                                    <th><label for="edit_group_name">Group Name *</label></th>
                                    <td><input type="text" id="edit_group_name" name="name" class="regular-text" value="<?php echo esc_attr($editing_group->name); ?>" required></td>
                                </tr>
                                <tr>
                                    <th><label for="edit_group_description">Description</label></th>
                                    <td><textarea id="edit_group_description" name="description" rows="2" class="large-text"><?php echo esc_textarea($editing_group->description); ?></textarea></td>
                                </tr>
                                <tr>
                                    <th><label>Include Attributes</label></th>
                                    <td>
                                        <?php if ($all_attributes): ?>
                                            <div style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; background: #f9f9f9;">
                                                <?php foreach ($all_attributes as $attr): ?>
                                                    <label style="display: block; margin-bottom: 5px;">
                                                        <input type="checkbox" name="group_attributes[]" value="<?php echo esc_attr($attr->id); ?>" <?php checked(in_array($attr->id, $group_attr_ids)); ?>>
                                                        <?php echo esc_html($attr->name); ?>
                                                        <span style="color: #666;">(<?php echo esc_html($attribute_types[$attr->attribute_type] ?? $attr->attribute_type); ?><?php echo $attr->unit ? ', ' . esc_html($attr->unit) : ''; ?>)</span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else: ?>
                                            <p class="description">No attributes available.</p>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary">Update Group</button>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=groups')); ?>" class="button">Cancel</a>
                            </p>
                        </form>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>

                <!-- Groups Bulk Actions -->
                <?php if ($is_premium_active): ?>
                <form id="ggmc-attribute-groups-bulk-form" method="post">
                    <?php wp_nonce_field('ggmc_bulk_attributes_action', 'ggmc_attr_groups_bulk_nonce'); ?>
                    <div class="tablenav top" style="margin-bottom: 10px;">
                        <div class="alignleft actions bulkactions">
                            <label for="bulk-action-selector-attr-groups" class="screen-reader-text">Select bulk action</label>
                            <select name="bulk_action" id="bulk-action-selector-attr-groups">
                                <option value="">Bulk Actions</option>
                                <option value="delete">Delete</option>
                            </select>
                            <button type="button" id="ggmc-apply-attr-groups-bulk-action" class="button action">Apply</button>
                            <span id="ggmc-attr-groups-selected-count" style="margin-left: 10px; color: #64748b;"></span>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Groups List -->
                <table class="wp-list-table widefat fixed striped" id="ggmc-attribute-groups-table">
                    <thead>
                        <tr>
                            <?php if ($is_premium_active): ?>
                            <td id="cb" class="manage-column column-cb check-column" style="width: 2.5em;">
                                <input type="checkbox" id="cb-select-all-attr-groups" title="Select All" />
                            </td>
                            <?php endif; ?>
                            <th style="width: 23%;">Group Name</th>
                            <th style="width: 23%;">Description</th>
                            <th style="width: 28%;">Attributes</th>
                            <th style="width: 18%;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($all_groups): ?>
                            <?php foreach ($all_groups as $group): ?>
                                <?php
                                $group_attrs = $attributes_manager->get_group_attributes($group->id, array('status' => null));
                                $attrs_display = !empty($group_attrs) ? implode(', ', array_column($group_attrs, 'name')) : '';
                                ?>
                                <tr data-group-id="<?php echo esc_attr($group->id); ?>">
                                    <?php if ($is_premium_active): ?>
                                    <th scope="row" class="check-column">
                                        <input type="checkbox" name="attribute_ids[]" value="<?php echo esc_attr($group->id); ?>" class="ggmc-bulk-checkbox" />
                                    </th>
                                    <?php endif; ?>
                                    <td><strong><?php echo esc_html($group->name); ?></strong></td>
                                    <td><?php echo esc_html($group->description ?: '-'); ?></td>
                                    <td><?php echo $attrs_display ? esc_html($attrs_display) : '<em>No attributes</em>'; ?> <span class="description">(<?php echo esc_html(count($group_attrs)); ?>)</span></td>
                                    <td>
                                        <?php if ($is_premium_active): ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-attributes&tab=groups&edit_group=' . $group->id)); ?>" class="button button-small">Edit</a>
                                            <form method="post" style="display:inline;" onsubmit="return confirm('Delete this group? The attributes will be preserved, only the group will be removed.');">
                                                <?php wp_nonce_field('ggmc_attribute_action'); ?>
                                                <input type="hidden" name="action" value="delete_group">
                                                <input type="hidden" name="group_id" value="<?php echo esc_attr($group->id); ?>">
                                                <button type="submit" class="button button-small button-link-delete">Delete</button>
                                            </form>
                                        <?php else: ?>
                                            <span class="description">Premium required</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="<?php echo $is_premium_active ? '5' : '4'; ?>">No groups created yet. <?php if ($is_premium_active): ?>Click "Add New Group" to create one.<?php endif; ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <?php if ($is_premium_active): ?>
                </form><!-- End attribute groups bulk form -->
                <?php endif; ?>

            <?php elseif ($current_tab === 'presets'): ?>
                <!-- ==================== PRESETS TAB ==================== -->
                <?php $this->render_attributes_presets_tab($is_premium_active); ?>

            <?php endif; ?>

            </div><!-- .tab-content -->

            <script>
            function ggmcToggleOptionsField(selectEl, prefix) {
                prefix = prefix || '';
                var rowClass = prefix ? '.ggmc-options-row-' + prefix : '.ggmc-options-row';
                var rows = document.querySelectorAll(rowClass);
                rows.forEach(function(row) {
                    row.style.display = selectEl.value === 'select' ? '' : 'none';
                });
            }

            // Filterable toggle handler
            jQuery(document).ready(function($) {
                $('.ggmc-filterable-toggle').on('change', function() {
                    var $checkbox = $(this);
                    var attributeId = $checkbox.data('attribute-id');
                    var filterable = $checkbox.is(':checked') ? 1 : 0;

                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'ggmc_toggle_attribute_filterable',
                            nonce: '<?php echo esc_js(wp_create_nonce('ggmc_toggle_filterable')); ?>',
                            attribute_id: attributeId,
                            filterable: filterable
                        },
                        success: function(response) {
                            if (!response.success) {
                                // Revert checkbox on error
                                $checkbox.prop('checked', !filterable);
                                alert(response.data && response.data.message ? response.data.message : 'Failed to update filterable status');
                            }
                        },
                        error: function() {
                            // Revert checkbox on error
                            $checkbox.prop('checked', !filterable);
                            alert('Request failed. Please try again.');
                        }
                    });
                });
            });
            </script>

        </div>
        <?php
    }

    /**
     * Get attribute preset groups for quick setup.
     *
     * @return array Preset groups with attributes.
     */
    private function get_attribute_presets() {
        return array(
            'real-estate' => array(
                'name' => 'Real Estate / Property',
                'icon' => 'fas fa-home',
                'description' => 'Attributes for property listings',
                'attributes' => array(
                    array( 'name' => 'Bedrooms', 'icon' => 'fas fa-bed', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Bathrooms', 'icon' => 'fas fa-bath', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Reception Rooms', 'icon' => 'fas fa-couch', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Floor Area', 'icon' => 'fas fa-ruler-combined', 'unit' => 'sq ft', 'type' => 'number' ),
                    array( 'name' => 'Land Area', 'icon' => 'fas fa-tree', 'unit' => 'acres', 'type' => 'number' ),
                    array( 'name' => 'Year Built', 'icon' => 'fas fa-calendar-alt', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Parking Spaces', 'icon' => 'fas fa-car', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Energy Rating', 'icon' => 'fas fa-leaf', 'unit' => '', 'type' => 'select', 'options' => 'A, B, C, D, E, F, G' ),
                    array( 'name' => 'Property Type', 'icon' => 'fas fa-building', 'unit' => '', 'type' => 'select', 'options' => 'Detached, Semi-Detached, Terraced, Flat, Bungalow, Cottage, Maisonette' ),
                    array( 'name' => 'Heating Type', 'icon' => 'fas fa-fire', 'unit' => '', 'type' => 'select', 'options' => 'Gas Central, Electric, Oil, Heat Pump, Solid Fuel, None' ),
                ),
            ),
            'vehicles' => array(
                'name' => 'Vehicles / Automotive',
                'icon' => 'fas fa-car',
                'description' => 'Attributes for cars and vehicles',
                'attributes' => array(
                    array( 'name' => 'Mileage', 'icon' => 'fas fa-tachometer-alt', 'unit' => 'miles', 'type' => 'number' ),
                    array( 'name' => 'Engine Size', 'icon' => 'fas fa-cog', 'unit' => 'cc', 'type' => 'number' ),
                    array( 'name' => 'Fuel Type', 'icon' => 'fas fa-gas-pump', 'unit' => '', 'type' => 'select', 'options' => 'Petrol, Diesel, Electric, Hybrid, LPG' ),
                    array( 'name' => 'Transmission', 'icon' => 'fas fa-cogs', 'unit' => '', 'type' => 'select', 'options' => 'Manual, Automatic, Semi-Automatic, CVT' ),
                    array( 'name' => 'Year', 'icon' => 'fas fa-calendar-alt', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Doors', 'icon' => 'fas fa-door-open', 'unit' => '', 'type' => 'select', 'options' => '2, 3, 4, 5' ),
                    array( 'name' => 'Seats', 'icon' => 'fas fa-chair', 'unit' => '', 'type' => 'select', 'options' => '2, 4, 5, 7, 8, 9+' ),
                    array( 'name' => 'Color', 'icon' => 'fas fa-palette', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Body Type', 'icon' => 'fas fa-car-side', 'unit' => '', 'type' => 'select', 'options' => 'Saloon, Hatchback, Estate, SUV, Coupe, Convertible, MPV, Van, Pickup' ),
                    array( 'name' => 'Horsepower', 'icon' => 'fas fa-horse-head', 'unit' => 'HP', 'type' => 'number' ),
                    array( 'name' => 'CO2 Emissions', 'icon' => 'fas fa-cloud', 'unit' => 'g/km', 'type' => 'number' ),
                    array( 'name' => 'MPG', 'icon' => 'fas fa-leaf', 'unit' => 'mpg', 'type' => 'number' ),
                ),
            ),
            'electronics' => array(
                'name' => 'Electronics / Appliances',
                'icon' => 'fas fa-plug',
                'description' => 'Attributes for electrical goods and appliances',
                'attributes' => array(
                    array( 'name' => 'Brand', 'icon' => 'fas fa-tag', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Model', 'icon' => 'fas fa-barcode', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Power', 'icon' => 'fas fa-bolt', 'unit' => 'W', 'type' => 'number' ),
                    array( 'name' => 'Voltage', 'icon' => 'fas fa-plug', 'unit' => 'V', 'type' => 'select', 'options' => '110V, 220V, 230V, 240V' ),
                    array( 'name' => 'Energy Rating', 'icon' => 'fas fa-leaf', 'unit' => '', 'type' => 'select', 'options' => 'A+++, A++, A+, A, B, C, D, E, F, G' ),
                    array( 'name' => 'Dimensions', 'icon' => 'fas fa-ruler-combined', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'kg', 'type' => 'number' ),
                    array( 'name' => 'Capacity', 'icon' => 'fas fa-box', 'unit' => 'L', 'type' => 'number' ),
                    array( 'name' => 'Color', 'icon' => 'fas fa-palette', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Warranty', 'icon' => 'fas fa-shield-alt', 'unit' => 'years', 'type' => 'number' ),
                ),
            ),
            'clothing' => array(
                'name' => 'Clothing / Fashion',
                'icon' => 'fas fa-tshirt',
                'description' => 'Attributes for clothing and fashion items',
                'attributes' => array(
                    array( 'name' => 'Size', 'icon' => 'fas fa-ruler', 'unit' => '', 'type' => 'select', 'options' => 'XS, S, M, L, XL, XXL, XXXL' ),
                    array( 'name' => 'Color', 'icon' => 'fas fa-palette', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Brand', 'icon' => 'fas fa-tag', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Gender', 'icon' => 'fas fa-venus-mars', 'unit' => '', 'type' => 'select', 'options' => 'Men, Women, Unisex, Boys, Girls' ),
                    array( 'name' => 'Style', 'icon' => 'fas fa-star', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Fit', 'icon' => 'fas fa-compress-arrows-alt', 'unit' => '', 'type' => 'select', 'options' => 'Regular, Slim, Relaxed, Loose, Oversized' ),
                    array( 'name' => 'Care Instructions', 'icon' => 'fas fa-hand-sparkles', 'unit' => '', 'type' => 'text' ),
                ),
            ),
            'furniture' => array(
                'name' => 'Furniture / Home',
                'icon' => 'fas fa-couch',
                'description' => 'Attributes for furniture and home items',
                'attributes' => array(
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Color', 'icon' => 'fas fa-palette', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Width', 'icon' => 'fas fa-arrows-alt-h', 'unit' => 'cm', 'type' => 'number' ),
                    array( 'name' => 'Height', 'icon' => 'fas fa-arrows-alt-v', 'unit' => 'cm', 'type' => 'number' ),
                    array( 'name' => 'Depth', 'icon' => 'fas fa-ruler', 'unit' => 'cm', 'type' => 'number' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'kg', 'type' => 'number' ),
                    array( 'name' => 'Assembly Required', 'icon' => 'fas fa-tools', 'unit' => '', 'type' => 'select', 'options' => 'Yes, No, Partial' ),
                    array( 'name' => 'Seating Capacity', 'icon' => 'fas fa-users', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Style', 'icon' => 'fas fa-star', 'unit' => '', 'type' => 'select', 'options' => 'Modern, Traditional, Contemporary, Industrial, Scandinavian, Rustic' ),
                ),
            ),
            'computers' => array(
                'name' => 'Computers / Tech',
                'icon' => 'fas fa-laptop',
                'description' => 'Attributes for computers and technology',
                'attributes' => array(
                    array( 'name' => 'Processor', 'icon' => 'fas fa-microchip', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'RAM', 'icon' => 'fas fa-memory', 'unit' => 'GB', 'type' => 'select', 'options' => '4, 8, 16, 32, 64, 128' ),
                    array( 'name' => 'Storage', 'icon' => 'fas fa-hdd', 'unit' => 'GB', 'type' => 'select', 'options' => '128, 256, 512, 1000, 2000' ),
                    array( 'name' => 'Screen Size', 'icon' => 'fas fa-desktop', 'unit' => 'inches', 'type' => 'number' ),
                    array( 'name' => 'Resolution', 'icon' => 'fas fa-th', 'unit' => '', 'type' => 'select', 'options' => 'HD (1366x768), Full HD (1920x1080), 2K (2560x1440), 4K (3840x2160)' ),
                    array( 'name' => 'Graphics Card', 'icon' => 'fas fa-gamepad', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Operating System', 'icon' => 'fas fa-laptop-code', 'unit' => '', 'type' => 'select', 'options' => 'Windows 11, Windows 10, macOS, Linux, Chrome OS' ),
                    array( 'name' => 'Battery Life', 'icon' => 'fas fa-battery-full', 'unit' => 'hours', 'type' => 'number' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'kg', 'type' => 'number' ),
                ),
            ),
            'food-beverage' => array(
                'name' => 'Food & Beverage',
                'icon' => 'fas fa-utensils',
                'description' => 'Attributes for food and drinks',
                'attributes' => array(
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'g', 'type' => 'number' ),
                    array( 'name' => 'Volume', 'icon' => 'fas fa-flask', 'unit' => 'ml', 'type' => 'number' ),
                    array( 'name' => 'Calories', 'icon' => 'fas fa-fire', 'unit' => 'kcal', 'type' => 'number' ),
                    array( 'name' => 'Servings', 'icon' => 'fas fa-utensil-spoon', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Allergens', 'icon' => 'fas fa-exclamation-triangle', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Ingredients', 'icon' => 'fas fa-list', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Origin', 'icon' => 'fas fa-globe', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Shelf Life', 'icon' => 'fas fa-calendar-alt', 'unit' => 'days', 'type' => 'number' ),
                    array( 'name' => 'Storage', 'icon' => 'fas fa-snowflake', 'unit' => '', 'type' => 'select', 'options' => 'Room Temperature, Refrigerate, Freeze' ),
                ),
            ),
            'jewelry' => array(
                'name' => 'Jewelry / Watches',
                'icon' => 'fas fa-gem',
                'description' => 'Attributes for jewelry and watches',
                'attributes' => array(
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'select', 'options' => 'Gold, Silver, Platinum, Rose Gold, Stainless Steel, Titanium' ),
                    array( 'name' => 'Gemstone', 'icon' => 'fas fa-gem', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Carat', 'icon' => 'fas fa-balance-scale', 'unit' => 'ct', 'type' => 'number' ),
                    array( 'name' => 'Ring Size', 'icon' => 'fas fa-ring', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Chain Length', 'icon' => 'fas fa-link', 'unit' => 'inches', 'type' => 'number' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'g', 'type' => 'number' ),
                    array( 'name' => 'Certification', 'icon' => 'fas fa-certificate', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Water Resistance', 'icon' => 'fas fa-tint', 'unit' => 'm', 'type' => 'number' ),
                ),
            ),
            'sports' => array(
                'name' => 'Sports / Fitness',
                'icon' => 'fas fa-running',
                'description' => 'Attributes for sports and fitness equipment',
                'attributes' => array(
                    array( 'name' => 'Size', 'icon' => 'fas fa-ruler', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'kg', 'type' => 'number' ),
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Color', 'icon' => 'fas fa-palette', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Sport Type', 'icon' => 'fas fa-football-ball', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Skill Level', 'icon' => 'fas fa-chart-line', 'unit' => '', 'type' => 'select', 'options' => 'Beginner, Intermediate, Advanced, Professional' ),
                    array( 'name' => 'Age Group', 'icon' => 'fas fa-users', 'unit' => '', 'type' => 'select', 'options' => 'Kids, Youth, Adult, All Ages' ),
                    array( 'name' => 'Brand', 'icon' => 'fas fa-tag', 'unit' => '', 'type' => 'text' ),
                ),
            ),
            'books' => array(
                'name' => 'Books / Media',
                'icon' => 'fas fa-book',
                'description' => 'Attributes for books and media',
                'attributes' => array(
                    array( 'name' => 'Author', 'icon' => 'fas fa-user', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Publisher', 'icon' => 'fas fa-building', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'ISBN', 'icon' => 'fas fa-barcode', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Pages', 'icon' => 'fas fa-file-alt', 'unit' => '', 'type' => 'number' ),
                    array( 'name' => 'Language', 'icon' => 'fas fa-language', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Format', 'icon' => 'fas fa-book-open', 'unit' => '', 'type' => 'select', 'options' => 'Hardcover, Paperback, eBook, Audiobook' ),
                    array( 'name' => 'Publication Date', 'icon' => 'fas fa-calendar-alt', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Genre', 'icon' => 'fas fa-tags', 'unit' => '', 'type' => 'text' ),
                ),
            ),
            'health-beauty' => array(
                'name' => 'Health & Beauty',
                'icon' => 'fas fa-spa',
                'description' => 'Attributes for health and beauty products',
                'attributes' => array(
                    array( 'name' => 'Volume', 'icon' => 'fas fa-flask', 'unit' => 'ml', 'type' => 'number' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'g', 'type' => 'number' ),
                    array( 'name' => 'Skin Type', 'icon' => 'fas fa-hand-sparkles', 'unit' => '', 'type' => 'select', 'options' => 'Normal, Dry, Oily, Combination, Sensitive, All Types' ),
                    array( 'name' => 'Ingredients', 'icon' => 'fas fa-list', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Fragrance', 'icon' => 'fas fa-spray-can', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'SPF', 'icon' => 'fas fa-sun', 'unit' => '', 'type' => 'select', 'options' => 'None, 15, 30, 50, 50+' ),
                    array( 'name' => 'Cruelty Free', 'icon' => 'fas fa-paw', 'unit' => '', 'type' => 'select', 'options' => 'Yes, No' ),
                    array( 'name' => 'Organic', 'icon' => 'fas fa-leaf', 'unit' => '', 'type' => 'select', 'options' => 'Yes, No, Partially' ),
                ),
            ),
            'industrial' => array(
                'name' => 'Industrial / Tools',
                'icon' => 'fas fa-industry',
                'description' => 'Attributes for industrial equipment and tools',
                'attributes' => array(
                    array( 'name' => 'Power', 'icon' => 'fas fa-bolt', 'unit' => 'W', 'type' => 'number' ),
                    array( 'name' => 'Voltage', 'icon' => 'fas fa-plug', 'unit' => 'V', 'type' => 'select', 'options' => '12V, 18V, 110V, 220V, 240V' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'kg', 'type' => 'number' ),
                    array( 'name' => 'Dimensions', 'icon' => 'fas fa-ruler-combined', 'unit' => 'mm', 'type' => 'text' ),
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Speed', 'icon' => 'fas fa-tachometer-alt', 'unit' => 'RPM', 'type' => 'number' ),
                    array( 'name' => 'Capacity', 'icon' => 'fas fa-box', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Warranty', 'icon' => 'fas fa-shield-alt', 'unit' => 'years', 'type' => 'number' ),
                    array( 'name' => 'Certification', 'icon' => 'fas fa-certificate', 'unit' => '', 'type' => 'text' ),
                ),
            ),
            'pets' => array(
                'name' => 'Pet Supplies',
                'icon' => 'fas fa-paw',
                'description' => 'Attributes for pet supplies',
                'attributes' => array(
                    array( 'name' => 'Pet Type', 'icon' => 'fas fa-paw', 'unit' => '', 'type' => 'select', 'options' => 'Dog, Cat, Bird, Fish, Small Animal, Reptile' ),
                    array( 'name' => 'Size', 'icon' => 'fas fa-ruler', 'unit' => '', 'type' => 'select', 'options' => 'Small, Medium, Large, Extra Large' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'kg', 'type' => 'number' ),
                    array( 'name' => 'Age Group', 'icon' => 'fas fa-birthday-cake', 'unit' => '', 'type' => 'select', 'options' => 'Puppy/Kitten, Adult, Senior, All Ages' ),
                    array( 'name' => 'Breed Size', 'icon' => 'fas fa-dog', 'unit' => '', 'type' => 'select', 'options' => 'Toy, Small, Medium, Large, Giant, All Sizes' ),
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Flavor', 'icon' => 'fas fa-bone', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Ingredients', 'icon' => 'fas fa-list', 'unit' => '', 'type' => 'text' ),
                ),
            ),
            'garden' => array(
                'name' => 'Garden / Outdoor',
                'icon' => 'fas fa-seedling',
                'description' => 'Attributes for garden and outdoor products',
                'attributes' => array(
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Dimensions', 'icon' => 'fas fa-ruler-combined', 'unit' => 'cm', 'type' => 'text' ),
                    array( 'name' => 'Weight', 'icon' => 'fas fa-weight-hanging', 'unit' => 'kg', 'type' => 'number' ),
                    array( 'name' => 'Color', 'icon' => 'fas fa-palette', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Weather Resistant', 'icon' => 'fas fa-cloud-sun', 'unit' => '', 'type' => 'select', 'options' => 'Yes, No, Partial' ),
                    array( 'name' => 'Plant Type', 'icon' => 'fas fa-seedling', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Sun Exposure', 'icon' => 'fas fa-sun', 'unit' => '', 'type' => 'select', 'options' => 'Full Sun, Partial Sun, Shade, Any' ),
                    array( 'name' => 'Watering Needs', 'icon' => 'fas fa-tint', 'unit' => '', 'type' => 'select', 'options' => 'Low, Medium, High' ),
                    array( 'name' => 'Assembly Required', 'icon' => 'fas fa-tools', 'unit' => '', 'type' => 'select', 'options' => 'Yes, No, Partial' ),
                ),
            ),
            'toys' => array(
                'name' => 'Toys / Games',
                'icon' => 'fas fa-gamepad',
                'description' => 'Attributes for toys and games',
                'attributes' => array(
                    array( 'name' => 'Age Range', 'icon' => 'fas fa-child', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Material', 'icon' => 'fas fa-layer-group', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Dimensions', 'icon' => 'fas fa-ruler-combined', 'unit' => 'cm', 'type' => 'text' ),
                    array( 'name' => 'Battery Required', 'icon' => 'fas fa-battery-half', 'unit' => '', 'type' => 'select', 'options' => 'Yes, No, Included' ),
                    array( 'name' => 'Players', 'icon' => 'fas fa-users', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Skill Level', 'icon' => 'fas fa-chart-line', 'unit' => '', 'type' => 'select', 'options' => 'Easy, Medium, Hard, Expert' ),
                    array( 'name' => 'Theme', 'icon' => 'fas fa-star', 'unit' => '', 'type' => 'text' ),
                    array( 'name' => 'Safety Certifications', 'icon' => 'fas fa-shield-alt', 'unit' => '', 'type' => 'text' ),
                ),
            ),
        );
    }

    /**
     * Render the attributes presets tab.
     *
     * @param bool $is_premium_active Whether premium is active.
     */
    private function render_attributes_presets_tab( $is_premium_active ) {
        $presets = $this->get_attribute_presets();
        ?>
        <p class="description">Quickly create a complete set of attributes for common product types. Select a preset to auto-generate attributes with icons, data types, and units.</p>

        <?php if ( ! $is_premium_active ) : ?>
            <div class="notice notice-warning inline">
                <p>Activate the Custom Attributes premium feature to import presets.</p>
            </div>
        <?php endif; ?>

        <div class="ggmc-presets-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; margin-top: 20px;">
            <?php foreach ( $presets as $preset_key => $preset ) : ?>
                <div class="ggmc-preset-card" style="background: #fff; border: 1px solid #ddd; border-radius: 8px; padding: 20px; transition: all 0.2s;">
                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 15px;">
                        <span style="width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; font-size: 24px; color: #0F766E; background: #e6f4f3; border-radius: 50%;">
                            <i class="<?php echo esc_attr( $preset['icon'] ); ?>"></i>
                        </span>
                        <div>
                            <h3 style="margin: 0; font-size: 16px; color: #1E293B;"><?php echo esc_html( $preset['name'] ); ?></h3>
                            <span style="font-size: 13px; color: #666;"><?php echo count( $preset['attributes'] ); ?> attributes</span>
                        </div>
                    </div>
                    <p style="color: #666; font-size: 13px; margin-bottom: 15px;"><?php echo esc_html( $preset['description'] ); ?></p>
                    <div style="margin-bottom: 15px; max-height: 120px; overflow-y: auto; padding: 10px; background: #f9f9f9; border-radius: 4px;">
                        <?php foreach ( $preset['attributes'] as $attr ) : ?>
                            <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; font-size: 12px;">
                                <i class="<?php echo esc_attr( $attr['icon'] ); ?>" style="color: #0F766E; width: 16px;"></i>
                                <span><?php echo esc_html( $attr['name'] ); ?></span>
                                <?php if ( ! empty( $attr['unit'] ) ) : ?>
                                    <span style="color: #999;">(<?php echo esc_html( $attr['unit'] ); ?>)</span>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php if ( $is_premium_active ) : ?>
                        <form method="post" action="" onsubmit="return confirm('This will create <?php echo count( $preset['attributes'] ); ?> attributes and a group named \'<?php echo esc_js( $preset['name'] ); ?>\'. Continue?');">
                            <?php wp_nonce_field( 'ggmc_import_preset' ); ?>
                            <input type="hidden" name="action" value="import_preset">
                            <input type="hidden" name="preset_key" value="<?php echo esc_attr( $preset_key ); ?>">
                            <button type="submit" class="button button-primary" style="width: 100%;">
                                <span class="dashicons dashicons-download" style="vertical-align: middle; margin-top: -2px;"></span>
                                Import Preset
                            </button>
                        </form>
                    <?php else : ?>
                        <button type="button" class="button" style="width: 100%;" disabled>
                            <span class="dashicons dashicons-lock" style="vertical-align: middle; margin-top: -2px;"></span>
                            Premium Required
                        </button>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>

        <?php
    }

    /**
     * Reviews moderation page
     */
    public function reviews_page() {
        global $title, $wpdb;
        $title = 'Reviews';

        // Handle actions
        $message = '';
        $message_type = '';

        if (isset($_POST['review_action']) && check_admin_referer('ggmc_review_action')) {
            $review_id = isset($_POST['review_id']) ? intval(wp_unslash($_POST['review_id'])) : 0;
            $action = isset($_POST['review_action']) ? sanitize_text_field(wp_unslash($_POST['review_action'])) : '';

            switch ($action) {
                case 'approve':
                    GGM_Commerce_Reviews::update_status($review_id, 'approved');
                    $message = 'Review approved successfully.';
                    $message_type = 'success';
                    break;

                case 'pending':
                    GGM_Commerce_Reviews::update_status($review_id, 'pending');
                    $message = 'Review set to pending.';
                    $message_type = 'success';
                    break;

                case 'spam':
                    GGM_Commerce_Reviews::update_status($review_id, 'spam');
                    $message = 'Review marked as spam.';
                    $message_type = 'success';
                    break;

                case 'trash':
                    GGM_Commerce_Reviews::update_status($review_id, 'trash');
                    $message = 'Review moved to trash.';
                    $message_type = 'success';
                    break;

                case 'delete':
                    GGM_Commerce_Reviews::delete_review($review_id);
                    $message = 'Review deleted permanently.';
                    $message_type = 'success';
                    break;
            }
        }

        // Handle bulk actions
        if (isset($_POST['bulk_action']) && isset($_POST['review_ids']) && check_admin_referer('ggmc_bulk_review_action')) {
            $bulk_action = isset($_POST['bulk_action']) ? sanitize_text_field(wp_unslash($_POST['bulk_action'])) : '';
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Array sanitized with array_map intval
            $review_ids = isset($_POST['review_ids']) ? array_map('intval', wp_unslash($_POST['review_ids'])) : [];

            if (!empty($review_ids) && in_array($bulk_action, ['approve', 'pending', 'spam', 'trash', 'delete'])) {
                foreach ($review_ids as $review_id) {
                    if ($bulk_action === 'delete') {
                        GGM_Commerce_Reviews::delete_review($review_id);
                    } else {
                        $status = $bulk_action === 'approve' ? 'approved' : $bulk_action;
                        GGM_Commerce_Reviews::update_status($review_id, $status);
                    }
                }
                $message = count($review_ids) . ' review(s) updated successfully.';
                $message_type = 'success';
            }
        }

        // Handle recalculate ratings action
        if (isset($_POST['recalculate_ratings']) && check_admin_referer('ggmc_recalculate_ratings')) {
            GGM_Commerce_Database::recalculate_all_product_ratings();
            $message = 'All product ratings have been recalculated.';
            $message_type = 'success';
        }

        // Get filter parameters
        $status_filter = isset($_GET['status']) ? sanitize_text_field(wp_unslash($_GET['status'])) : '';
        $product_filter = isset($_GET['product_id']) ? intval(wp_unslash($_GET['product_id'])) : 0;
        $rating_filter = isset($_GET['rating']) ? intval($_GET['rating']) : 0;

        // Build query
        $reviews_table = $wpdb->prefix . 'ggmc_product_reviews';
        $products_table = $wpdb->prefix . 'ggmc_products';

        $where_clauses = [];
        if ($status_filter) {
            $where_clauses[] = $wpdb->prepare("r.status = %s", $status_filter);
        }
        if ($product_filter) {
            $where_clauses[] = $wpdb->prepare("r.product_id = %d", $product_filter);
        }
        if ($rating_filter) {
            $where_clauses[] = $wpdb->prepare("r.rating = %d", $rating_filter);
        }

        $where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

        // Get reviews with product names
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $reviews = $wpdb->get_results("
            SELECT r.*, p.name as product_name
            FROM {$reviews_table} r
            LEFT JOIN {$products_table} p ON r.product_id = p.id
            {$where_sql}
            ORDER BY r.created_at DESC
            LIMIT 100
        ");

        // Get status counts
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $status_counts = $wpdb->get_results("
            SELECT status, COUNT(*) as count
            FROM {$reviews_table}
            GROUP BY status
        ");

        $counts = ['all' => 0];
        foreach ($status_counts as $stat) {
            $counts[$stat->status] = $stat->count;
            $counts['all'] += $stat->count;
        }

        // Get products for filter dropdown
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name interpolation
        $products = $wpdb->get_results("SELECT id, name FROM {$products_table} ORDER BY name ASC");

        ?>
        <div class="wrap">
            <?php self::page_title( 'Product Reviews' ); ?>
            <hr class="wp-header-end">

            <?php if ($message): ?>
                <div class="notice notice-<?php echo $message_type === 'success' ? 'success' : 'error'; ?> is-dismissible">
                    <p><?php echo esc_html($message); ?></p>
                </div>
            <?php endif; ?>

            <!-- Status Filter Tabs -->
            <ul class="subsubsub">
                <li><a href="?page=ggmc-reviews" class="<?php echo !$status_filter ? 'current' : ''; ?>">All <span class="count">(<?php echo esc_html($counts['all']); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-reviews&status=pending" class="<?php echo $status_filter === 'pending' ? 'current' : ''; ?>">Pending <span class="count">(<?php echo esc_html($counts['pending'] ?? 0); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-reviews&status=approved" class="<?php echo $status_filter === 'approved' ? 'current' : ''; ?>">Approved <span class="count">(<?php echo esc_html($counts['approved'] ?? 0); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-reviews&status=spam" class="<?php echo $status_filter === 'spam' ? 'current' : ''; ?>">Spam <span class="count">(<?php echo esc_html($counts['spam'] ?? 0); ?>)</span></a> |</li>
                <li><a href="?page=ggmc-reviews&status=trash" class="<?php echo $status_filter === 'trash' ? 'current' : ''; ?>">Trash <span class="count">(<?php echo esc_html($counts['trash'] ?? 0); ?>)</span></a></li>
            </ul>

            <!-- Filters -->
            <div class="tablenav top" style="clear: both;">
                <form method="get" style="float: left;">
                    <input type="hidden" name="page" value="ggmc-reviews">
                    <?php if ($status_filter): ?>
                        <input type="hidden" name="status" value="<?php echo esc_attr($status_filter); ?>">
                    <?php endif; ?>
                    <select name="product_id">
                        <option value="">All Products</option>
                        <?php foreach ($products as $product): ?>
                            <option value="<?php echo esc_attr($product->id); ?>" <?php selected($product_filter, $product->id); ?>>
                                <?php echo esc_html($product->name); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <select name="rating">
                        <option value="">All Ratings</option>
                        <?php for ($i = 5; $i >= 1; $i--): ?>
                            <option value="<?php echo esc_attr($i); ?>" <?php selected($rating_filter, $i); ?>><?php echo esc_html($i); ?> Star<?php echo $i > 1 ? 's' : ''; ?></option>
                        <?php endfor; ?>
                    </select>
                    <button type="submit" class="button">Filter</button>
                </form>

                <!-- Recalculate Ratings Button -->
                <form method="post" style="float: right; margin-left: 10px;">
                    <?php wp_nonce_field('ggmc_recalculate_ratings'); ?>
                    <button type="submit" name="recalculate_ratings" value="1" class="button button-secondary"
                            onclick="return confirm('This will recalculate all product ratings based on approved reviews. Continue?');">
                        <span class="dashicons dashicons-update" style="vertical-align: middle; margin-right: 3px;"></span>
                        Recalculate All Ratings
                    </button>
                </form>
            </div>

            <form method="post" id="reviews-form">
                <?php wp_nonce_field('ggmc_bulk_review_action'); ?>

                <div class="tablenav top">
                    <div class="alignleft actions bulkactions">
                        <select name="bulk_action" id="bulk-action-selector-top">
                            <option value="">Bulk Actions</option>
                            <option value="approve">Approve</option>
                            <option value="pending">Mark as Pending</option>
                            <option value="spam">Mark as Spam</option>
                            <option value="trash">Move to Trash</option>
                            <?php if ($status_filter === 'trash'): ?>
                                <option value="delete">Delete Permanently</option>
                            <?php endif; ?>
                        </select>
                        <button type="submit" class="button action">Apply</button>
                    </div>
                </div>

                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <td class="manage-column column-cb check-column"><input type="checkbox" id="cb-select-all"></td>
                            <th style="width: 60px;">Rating</th>
                            <th>Review</th>
                            <th>Product</th>
                            <th style="width: 150px;">Author</th>
                            <th style="width: 80px;">Status</th>
                            <th style="width: 140px;">Date</th>
                            <th style="width: 200px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($reviews)): ?>
                            <?php foreach ($reviews as $review): ?>
                                <tr>
                                    <th class="check-column">
                                        <input type="checkbox" name="review_ids[]" value="<?php echo esc_attr($review->id); ?>">
                                    </th>
                                    <td>
                                        <span style="color: #ffc107; font-size: 16px;">
                                            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- str_repeat with HTML entities is safe ?>
                                            <?php echo str_repeat('&#9733;', (int) $review->rating); ?>
                                            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- str_repeat with HTML entities is safe ?>
                                            <?php echo str_repeat('&#9734;', 5 - (int) $review->rating); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($review->title): ?>
                                            <strong><?php echo esc_html($review->title); ?></strong><br>
                                        <?php endif; ?>
                                        <?php echo esc_html(wp_trim_words($review->content, 20, '...')); ?>
                                        <?php if ($review->verified_purchase): ?>
                                            <br><span style="color: #46B450; font-size: 11px;">&#10003; Verified Purchase</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-edit-product&id=' . $review->product_id)); ?>">
                                            <?php echo esc_html($review->product_name ?: 'Unknown Product'); ?>
                                        </a>
                                    </td>
                                    <td>
                                        <strong><?php echo esc_html($review->author_name); ?></strong><br>
                                        <small><?php echo esc_html($review->author_email); ?></small>
                                    </td>
                                    <td>
                                        <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_review_status_badge() returns escaped HTML ?>
                                        <?php echo $this->render_review_status_badge($review->status); ?>
                                    </td>
                                    <td>
                                        <?php echo esc_html(gmdate('M j, Y', strtotime($review->created_at))); ?><br>
                                        <small><?php echo esc_html(gmdate('g:i a', strtotime($review->created_at))); ?></small>
                                    </td>
                                    <td>
                                        <div style="display: flex; gap: 5px; flex-wrap: wrap;">
                                            <?php if ($review->status !== 'approved'): ?>
                                                <form method="post" style="display: inline; margin: 0;">
                                                    <?php wp_nonce_field('ggmc_review_action'); ?>
                                                    <input type="hidden" name="review_id" value="<?php echo esc_attr($review->id); ?>">
                                                    <input type="hidden" name="review_action" value="approve">
                                                    <button type="submit" class="button button-small button-primary">Approve</button>
                                                </form>
                                            <?php endif; ?>

                                            <?php if ($review->status === 'approved'): ?>
                                                <form method="post" style="display: inline; margin: 0;">
                                                    <?php wp_nonce_field('ggmc_review_action'); ?>
                                                    <input type="hidden" name="review_id" value="<?php echo esc_attr($review->id); ?>">
                                                    <input type="hidden" name="review_action" value="pending">
                                                    <button type="submit" class="button button-small">Unapprove</button>
                                                </form>
                                            <?php endif; ?>

                                            <?php if ($review->status !== 'spam'): ?>
                                                <form method="post" style="display: inline; margin: 0;">
                                                    <?php wp_nonce_field('ggmc_review_action'); ?>
                                                    <input type="hidden" name="review_id" value="<?php echo esc_attr($review->id); ?>">
                                                    <input type="hidden" name="review_action" value="spam">
                                                    <button type="submit" class="button button-small">Spam</button>
                                                </form>
                                            <?php endif; ?>

                                            <?php if ($review->status !== 'trash'): ?>
                                                <form method="post" style="display: inline; margin: 0;">
                                                    <?php wp_nonce_field('ggmc_review_action'); ?>
                                                    <input type="hidden" name="review_id" value="<?php echo esc_attr($review->id); ?>">
                                                    <input type="hidden" name="review_action" value="trash">
                                                    <button type="submit" class="button button-small">Trash</button>
                                                </form>
                                            <?php else: ?>
                                                <form method="post" style="display: inline; margin: 0;" onsubmit="return confirm('Delete this review permanently?');">
                                                    <?php wp_nonce_field('ggmc_review_action'); ?>
                                                    <input type="hidden" name="review_id" value="<?php echo esc_attr($review->id); ?>">
                                                    <input type="hidden" name="review_action" value="delete">
                                                    <button type="submit" class="button button-small button-link-delete">Delete</button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8">No reviews found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </form>
        </div>

        <script>
        jQuery(document).ready(function($) {
            // Select all checkbox
            $('#cb-select-all').on('change', function() {
                $('input[name="review_ids[]"]').prop('checked', $(this).prop('checked'));
            });
        });
        </script>
        <?php
    }

    /**
     * Checkout Fields page - manage custom checkout fields
     */
    public function checkout_fields_page() {
        echo '<div class="wrap">';
        self::page_title( __( 'Checkout Fields', 'ggm-commerce' ) );
        ggm_commerce_render_checkout_fields_tab();
        echo '</div>';
    }

    /**
     * Discounts page - manage discount codes and vouchers
     */
    public function discounts_page() {
        // Load and render the discounts admin page
        require_once plugin_dir_path( __FILE__ ) . 'admin-discounts-tab.php';
        ggmc_render_discounts_tab();
    }

    /**
     * Customers page - manage customer accounts and B2B tax exemptions
     */
    public function customers_page() {
        global $title, $wpdb;
        $title = 'Customers';

        $tax = ggm_commerce_tax();
        $b2b_enabled = $tax->is_b2b_enabled();

        // Handle actions
        $message = '';
        $message_type = '';

        if (isset($_POST['customer_action']) && check_admin_referer('ggmc_customer_action')) {
            $customer_id = isset($_POST['customer_id']) ? intval(wp_unslash($_POST['customer_id'])) : 0;
            $action = isset($_POST['customer_action']) ? sanitize_text_field(wp_unslash($_POST['customer_action'])) : '';

            if ($customer_id && in_array($action, ['approve', 'reject', 'revoke'], true)) {
                $new_status = '';
                switch ($action) {
                    case 'approve':
                        $new_status = 'approved';
                        $message = __('Tax exemption approved successfully.', 'ggm-commerce');
                        break;
                    case 'reject':
                        $new_status = 'rejected';
                        $message = __('Tax exemption rejected.', 'ggm-commerce');
                        break;
                    case 'revoke':
                        $new_status = 'none';
                        // Also clear is_tax_exempt flag
                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                        $wpdb->update(
                            "{$wpdb->prefix}ggmc_customers",
                            [
                                'is_tax_exempt' => 0,
                                'tax_exempt_status' => 'none'
                            ],
                            ['id' => $customer_id]
                        );
                        $message = __('Tax exemption revoked.', 'ggm-commerce');
                        $message_type = 'success';
                        break;
                }

                if ($new_status && $action !== 'revoke') {
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $wpdb->update(
                        "{$wpdb->prefix}ggmc_customers",
                        ['tax_exempt_status' => $new_status],
                        ['id' => $customer_id]
                    );
                    $message_type = 'success';
                }
            }
        }

        // Customer detail view
        if (isset($_GET['view']) && $_GET['view'] === 'customer' && isset($_GET['id'])) {
            $customer_id = intval($_GET['id']);
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $customer = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_customers WHERE id = %d",
                $customer_id
            ));

            if (!$customer) {
                echo '<div class="wrap"><div class="notice notice-error"><p>' . esc_html__('Customer not found.', 'ggm-commerce') . '</p></div></div>';
                return;
            }

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $addresses = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_customer_addresses WHERE customer_id = %d ORDER BY is_default DESC, id ASC",
                $customer_id
            ));

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $orders = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}ggmc_orders WHERE customer_id = %d OR customer_email = %s ORDER BY created_at DESC LIMIT 20",
                $customer_id,
                $customer->email
            ));

            ?>
            <div class="wrap">
                <?php self::page_title( __( 'Customers', 'ggm-commerce' ) ); ?>
                <hr class="wp-header-end">
                <p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-customers')); ?>">&larr; <?php esc_html_e('Back to Customers', 'ggm-commerce'); ?></a>
                </p>
                <h2><?php echo esc_html($customer->first_name . ' ' . $customer->last_name); ?></h2>

                <div style="display: flex; gap: 20px; margin-bottom: 20px;">
                    <!-- Left: Customer Details -->
                    <div style="flex: 1;">
                        <div class="postbox">
                            <h2 class="hndle" style="padding-left: 12px;"><span><?php esc_html_e('Customer Details', 'ggm-commerce'); ?></span></h2>
                            <div class="inside">
                                <table class="form-table" style="margin: 0;">
                                    <tr>
                                        <th><?php esc_html_e('Name', 'ggm-commerce'); ?></th>
                                        <td><?php echo esc_html($customer->first_name . ' ' . $customer->last_name); ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Email', 'ggm-commerce'); ?></th>
                                        <td><a href="mailto:<?php echo esc_attr($customer->email); ?>"><?php echo esc_html($customer->email); ?></a></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Phone', 'ggm-commerce'); ?></th>
                                        <td><?php echo esc_html($customer->phone ?: '—'); ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Company', 'ggm-commerce'); ?></th>
                                        <td><?php echo esc_html($customer->company ?: '—'); ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Tax ID', 'ggm-commerce'); ?></th>
                                        <td><?php echo !empty($customer->tax_id) ? '<code>' . esc_html($customer->tax_id) . '</code>' : '—'; ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Account Type', 'ggm-commerce'); ?></th>
                                        <td><?php echo $customer->user_id ? esc_html__('Registered', 'ggm-commerce') : esc_html__('Guest', 'ggm-commerce'); ?></td>
                                    </tr>
                                    <?php if ($b2b_enabled): ?>
                                    <tr>
                                        <th><?php esc_html_e('B2B Status', 'ggm-commerce'); ?></th>
                                        <td>
                                            <?php
                                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_tax_status_badge() returns escaped HTML
                                            echo $this->render_tax_status_badge($customer->tax_exempt_status, $customer->is_tax_exempt);
                                            ?>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <th><?php esc_html_e('Total Orders', 'ggm-commerce'); ?></th>
                                        <td><?php echo esc_html(intval($customer->total_orders)); ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Total Spent', 'ggm-commerce'); ?></th>
                                        <td><?php echo esc_html(ggm_commerce_format_price(floatval($customer->total_spent))); ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Last Order', 'ggm-commerce'); ?></th>
                                        <td><?php echo $customer->last_order_date ? esc_html(date_i18n(get_option('date_format'), strtotime($customer->last_order_date))) : '—'; ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php esc_html_e('Member Since', 'ggm-commerce'); ?></th>
                                        <td><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($customer->created_at))); ?></td>
                                    </tr>
                                    <?php if ($customer->user_id): ?>
                                    <tr>
                                        <th><?php esc_html_e('WordPress User', 'ggm-commerce'); ?></th>
                                        <td><a href="<?php echo esc_url(admin_url('user-edit.php?user_id=' . $customer->user_id)); ?>"><?php esc_html_e('Edit User', 'ggm-commerce'); ?></a></td>
                                    </tr>
                                    <?php endif; ?>
                                </table>
                            </div>
                        </div>
                    </div>

                    <!-- Right: Addresses -->
                    <div style="flex: 1;">
                        <div class="postbox">
                            <h2 class="hndle" style="padding-left: 12px;"><span><?php esc_html_e('Addresses', 'ggm-commerce'); ?></span></h2>
                            <div class="inside">
                                <?php if ($addresses): ?>
                                    <?php foreach ($addresses as $address): ?>
                                        <div style="border: 1px solid #e2e8f0; border-radius: 4px; padding: 12px; margin-bottom: 12px;">
                                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                                                <strong>
                                                    <?php echo $address->address_label ? esc_html($address->address_label) : esc_html(ucfirst($address->address_type)); ?>
                                                </strong>
                                                <span style="display: flex; gap: 6px;">
                                                    <span style="display: inline-block; padding: 2px 6px; background: #e2e8f0; color: #555; border-radius: 3px; font-size: 11px;"><?php echo esc_html(ucfirst($address->address_type)); ?></span>
                                                    <?php if ($address->is_default): ?>
                                                        <span style="display: inline-block; padding: 2px 6px; background: #2563eb; color: white; border-radius: 3px; font-size: 11px;"><?php esc_html_e('Default', 'ggm-commerce'); ?></span>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                            <div style="color: #374151; line-height: 1.6;">
                                                <?php if ($address->first_name || $address->last_name): ?>
                                                    <div><?php echo esc_html(trim($address->first_name . ' ' . $address->last_name)); ?></div>
                                                <?php endif; ?>
                                                <?php if ($address->company): ?>
                                                    <div><?php echo esc_html($address->company); ?></div>
                                                <?php endif; ?>
                                                <?php if ($address->address_1): ?>
                                                    <div><?php echo esc_html($address->address_1); ?></div>
                                                <?php endif; ?>
                                                <?php if ($address->address_2): ?>
                                                    <div><?php echo esc_html($address->address_2); ?></div>
                                                <?php endif; ?>
                                                <?php
                                                $city_line = array_filter([$address->city, $address->state, $address->postcode]);
                                                if ($city_line): ?>
                                                    <div><?php echo esc_html(implode(', ', $city_line)); ?></div>
                                                <?php endif; ?>
                                                <?php if ($address->country): ?>
                                                    <div><?php echo esc_html($address->country); ?></div>
                                                <?php endif; ?>
                                                <?php if ($address->phone): ?>
                                                    <div><?php echo esc_html($address->phone); ?></div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <p style="color: #999;"><?php esc_html_e('No addresses saved.', 'ggm-commerce'); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Orders -->
                <div class="postbox">
                    <h2 class="hndle" style="padding-left: 12px;"><span><?php esc_html_e('Recent Orders', 'ggm-commerce'); ?></span></h2>
                    <div class="inside">
                        <?php if ($orders): ?>
                            <table class="wp-list-table widefat fixed striped">
                                <thead>
                                    <tr>
                                        <th><?php esc_html_e('Order ID', 'ggm-commerce'); ?></th>
                                        <th><?php esc_html_e('Date', 'ggm-commerce'); ?></th>
                                        <th><?php esc_html_e('Status', 'ggm-commerce'); ?></th>
                                        <th><?php esc_html_e('Total', 'ggm-commerce'); ?></th>
                                        <th><?php esc_html_e('View', 'ggm-commerce'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($orders as $order): ?>
                                        <tr>
                                            <td>#<?php echo esc_html($order->id); ?></td>
                                            <td><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($order->created_at))); ?></td>
                                            <td><?php echo esc_html(ucfirst($order->status)); ?></td>
                                            <td><?php echo esc_html(ggm_commerce_format_price(floatval($order->total_amount))); ?></td>
                                            <td><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-orders&view=order&id=' . intval($order->id))); ?>"><?php esc_html_e('View', 'ggm-commerce'); ?></a></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <p style="color: #999;"><?php esc_html_e('No orders found for this customer.', 'ggm-commerce'); ?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php
            return;
        }

        // Get filter parameters
        $filter = isset($_GET['filter']) ? sanitize_text_field(wp_unslash($_GET['filter'])) : '';
        $search = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '';

        // Pagination
        $per_page = 20;
        $paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $offset = ($paged - 1) * $per_page;

        // Build query
        $customers_table = $wpdb->prefix . 'ggmc_customers';
        $where_clauses = [];

        if ($filter === 'pending') {
            $where_clauses[] = "tax_exempt_status = 'pending'";
        } elseif ($filter === 'approved') {
            $where_clauses[] = "tax_exempt_status = 'approved'";
        } elseif ($filter === 'rejected') {
            $where_clauses[] = "tax_exempt_status = 'rejected'";
        } elseif ($filter === 'b2b') {
            $where_clauses[] = "is_tax_exempt = 1";
        }

        if ($search) {
            $search_escaped = '%' . $wpdb->esc_like($search) . '%';
            $where_clauses[] = $wpdb->prepare(
                "(email LIKE %s OR first_name LIKE %s OR last_name LIKE %s OR company LIKE %s OR tax_id LIKE %s)",
                $search_escaped, $search_escaped, $search_escaped, $search_escaped, $search_escaped
            );
        }

        $where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

        // Get total count for pagination
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name and pre-escaped where clause
        $filtered_count = intval($wpdb->get_var("SELECT COUNT(*) FROM {$customers_table} {$where_sql}"));
        $total_pages = ceil($filtered_count / $per_page);

        // Get customers
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name and pre-escaped where clause
        $customers = $wpdb->get_results("SELECT * FROM {$customers_table} {$where_sql} ORDER BY id DESC LIMIT {$per_page} OFFSET {$offset}");

        // Get status counts
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name
        $pending_count = $wpdb->get_var("SELECT COUNT(*) FROM {$customers_table} WHERE tax_exempt_status = 'pending'");
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name
        $approved_count = $wpdb->get_var("SELECT COUNT(*) FROM {$customers_table} WHERE tax_exempt_status = 'approved'");
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name
        $rejected_count = $wpdb->get_var("SELECT COUNT(*) FROM {$customers_table} WHERE tax_exempt_status = 'rejected'");
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name
        $b2b_count = $wpdb->get_var("SELECT COUNT(*) FROM {$customers_table} WHERE is_tax_exempt = 1");
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Safe table name
        $total_count = $wpdb->get_var("SELECT COUNT(*) FROM {$customers_table}");

        ?>
        <div class="wrap">
            <?php self::page_title( __( 'Customers', 'ggm-commerce' ) ); ?>
            <hr class="wp-header-end">

            <?php if ($message): ?>
                <div class="notice notice-<?php echo esc_attr($message_type); ?> is-dismissible">
                    <p><?php echo esc_html($message); ?></p>
                </div>
            <?php endif; ?>

            <?php if ($b2b_enabled && $pending_count > 0): ?>
                <div class="notice notice-warning">
                    <p>
                        <strong><?php esc_html_e('Attention:', 'ggm-commerce'); ?></strong>
                        <?php
                        printf(
                            /* translators: %d: number of pending requests */
                            esc_html(_n(
                                'You have %d pending B2B tax exemption request awaiting review.',
                                'You have %d pending B2B tax exemption requests awaiting review.',
                                $pending_count,
                                'ggm-commerce'
                            )),
                            intval($pending_count)
                        );
                        ?>
                        <a href="?page=ggmc-customers&filter=pending"><?php esc_html_e('View pending requests', 'ggm-commerce'); ?></a>
                    </p>
                </div>
            <?php endif; ?>

            <!-- Filter Tabs -->
            <ul class="subsubsub">
                <li>
                    <a href="?page=ggmc-customers" class="<?php echo !$filter ? 'current' : ''; ?>">
                        <?php esc_html_e('All', 'ggm-commerce'); ?> <span class="count">(<?php echo esc_html($total_count); ?>)</span>
                    </a> |
                </li>
                <?php if ($b2b_enabled): ?>
                    <li>
                        <a href="?page=ggmc-customers&filter=pending" class="<?php echo $filter === 'pending' ? 'current' : ''; ?>">
                            <?php esc_html_e('Pending Approval', 'ggm-commerce'); ?> <span class="count">(<?php echo esc_html($pending_count); ?>)</span>
                        </a> |
                    </li>
                    <li>
                        <a href="?page=ggmc-customers&filter=approved" class="<?php echo $filter === 'approved' ? 'current' : ''; ?>">
                            <?php esc_html_e('Approved', 'ggm-commerce'); ?> <span class="count">(<?php echo esc_html($approved_count); ?>)</span>
                        </a> |
                    </li>
                    <li>
                        <a href="?page=ggmc-customers&filter=rejected" class="<?php echo $filter === 'rejected' ? 'current' : ''; ?>">
                            <?php esc_html_e('Rejected', 'ggm-commerce'); ?> <span class="count">(<?php echo esc_html($rejected_count); ?>)</span>
                        </a> |
                    </li>
                    <li>
                        <a href="?page=ggmc-customers&filter=b2b" class="<?php echo $filter === 'b2b' ? 'current' : ''; ?>">
                            <?php esc_html_e('B2B Customers', 'ggm-commerce'); ?> <span class="count">(<?php echo esc_html($b2b_count); ?>)</span>
                        </a>
                    </li>
                <?php endif; ?>
            </ul>

            <!-- Search Box -->
            <form method="get" style="clear: both; margin-top: 20px;">
                <input type="hidden" name="page" value="ggmc-customers">
                <?php if ($filter): ?>
                    <input type="hidden" name="filter" value="<?php echo esc_attr($filter); ?>">
                <?php endif; ?>
                <p class="search-box">
                    <label class="screen-reader-text" for="customer-search-input"><?php esc_html_e('Search Customers', 'ggm-commerce'); ?></label>
                    <input type="search" id="customer-search-input" name="s" value="<?php echo esc_attr($search); ?>" placeholder="<?php esc_attr_e('Search by name, email, company, or tax ID...', 'ggm-commerce'); ?>">
                    <button type="submit" class="button"><?php esc_html_e('Search', 'ggm-commerce'); ?></button>
                </p>
            </form>

            <table class="wp-list-table widefat fixed striped" style="margin-top: 15px;">
                <thead>
                    <tr>
                        <th style="width: 50px;"><?php esc_html_e('ID', 'ggm-commerce'); ?></th>
                        <th><?php esc_html_e('Customer', 'ggm-commerce'); ?></th>
                        <th><?php esc_html_e('Email', 'ggm-commerce'); ?></th>
                        <th><?php esc_html_e('Company', 'ggm-commerce'); ?></th>
                        <th style="width: 110px;"><?php esc_html_e('Phone', 'ggm-commerce'); ?></th>
                        <th style="width: 70px;"><?php esc_html_e('Orders', 'ggm-commerce'); ?></th>
                        <th style="width: 110px;"><?php esc_html_e('Total Spent', 'ggm-commerce'); ?></th>
                        <th style="width: 100px;"><?php esc_html_e('Last Order', 'ggm-commerce'); ?></th>
                        <?php if ($b2b_enabled): ?>
                            <th><?php esc_html_e('Tax ID', 'ggm-commerce'); ?></th>
                            <th style="width: 130px;"><?php esc_html_e('B2B Status', 'ggm-commerce'); ?></th>
                            <th style="width: 180px;"><?php esc_html_e('Actions', 'ggm-commerce'); ?></th>
                        <?php endif; ?>
                        <th style="width: 60px;"><?php esc_html_e('View', 'ggm-commerce'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($customers): ?>
                        <?php foreach ($customers as $customer): ?>
                            <tr>
                                <td><?php echo esc_html($customer->id); ?></td>
                                <td>
                                    <strong><?php echo esc_html($customer->first_name . ' ' . $customer->last_name); ?></strong>
                                    <?php if ($customer->user_id): ?>
                                        <br><small><a href="<?php echo esc_url(admin_url('user-edit.php?user_id=' . $customer->user_id)); ?>"><?php esc_html_e('Edit User', 'ggm-commerce'); ?></a></small>
                                    <?php endif; ?>
                                </td>
                                <td><a href="mailto:<?php echo esc_attr($customer->email); ?>"><?php echo esc_html($customer->email); ?></a></td>
                                <td><?php echo esc_html($customer->company ?: '—'); ?></td>
                                <td><?php echo esc_html($customer->phone ?: '—'); ?></td>
                                <td><?php echo esc_html(intval($customer->total_orders)); ?></td>
                                <td><?php echo esc_html(ggm_commerce_format_price(floatval($customer->total_spent))); ?></td>
                                <td><?php echo $customer->last_order_date ? esc_html(date_i18n(get_option('date_format'), strtotime($customer->last_order_date))) : '—'; ?></td>
                                <?php if ($b2b_enabled): ?>
                                    <td>
                                        <?php if (!empty($customer->tax_id)): ?>
                                            <code><?php echo esc_html($customer->tax_id); ?></code>
                                        <?php else: ?>
                                            —
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php
                                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_tax_status_badge() returns escaped HTML
                                        echo $this->render_tax_status_badge($customer->tax_exempt_status, $customer->is_tax_exempt);
                                        ?>
                                    </td>
                                    <td>
                                        <?php if ($customer->is_tax_exempt && $customer->tax_exempt_status === 'pending'): ?>
                                            <form method="post" style="display: inline;">
                                                <?php wp_nonce_field('ggmc_customer_action'); ?>
                                                <input type="hidden" name="customer_id" value="<?php echo esc_attr($customer->id); ?>">
                                                <input type="hidden" name="customer_action" value="approve">
                                                <button type="submit" class="button button-small button-primary"><?php esc_html_e('Approve', 'ggm-commerce'); ?></button>
                                            </form>
                                            <form method="post" style="display: inline;">
                                                <?php wp_nonce_field('ggmc_customer_action'); ?>
                                                <input type="hidden" name="customer_id" value="<?php echo esc_attr($customer->id); ?>">
                                                <input type="hidden" name="customer_action" value="reject">
                                                <button type="submit" class="button button-small"><?php esc_html_e('Reject', 'ggm-commerce'); ?></button>
                                            </form>
                                        <?php elseif ($customer->tax_exempt_status === 'approved'): ?>
                                            <form method="post" style="display: inline;" onsubmit="return confirm('<?php echo esc_js(__('Are you sure you want to revoke this tax exemption?', 'ggm-commerce')); ?>');">
                                                <?php wp_nonce_field('ggmc_customer_action'); ?>
                                                <input type="hidden" name="customer_id" value="<?php echo esc_attr($customer->id); ?>">
                                                <input type="hidden" name="customer_action" value="revoke">
                                                <button type="submit" class="button button-small"><?php esc_html_e('Revoke', 'ggm-commerce'); ?></button>
                                            </form>
                                        <?php elseif ($customer->tax_exempt_status === 'rejected'): ?>
                                            <form method="post" style="display: inline;">
                                                <?php wp_nonce_field('ggmc_customer_action'); ?>
                                                <input type="hidden" name="customer_id" value="<?php echo esc_attr($customer->id); ?>">
                                                <input type="hidden" name="customer_action" value="approve">
                                                <button type="submit" class="button button-small"><?php esc_html_e('Approve', 'ggm-commerce'); ?></button>
                                            </form>
                                        <?php else: ?>
                                            <span style="color: #999;">—</span>
                                        <?php endif; ?>
                                    </td>
                                <?php endif; ?>
                                <td><a href="<?php echo esc_url(admin_url('admin.php?page=ggmc-customers&view=customer&id=' . intval($customer->id))); ?>"><?php esc_html_e('View', 'ggm-commerce'); ?></a></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="<?php echo $b2b_enabled ? '11' : '8'; ?>" style="text-align: center; padding: 40px;">
                                <?php esc_html_e('No customers found.', 'ggm-commerce'); ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <?php if ($total_pages > 1): ?>
                <div class="tablenav bottom" style="margin-top: 10px;">
                    <div class="tablenav-pages">
                        <?php
                        $pagination_args = [
                            'base'      => add_query_arg('paged', '%#%'),
                            'format'    => '',
                            'prev_text' => '&laquo;',
                            'next_text' => '&raquo;',
                            'total'     => $total_pages,
                            'current'   => $paged,
                        ];
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- paginate_links() returns safe HTML
                        echo paginate_links($pagination_args);
                        ?>
                        <span class="displaying-num">
                            <?php
                            printf(
                                /* translators: %d: number of customers */
                                esc_html(_n('%d customer', '%d customers', $filtered_count, 'ggm-commerce')),
                                intval($filtered_count)
                            );
                            ?>
                        </span>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render tax exemption status badge
     */
    private function render_tax_status_badge($status, $is_tax_exempt = false) {
        if (!$is_tax_exempt && $status === 'none') {
            return '<span style="color: #999;">—</span>';
        }

        $colors = [
            'none' => '#999',
            'pending' => '#FFA500',
            'approved' => '#46B450',
            'rejected' => '#DC3232'
        ];

        $labels = [
            'none' => __('None', 'ggm-commerce'),
            'pending' => __('Pending', 'ggm-commerce'),
            'approved' => __('Approved', 'ggm-commerce'),
            'rejected' => __('Rejected', 'ggm-commerce')
        ];

        $color = $colors[$status] ?? '#999';
        $label = $labels[$status] ?? ucfirst($status);

        return sprintf(
            '<span style="display: inline-block; padding: 3px 8px; background: %s; color: white; border-radius: 3px; font-size: 11px; font-weight: 600;">%s</span>',
            esc_attr($color),
            esc_html($label)
        );
    }

    /**
     * Render review status badge
     */
    private function render_review_status_badge($status) {
        $colors = [
            'pending' => '#FFA500',
            'approved' => '#46B450',
            'spam' => '#999',
            'trash' => '#DC3232'
        ];

        $color = $colors[$status] ?? '#999';
        $label = ucfirst($status);

        return sprintf(
            '<span style="display: inline-block; padding: 3px 6px; background: %s; color: white; border-radius: 3px; font-size: 11px; font-weight: 600;">%s</span>',
            esc_attr($color),
            esc_html($label)
        );
    }

    /**
     * Render status badge with color coding
     */
    private function render_status_badge($status) {
        $colors = [
            'pending' => '#FFA500',
            'processing' => '#0073AA',
            'shipped' => '#9B59B6',
            'completed' => '#46B450',
            'cancelled' => '#DC3232',
            'refunded' => '#999'
        ];

        $color = $colors[$status] ?? '#999';
        $label = ucfirst($status);

        return sprintf(
            '<span style="display: inline-block; padding: 4px 8px; background: %s; color: white; border-radius: 3px; font-size: 12px; font-weight: 600;">%s</span>',
            esc_attr($color),
            esc_html($label)
        );
    }

    /**
     * Render payment status badge
     */
    private function render_payment_status_badge($status) {
        $colors = [
            'pending' => '#FFA500',
            'paid' => '#46B450',
            'failed' => '#DC3232',
            'refunded' => '#999'
        ];

        $color = $colors[$status] ?? '#999';
        $label = ucfirst($status);

        return sprintf(
            '<span style="display: inline-block; padding: 4px 8px; background: %s; color: white; border-radius: 3px; font-size: 12px; font-weight: 600;">%s</span>',
            esc_attr($color),
            esc_html($label)
        );
    }

    /**
     * Render order detail page
     */
    private function render_order_detail($order_id) {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $order = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_orders WHERE id = %d",
            $order_id
        ));

        if (!$order) {
            echo '<div class="wrap"><h1>Order not found</h1><p><a href="?page=ggmc-orders">Back to Orders</a></p></div>';
            return;
        }

        // Get order items
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $items = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_order_items WHERE order_id = %d",
            $order_id
        ));

        // Handle status update
        if (isset($_POST['update_order_status']) && check_admin_referer('ggmc_update_order_' . $order_id)) {
            $new_status = isset($_POST['order_status']) ? sanitize_text_field(wp_unslash($_POST['order_status'])) : '';
            $new_payment_status = isset($_POST['payment_status']) ? sanitize_text_field(wp_unslash($_POST['payment_status'])) : '';
            $note = isset($_POST['order_note']) ? sanitize_textarea_field(wp_unslash($_POST['order_note'])) : '';

            // Track what changed
            $old_status = $order->status;
            $old_payment_status = $order->payment_status;
            $status_changed = ($new_status !== $old_status);
            $payment_changed = ($new_payment_status !== $old_payment_status);

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $updated = $wpdb->update(
                "{$wpdb->prefix}ggmc_orders",
                [
                    'status' => $new_status,
                    'payment_status' => $new_payment_status,
                    'updated_at' => current_time('mysql')
                ],
                ['id' => $order_id]
            );

            if ($updated !== false) {
                // Fire hooks for download permissions, email notifications, etc.
                if ($status_changed) {
                    do_action('ggm_commerce_order_status_changed', $order_id, $new_status, $new_payment_status);
                    do_action('ggmc_order_status_' . $new_status, $order_id);
                }

                // Log status changes as private system notes
                if ($status_changed || $payment_changed) {
                    $changes = [];
                    if ($status_changed) {
                        $changes[] = sprintf('Order Status: %s → %s', ucfirst($old_status), ucfirst($new_status));
                    }
                    if ($payment_changed) {
                        $changes[] = sprintf('Payment Status: %s → %s', ucfirst($old_payment_status), ucfirst($new_payment_status));
                    }
                    GGM_Commerce_Order_Notes::add_system_note($order_id, implode(', ', $changes));
                }

                // Add manual note if provided (with selected visibility)
                if (!empty($note)) {
                    $note_type = isset($_POST['note_type']) ? sanitize_text_field(wp_unslash($_POST['note_type'])) : 'private';
                    GGM_Commerce_Order_Notes::add_note($order_id, $note, $note_type, false);
                }

                $order->status = $new_status;
                $order->payment_status = $new_payment_status;
                echo '<div class="notice notice-success"><p>Order updated successfully!</p></div>';
            }
        }

        // Handle adding a standalone note
        if (isset($_POST['add_order_note']) && check_admin_referer('ggmc_add_note_' . $order_id)) {
            $note_content = isset($_POST['note_content']) ? sanitize_textarea_field(wp_unslash($_POST['note_content'])) : '';
            $note_type = isset($_POST['note_type']) ? sanitize_text_field(wp_unslash($_POST['note_type'])) : 'private';

            if (!empty($note_content)) {
                GGM_Commerce_Order_Notes::add_note($order_id, $note_content, $note_type, false);
                echo '<div class="notice notice-success"><p>Note added successfully!</p></div>';
            }
        }

        // Handle creating a new shipment
        if (isset($_POST['create_shipment']) && check_admin_referer('ggmc_shipment_' . $order_id)) {
            $carrier = isset($_POST['shipment_carrier']) ? sanitize_text_field(wp_unslash($_POST['shipment_carrier'])) : '';
            $tracking_number = isset($_POST['shipment_tracking_number']) ? sanitize_text_field(wp_unslash($_POST['shipment_tracking_number'])) : '';
            $tracking_url = isset($_POST['shipment_tracking_url']) ? esc_url_raw(wp_unslash($_POST['shipment_tracking_url'])) : '';
            $mark_shipped = isset($_POST['mark_shipped']) && $_POST['mark_shipped'] === '1';

            if (!empty($carrier)) {
                $shipment_data = [
                    'carrier'         => $carrier,
                    'tracking_number' => $tracking_number,
                    'tracking_url'    => $tracking_url,
                    'status'          => $mark_shipped ? GGM_Commerce_Shipments::STATUS_SHIPPED : GGM_Commerce_Shipments::STATUS_PENDING,
                ];

                if ($mark_shipped) {
                    $shipment_data['shipped_at'] = current_time('mysql');
                }

                $shipment_id = GGM_Commerce_Shipments::create_shipment($order_id, $shipment_data);

                if ($shipment_id) {
                    echo '<div class="notice notice-success"><p>Shipment created successfully!</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>Failed to create shipment.</p></div>';
                }
            }
        }

        // Handle updating an existing shipment
        if (isset($_POST['update_shipment']) && check_admin_referer('ggmc_shipment_' . $order_id)) {
            $shipment_id = isset($_POST['shipment_id']) ? absint($_POST['shipment_id']) : 0;
            $tracking_number = isset($_POST['shipment_tracking_number']) ? sanitize_text_field(wp_unslash($_POST['shipment_tracking_number'])) : '';
            $tracking_url = isset($_POST['shipment_tracking_url']) ? esc_url_raw(wp_unslash($_POST['shipment_tracking_url'])) : '';
            $new_status = isset($_POST['shipment_status']) ? sanitize_text_field(wp_unslash($_POST['shipment_status'])) : '';

            if ($shipment_id) {
                $update_data = [
                    'tracking_number' => $tracking_number,
                    'tracking_url'    => $tracking_url,
                ];

                if (!empty($new_status)) {
                    $update_data['status'] = $new_status;

                    // Set timestamps based on status
                    if ($new_status === GGM_Commerce_Shipments::STATUS_SHIPPED) {
                        $shipment = GGM_Commerce_Shipments::get_shipment($shipment_id);
                        if ($shipment && empty($shipment->shipped_at)) {
                            $update_data['shipped_at'] = current_time('mysql');
                        }
                    } elseif ($new_status === GGM_Commerce_Shipments::STATUS_DELIVERED) {
                        $update_data['delivered_at'] = current_time('mysql');
                    }
                }

                GGM_Commerce_Shipments::update_shipment($shipment_id, $update_data);
                echo '<div class="notice notice-success"><p>Shipment updated!</p></div>';
            }
        }

        // Handle deleting a shipment
        if (isset($_POST['delete_shipment']) && check_admin_referer('ggmc_shipment_' . $order_id)) {
            $shipment_id = isset($_POST['shipment_id']) ? absint($_POST['shipment_id']) : 0;
            if ($shipment_id) {
                GGM_Commerce_Shipments::delete_shipment($shipment_id);
                echo '<div class="notice notice-success"><p>Shipment deleted.</p></div>';
            }
        }

        ?>
        <div class="wrap">
            <p><a href="?page=ggmc-orders">&larr; Back to Orders</a></p>
            <?php self::page_title( 'Order Details' ); ?>

            <?php
            // Generate secure URLs for packing list and invoice
            $nonce = wp_create_nonce('ggmc_print_order_' . $order->id);
            $plugin_url = plugin_dir_url(dirname(__FILE__));
            $packing_list_url = $plugin_url . 'templates/packing-list.php?order_id=' . $order->id . '&key=' . $nonce;
            $invoice_url = $plugin_url . 'templates/invoice.php?order_id=' . $order->id . '&key=' . $nonce;
            ?>

            <!-- ORDER INFORMATION HEADER -->
            <div class="postbox" style="margin-top: 20px;">
                <div class="inside" style="padding: 12px 15px; margin: 0;">
                    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
                        <div style="display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">
                            <h2 style="margin: 0; font-size: 20px; line-height: 1;">Order #<?php echo esc_html($order->order_number); ?></h2>
                            <span style="color: #666; font-size: 13px;">
                                <span class="dashicons dashicons-calendar-alt" style="vertical-align: middle; font-size: 14px;"></span>
                                <?php echo esc_html(gmdate('F j, Y \a\t g:i a', strtotime($order->created_at))); ?>
                            </span>
                            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_status_badge() returns escaped HTML ?>
                            <?php echo $this->render_status_badge($order->status); ?>
                            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_payment_status_badge() returns escaped HTML ?>
                            <?php echo $this->render_payment_status_badge($order->payment_status); ?>
                        </div>
                        <div style="display: flex; gap: 8px;">
                            <a href="<?php echo esc_url($packing_list_url); ?>" class="button" target="_blank" style="padding: 4px 10px;">
                                <span class="dashicons dashicons-list-view" style="vertical-align: middle; font-size: 16px;"></span> Packing List
                            </a>
                            <a href="<?php echo esc_url($invoice_url); ?>" class="button button-primary" target="_blank" style="padding: 4px 10px;">
                                <span class="dashicons dashicons-media-spreadsheet" style="vertical-align: middle; font-size: 16px;"></span> Invoice
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- MAIN 3-COLUMN GRID: Order Items | Customer Details | Order Status -->
            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-top: 20px;">

                <!-- Column 1: Order Items -->
                <div class="postbox" style="margin: 0;">
                    <h2 class="hndle" style="padding: 12px; margin: 0; border-bottom: 1px solid #ccd0d4;">
                        <span class="dashicons dashicons-cart" style="vertical-align: middle; margin-right: 5px;"></span>
                        Order Items
                    </h2>
                    <div class="inside" style="padding: 0; margin: 0;">
                        <table class="wp-list-table widefat striped" style="border: none;">
                            <thead>
                                <tr>
                                    <th style="padding: 10px;">Product</th>
                                    <th style="width: 50px; text-align: center;">Qty</th>
                                    <th style="width: 80px; text-align: right;">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($items as $item):
                                    // Get variation display - use stored data or look up from variation_id
                                    $variation_display = '';
                                    if (!empty($item->variation_data)) {
                                        $variation_display = $item->variation_data;
                                    } elseif (!empty($item->variation_id) && class_exists('GGM_Commerce_Variations')) {
                                        // Fallback: look up variation attributes from variation_id
                                        $variations_manager = \GGM_Commerce_Variations::instance();
                                        $variation = $variations_manager->get_variation($item->variation_id);
                                        if ($variation && !empty($variation['attributes'])) {
                                            $attr_parts = [];
                                            foreach ($variation['attributes'] as $attr) {
                                                $attr_name = $attr['attribute_name'] ?? $attr['name'] ?? '';
                                                $attr_value = $attr['attribute_value'] ?? $attr['value'] ?? '';
                                                if (!empty($attr_name) && !empty($attr_value)) {
                                                    $attr_parts[] = $attr_name . ': ' . $attr_value;
                                                }
                                            }
                                            if (!empty($attr_parts)) {
                                                $variation_display = implode(', ', $attr_parts);
                                            }
                                        }
                                    }
                                ?>
                                    <tr>
                                        <td style="padding: 10px;">
                                            <strong><?php echo esc_html($item->product_name); ?></strong>
                                            <?php if (!empty($variation_display)): ?>
                                                <br><small style="color: #666; font-style: italic;"><?php echo esc_html($variation_display); ?></small>
                                            <?php endif; ?>
                                            <br><small style="color: #666;">SKU: <?php echo esc_html($item->product_sku); ?></small>
                                        </td>
                                        <td style="text-align: center;"><?php echo esc_html($item->quantity); ?></td>
                                        <td style="text-align: right;">$<?php echo esc_html(number_format($item->total, 2)); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <div style="padding: 12px; background: #f9f9f9; border-top: 1px solid #ccd0d4;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                                <span>Subtotal:</span>
                                <span>$<?php echo esc_html(number_format($order->subtotal, 2)); ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                                <span>
                                    <?php echo esc_html($order->tax_label ?? 'Tax'); ?>:
                                    <?php if (!empty($order->is_tax_exempt)): ?>
                                        <span style="background: #e7f3ff; color: #0073aa; padding: 1px 5px; border-radius: 3px; font-size: 10px;">Exempt</span>
                                    <?php endif; ?>
                                </span>
                                <span>$<?php echo esc_html(number_format($order->tax_amount, 2)); ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                                <span>Shipping:</span>
                                <span>$<?php echo esc_html(number_format($order->shipping_amount, 2)); ?></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; font-weight: bold; font-size: 16px; padding-top: 8px; border-top: 1px solid #ddd;">
                                <span>Total:</span>
                                <span>$<?php echo esc_html(number_format($order->total_amount, 2)); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Column 2: Customer Details -->
                <div class="postbox" style="margin: 0;">
                    <h2 class="hndle" style="padding: 12px; margin: 0; border-bottom: 1px solid #ccd0d4;">
                        <span class="dashicons dashicons-admin-users" style="vertical-align: middle; margin-right: 5px;"></span>
                        Customer Details
                    </h2>
                    <div class="inside" style="padding: 15px;">
                        <div style="margin-bottom: 20px;">
                            <h4 style="margin: 0 0 8px 0; color: #23282d;">
                                <span class="dashicons dashicons-email" style="font-size: 16px; vertical-align: middle;"></span>
                                Contact
                            </h4>
                            <p style="margin: 0;">
                                <strong><?php echo esc_html($order->customer_first_name . ' ' . $order->customer_last_name); ?></strong><br>
                                <a href="mailto:<?php echo esc_attr($order->customer_email); ?>"><?php echo esc_html($order->customer_email); ?></a>
                                <?php if ($order->customer_phone): ?>
                                    <br><?php echo esc_html($order->customer_phone); ?>
                                <?php endif; ?>
                                <?php if (!empty($order->customer_tax_id)): ?>
                                    <br><small>Tax ID: <?php echo esc_html($order->customer_tax_id); ?>
                                    <?php if (!empty($order->is_tax_exempt)): ?>
                                        <span style="background: #d4edda; color: #155724; padding: 1px 5px; border-radius: 3px; font-size: 10px;">Exempt</span>
                                    <?php endif; ?>
                                    </small>
                                <?php endif; ?>
                            </p>
                        </div>

                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                            <div>
                                <h4 style="margin: 0 0 8px 0; color: #23282d; font-size: 13px;">
                                    <span class="dashicons dashicons-building" style="font-size: 14px; vertical-align: middle;"></span>
                                    Billing
                                </h4>
                                <p style="margin: 0; font-size: 12px; line-height: 1.5;">
                                    <?php if ($order->billing_address_1): ?>
                                        <?php echo esc_html($order->billing_address_1); ?><br>
                                        <?php if ($order->billing_address_2): ?>
                                            <?php echo esc_html($order->billing_address_2); ?><br>
                                        <?php endif; ?>
                                        <?php echo esc_html($order->billing_city); ?>, <?php echo esc_html($order->billing_state); ?><br>
                                        <?php echo esc_html($order->billing_postcode); ?><br>
                                        <?php echo esc_html($order->billing_country); ?>
                                    <?php else: ?>
                                        <em style="color: #666;">Not provided</em>
                                    <?php endif; ?>
                                </p>
                            </div>
                            <div>
                                <h4 style="margin: 0 0 8px 0; color: #23282d; font-size: 13px;">
                                    <span class="dashicons dashicons-location" style="font-size: 14px; vertical-align: middle;"></span>
                                    Shipping
                                </h4>
                                <p style="margin: 0; font-size: 12px; line-height: 1.5;">
                                    <?php if ($order->shipping_address_1): ?>
                                        <?php echo esc_html($order->shipping_address_1); ?><br>
                                        <?php if ($order->shipping_address_2): ?>
                                            <?php echo esc_html($order->shipping_address_2); ?><br>
                                        <?php endif; ?>
                                        <?php echo esc_html($order->shipping_city); ?>, <?php echo esc_html($order->shipping_state); ?><br>
                                        <?php echo esc_html($order->shipping_postcode); ?><br>
                                        <?php echo esc_html($order->shipping_country); ?>
                                    <?php else: ?>
                                        <em style="color: #666;">Same as billing</em>
                                    <?php endif; ?>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <?php
                // Custom Checkout Fields section.
                if ( class_exists( 'GGM_Commerce_Checkout_Fields' ) ) {
                    $cf_manager = GGM_Commerce_Checkout_Fields::get_instance();
                    $cf_values  = $cf_manager->get_order_field_values( $order_id );

                    if ( ! empty( $cf_values ) ) :
                ?>
                <div class="postbox" style="margin: 0;">
                    <h2 class="hndle" style="padding: 12px; margin: 0; border-bottom: 1px solid #ccd0d4;">
                        <span class="dashicons dashicons-editor-table" style="vertical-align: middle; margin-right: 5px;"></span>
                        Custom Checkout Fields
                    </h2>
                    <div class="inside" style="padding: 15px;">
                        <table class="widefat fixed striped" style="border: none;">
                            <tbody>
                                <?php foreach ( $cf_values as $cf_val ) :
                                    $cf_label = ! empty( $cf_val->label ) ? $cf_val->label : $cf_val->field_name;
                                    $cf_display = $cf_val->field_value;

                                    // Decode JSON arrays (checkboxes).
                                    $decoded = json_decode( $cf_display, true );
                                    if ( is_array( $decoded ) ) {
                                        $cf_display = implode( ', ', $decoded );
                                    }
                                ?>
                                <tr>
                                    <td style="width: 35%; font-weight: 600; padding: 8px 10px;"><?php echo esc_html( $cf_label ); ?></td>
                                    <td style="padding: 8px 10px;">
                                        <?php if ( $cf_val->admin_editable ) : ?>
                                            <div style="display: flex; gap: 5px; align-items: center;">
                                                <input type="text" class="ggmc-cf-edit-input" data-order-id="<?php echo esc_attr( $order_id ); ?>" data-field-id="<?php echo esc_attr( $cf_val->field_id ); ?>" value="<?php echo esc_attr( $cf_display ); ?>" style="flex: 1;">
                                                <button type="button" class="button button-small ggmc-cf-save-btn"><?php esc_html_e( 'Save', 'ggm-commerce' ); ?></button>
                                            </div>
                                        <?php else : ?>
                                            <?php echo esc_html( $cf_display ); ?>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <script>
                jQuery(document).ready(function($) {
                    $('.ggmc-cf-save-btn').on('click', function() {
                        var $btn = $(this);
                        var $input = $btn.siblings('.ggmc-cf-edit-input');
                        $btn.prop('disabled', true).text('Saving...');
                        $.post(ajaxurl, {
                            action: 'ggmc_update_order_checkout_field',
                            nonce: '<?php echo esc_js( wp_create_nonce( 'ggm_commerce_admin' ) ); ?>',
                            order_id: $input.data('order-id'),
                            field_id: $input.data('field-id'),
                            field_value: $input.val()
                        }, function(response) {
                            $btn.prop('disabled', false).text('Save');
                            if (response.success) {
                                $btn.text('Saved!');
                                setTimeout(function() { $btn.text('Save'); }, 2000);
                            } else {
                                alert(response.data.message || 'Error saving.');
                            }
                        }).fail(function() {
                            $btn.prop('disabled', false).text('Save');
                            alert('Request failed.');
                        });
                    });
                });
                </script>
                <?php
                    endif;
                }
                ?>

                <!-- Column 3: Order Status -->
                <div class="postbox" style="margin: 0;">
                    <h2 class="hndle" style="padding: 12px; margin: 0; border-bottom: 1px solid #ccd0d4;">
                        <span class="dashicons dashicons-flag" style="vertical-align: middle; margin-right: 5px;"></span>
                        Order Status
                    </h2>
                    <div class="inside" style="padding: 15px;">
                        <form method="post">
                            <?php wp_nonce_field('ggmc_update_order_' . $order_id); ?>

                            <p style="margin-top: 0;">
                                <label><strong>Order Status</strong></label><br>
                                <select name="order_status" class="widefat" style="margin-top: 5px;">
                                    <option value="pending" <?php selected($order->status, 'pending'); ?>>Pending</option>
                                    <option value="processing" <?php selected($order->status, 'processing'); ?>>Processing</option>
                                    <option value="shipped" <?php selected($order->status, 'shipped'); ?>>Shipped</option>
                                    <option value="completed" <?php selected($order->status, 'completed'); ?>>Completed</option>
                                    <option value="cancelled" <?php selected($order->status, 'cancelled'); ?>>Cancelled</option>
                                    <option value="refunded" <?php selected($order->status, 'refunded'); ?>>Refunded</option>
                                </select>
                            </p>

                            <p>
                                <label><strong>Payment Status</strong></label><br>
                                <select name="payment_status" class="widefat" style="margin-top: 5px;">
                                    <option value="pending" <?php selected($order->payment_status, 'pending'); ?>>Pending</option>
                                    <option value="paid" <?php selected($order->payment_status, 'paid'); ?>>Paid</option>
                                    <option value="failed" <?php selected($order->payment_status, 'failed'); ?>>Failed</option>
                                    <option value="refunded" <?php selected($order->payment_status, 'refunded'); ?>>Refunded</option>
                                </select>
                            </p>

                            <p>
                                <label><strong>Note (optional)</strong></label><br>
                                <textarea name="order_note" class="widefat" rows="2" style="margin-top: 5px;" placeholder="Add note with status change..."></textarea>
                                <select name="note_type" style="margin-top: 5px; width: 100%;">
                                    <option value="private">Private</option>
                                    <option value="picking">Picking List</option>
                                    <option value="customer">Customer Visible</option>
                                </select>
                            </p>

                            <p style="margin-bottom: 0;">
                                <button type="submit" name="update_order_status" class="button button-primary" style="width: 100%;">Update Order</button>
                            </p>
                        </form>

                        <?php if ($order->payment_method || $order->payment_transaction_id): ?>
                            <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #ddd; font-size: 12px; color: #666;">
                                <?php if ($order->payment_method): ?>
                                    <strong>Payment:</strong> <?php echo esc_html(ucfirst($order->payment_method)); ?><br>
                                <?php endif; ?>
                                <?php if ($order->payment_transaction_id): ?>
                                    <strong>Transaction:</strong> <code style="font-size: 11px;"><?php echo esc_html($order->payment_transaction_id); ?></code>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <!-- BOTTOM 2-COLUMN GRID: Order Notes | Shipping Details -->
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px;">

                <!-- Order Notes -->
                <div class="postbox" style="margin: 0;">
                    <h2 class="hndle" style="padding: 12px; margin: 0; border-bottom: 1px solid #ccd0d4;">
                        <span class="dashicons dashicons-edit" style="vertical-align: middle; margin-right: 5px;"></span>
                        Order Notes & History
                    </h2>
                    <div class="inside" style="padding: 15px;">
                        <?php
                        $order_notes = GGM_Commerce_Order_Notes::get_all_notes($order_id);
                        if (!empty($order_notes)):
                        ?>
                            <div style="max-height: 300px; overflow-y: auto; margin-bottom: 15px;">
                                <?php foreach ($order_notes as $note): ?>
                                    <div style="background: #f9f9f9; padding: 10px; margin-bottom: 8px; border-radius: 4px; border-left: 3px solid <?php echo $note->is_system ? '#ccc' : ($note->note_type === 'customer' ? '#28a745' : ($note->note_type === 'picking' ? '#ffc107' : '#6c757d')); ?>;">
                                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                                            <div>
                                                <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_type_badge returns escaped HTML ?>
                                                <?php echo GGM_Commerce_Order_Notes::get_type_badge($note->note_type); ?>
                                                <?php if ($note->is_system): ?>
                                                    <span style="display: inline-block; padding: 2px 6px; border-radius: 3px; font-size: 10px; background: #e9ecef; color: #6c757d; margin-left: 3px;">System</span>
                                                <?php endif; ?>
                                            </div>
                                            <small style="color: #999; font-size: 11px;">
                                                <?php echo esc_html(gmdate('M j, g:i a', strtotime($note->created_at))); ?>
                                                <?php if (!empty($note->created_by_name)): ?>
                                                    - <?php echo esc_html($note->created_by_name); ?>
                                                <?php endif; ?>
                                            </small>
                                        </div>
                                        <div style="color: #333; font-size: 13px;">
                                            <?php echo nl2br(esc_html($note->content)); ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <p style="color: #666; font-style: italic; margin-bottom: 15px;">No notes yet.</p>
                        <?php endif; ?>

                        <!-- Add Note Form -->
                        <div style="padding-top: 15px; border-top: 1px solid #ddd;">
                            <form method="post">
                                <?php wp_nonce_field('ggmc_add_note_' . $order_id); ?>
                                <textarea name="note_content" class="widefat" rows="2" placeholder="Add a note..."></textarea>
                                <div style="display: flex; gap: 10px; margin-top: 8px;">
                                    <select name="note_type" style="flex: 1;">
                                        <option value="private">Private</option>
                                        <option value="picking">Picking List</option>
                                        <option value="customer">Customer</option>
                                    </select>
                                    <button type="submit" name="add_order_note" class="button">Add Note</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Shipments -->
                <div class="postbox" style="margin: 0;">
                    <h2 class="hndle" style="padding: 12px; margin: 0; border-bottom: 1px solid #ccd0d4;">
                        <span class="dashicons dashicons-car" style="vertical-align: middle; margin-right: 5px;"></span>
                        Shipments
                    </h2>
                    <div class="inside" style="padding: 15px;">
                        <?php
                        $shipments = GGM_Commerce_Shipments::get_order_shipments($order_id);
                        $carriers = GGM_Commerce_Shipments::get_carriers();
                        $statuses = GGM_Commerce_Shipments::get_statuses();

                        if (!empty($shipments)):
                            foreach ($shipments as $shipment):
                        ?>
                            <div style="background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px; padding: 12px; margin-bottom: 12px;">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                    <div>
                                        <strong style="font-size: 13px;"><?php echo esc_html($shipment->shipment_number); ?></strong>
                                        <span style="margin-left: 8px;">
                                            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_status_badge returns escaped HTML ?>
                                            <?php echo GGM_Commerce_Shipments::get_status_badge($shipment->status); ?>
                                        </span>
                                    </div>
                                    <small style="color: #666;">
                                        <?php echo esc_html(GGM_Commerce_Shipments::get_carrier_name($shipment->carrier)); ?>
                                    </small>
                                </div>

                                <form method="post" style="margin: 0;">
                                    <?php wp_nonce_field('ggmc_shipment_' . $order_id); ?>
                                    <input type="hidden" name="shipment_id" value="<?php echo esc_attr($shipment->id); ?>">

                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px;">
                                        <div>
                                            <label style="font-size: 11px; color: #666;">Tracking Number</label>
                                            <input type="text" name="shipment_tracking_number" class="widefat" style="margin-top: 3px;" value="<?php echo esc_attr($shipment->tracking_number); ?>" placeholder="Tracking #">
                                        </div>
                                        <div>
                                            <label style="font-size: 11px; color: #666;">Status</label>
                                            <select name="shipment_status" class="widefat" style="margin-top: 3px;">
                                                <?php foreach ($statuses as $status_key => $status_label): ?>
                                                    <option value="<?php echo esc_attr($status_key); ?>" <?php selected($shipment->status, $status_key); ?>><?php echo esc_html($status_label); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div style="margin-bottom: 10px;">
                                        <label style="font-size: 11px; color: #666;">Tracking URL</label>
                                        <input type="url" name="shipment_tracking_url" class="widefat" style="margin-top: 3px;" value="<?php echo esc_attr($shipment->tracking_url); ?>" placeholder="https://...">
                                    </div>

                                    <div style="display: flex; gap: 8px; align-items: center;">
                                        <button type="submit" name="update_shipment" class="button button-small">Update</button>
                                        <?php if (!empty($shipment->tracking_url)): ?>
                                            <a href="<?php echo esc_url($shipment->tracking_url); ?>" class="button button-small" target="_blank">
                                                <span class="dashicons dashicons-external" style="font-size: 14px; vertical-align: middle;"></span> Track
                                            </a>
                                        <?php endif; ?>
                                        <button type="submit" name="delete_shipment" class="button button-small button-link-delete" style="color: #a00; margin-left: auto;" onclick="return confirm('Delete this shipment?');">Delete</button>
                                    </div>

                                    <?php if (!empty($shipment->shipped_at)): ?>
                                        <div style="margin-top: 10px; padding-top: 8px; border-top: 1px solid #ddd; font-size: 11px; color: #666;">
                                            <span class="dashicons dashicons-clock" style="font-size: 12px; vertical-align: middle;"></span>
                                            Shipped: <?php echo esc_html(gmdate('M j, Y g:i a', strtotime($shipment->shipped_at))); ?>
                                            <?php if (!empty($shipment->delivered_at)): ?>
                                                &bull; Delivered: <?php echo esc_html(gmdate('M j, Y g:i a', strtotime($shipment->delivered_at))); ?>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </form>
                            </div>
                        <?php
                            endforeach;
                        else:
                        ?>
                            <p style="color: #666; font-style: italic; margin: 0 0 15px 0;">No shipments yet.</p>
                        <?php endif; ?>

                        <!-- Create New Shipment Form -->
                        <div style="padding-top: 15px; border-top: 1px solid #ddd;">
                            <h4 style="margin: 0 0 10px 0; font-size: 13px;">
                                <span class="dashicons dashicons-plus-alt" style="font-size: 16px; vertical-align: middle;"></span>
                                Add Shipment
                            </h4>
                            <form method="post">
                                <?php wp_nonce_field('ggmc_shipment_' . $order_id); ?>

                                <div style="margin-bottom: 10px;">
                                    <select name="shipment_carrier" class="widefat" required>
                                        <option value="">-- Select Carrier --</option>
                                        <?php foreach ($carriers as $carrier_key => $carrier_name): ?>
                                            <option value="<?php echo esc_attr($carrier_key); ?>"><?php echo esc_html($carrier_name); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px;">
                                    <input type="text" name="shipment_tracking_number" class="widefat" placeholder="Tracking Number">
                                    <input type="url" name="shipment_tracking_url" class="widefat" placeholder="Tracking URL">
                                </div>

                                <div style="display: flex; gap: 10px; align-items: center;">
                                    <label style="font-size: 12px;">
                                        <input type="checkbox" name="mark_shipped" value="1" checked>
                                        Mark as shipped
                                    </label>
                                    <button type="submit" name="create_shipment" class="button button-primary" style="margin-left: auto;">
                                        <span class="dashicons dashicons-plus" style="vertical-align: middle;"></span> Create Shipment
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

            </div>
        </div>
        <?php
    }

    /**
     * AJAX handler for MCP authentication toggle
     */
    public function ajax_toggle_mcp_auth() {
        // Verify nonce
        check_ajax_referer('ggm_mcp_toggle_auth', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        // Get the enable parameter
        $enable = isset($_POST['enable']) && $_POST['enable'] === 'yes';

        // Update the option (inverse logic: option stores "disable" state)
        $disable_auth = !$enable;
        update_option('ggm_mcp_disable_auth', $disable_auth);

        wp_send_json_success([
            'message' => $enable ? 'Authentication enabled' : 'Authentication disabled',
            'auth_disabled' => $disable_auth
        ]);
    }

    /**
     * AJAX handler for generating MCP API key
     */
    public function ajax_generate_mcp_api_key() {
        // Verify nonce
        check_ajax_referer('ggm_mcp_generate_key', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        // Get parameters
        $key_name = isset($_POST['key_name']) ? sanitize_text_field(wp_unslash($_POST['key_name'])) : '';
        $expires_in_days = isset($_POST['expires_in_days']) ? intval($_POST['expires_in_days']) : 365;

        if (empty($key_name)) {
            wp_send_json_error(['message' => 'API key name is required']);
            return;
        }

        // Load MCP auth class
        require_once plugin_dir_path(__FILE__) . 'mcp/class-mcp-auth.php';
        $auth = new GGM_Commerce_MCP_Auth();

        // Generate the key
        $api_key = $auth->generate_api_key($key_name, [], $expires_in_days);

        if (is_wp_error($api_key)) {
            wp_send_json_error(['message' => $api_key->get_error_message()]);
            return;
        }

        wp_send_json_success([
            'api_key' => $api_key,
            'message' => 'API key generated successfully'
        ]);
    }

    /**
     * AJAX handler for toggling MCP API key status
     */
    public function ajax_toggle_mcp_api_key() {
        // Verify nonce
        check_ajax_referer('ggm_mcp_toggle_key', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        $key_hash = isset($_POST['key_hash']) ? sanitize_text_field(wp_unslash($_POST['key_hash'])) : '';
        $new_status = isset($_POST['new_status']) ? sanitize_text_field(wp_unslash($_POST['new_status'])) : '';

        if (empty($key_hash) || !in_array($new_status, ['active', 'inactive'], true)) {
            wp_send_json_error(['message' => 'Invalid parameters']);
            return;
        }

        // Load MCP auth class
        require_once plugin_dir_path(__FILE__) . 'mcp/class-mcp-auth.php';
        $auth = new GGM_Commerce_MCP_Auth();

        $result = $auth->update_api_key_status($key_hash, $new_status);

        if ($result) {
            wp_send_json_success([
                'message' => $new_status === 'active' ? 'API key enabled' : 'API key disabled',
                'new_status' => $new_status
            ]);
        } else {
            wp_send_json_error(['message' => 'Failed to update API key status']);
        }
    }

    /**
     * AJAX handler for revoking MCP API key
     */
    public function ajax_revoke_mcp_api_key() {
        // Verify nonce
        check_ajax_referer('ggm_mcp_revoke_key', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        $key_hash = isset($_POST['key_hash']) ? sanitize_text_field(wp_unslash($_POST['key_hash'])) : '';

        if (empty($key_hash)) {
            wp_send_json_error(['message' => 'Invalid key']);
            return;
        }

        // Load MCP auth class
        require_once plugin_dir_path(__FILE__) . 'mcp/class-mcp-auth.php';
        $auth = new GGM_Commerce_MCP_Auth();

        // Find and revoke the key by hash
        $stored_keys = get_option('ggm_commerce_mcp_api_keys', []);
        $revoked = false;

        foreach ($stored_keys as $key => $data) {
            if (md5($key) === $key_hash) {
                $auth->revoke_api_key($key);
                $revoked = true;
                break;
            }
        }

        if ($revoked) {
            wp_send_json_success(['message' => 'API key revoked']);
        } else {
            wp_send_json_error(['message' => 'API key not found']);
        }
    }

    /**
     * AJAX handler for clearing all carts
     */
    public function ajax_clear_all_carts() {
        // Verify nonce
        check_ajax_referer('ggm_clear_carts', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        global $wpdb;

        // Get count before deleting
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $db_count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_cart");

        // Clear database cart items
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $deleted = $wpdb->query("TRUNCATE TABLE {$wpdb->prefix}ggmc_cart");

        if ($deleted === false) {
            wp_send_json_error(['message' => 'Failed to clear cart database']);
            return;
        }

        // Clear current user's session cart
        if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
            session_start();
        }

        $session_count = 0;
        if (isset($_SESSION['ggm_commerce_cart'])) {
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Cart data is internal
            $session_cart = $_SESSION['ggm_commerce_cart'];
            $session_count = !empty($session_cart) ? array_sum(array_column($session_cart, 'quantity')) : 0;
            unset($_SESSION['ggm_commerce_cart']);
        }

        wp_send_json_success([
            'message' => 'All cart data cleared',
            'db_count' => intval($db_count),
            'session_count' => intval($session_count),
            'total_cleared' => intval($db_count) + intval($session_count)
        ]);
    }

    /**
     * AJAX handler for clearing all wishlists
     */
    public function ajax_clear_all_wishlists() {
        // Verify nonce
        check_ajax_referer('ggm_clear_wishlists', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        global $wpdb;

        // Get count before deleting
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_wishlist");

        // Clear wishlist table
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $deleted = $wpdb->query("TRUNCATE TABLE {$wpdb->prefix}ggmc_wishlist");

        if ($deleted === false) {
            wp_send_json_error(['message' => 'Failed to clear wishlist database']);
            return;
        }

        wp_send_json_success([
            'message' => 'All wishlist data cleared',
            'count' => intval($count)
        ]);
    }

    /**
     * AJAX handler for clearing all comparisons
     * Note: Comparisons are stored in cookies, so this clears server-side
     */
    public function ajax_clear_all_comparisons() {
        // Verify nonce
        check_ajax_referer('ggm_clear_comparisons', 'nonce');

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        // Clear the comparison cookie for this user
        if (isset($_COOKIE['ggmc_compare'])) {
            setcookie('ggmc_compare', '', time() - 3600, '/');
            unset($_COOKIE['ggmc_compare']);
        }

        wp_send_json_success([
            'message' => 'Comparison cookie cleared'
        ]);
    }

    /**
     * AJAX handler for setting default category.
     */
    public function ajax_set_default_category() {
        // Verify nonce.
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce(wp_unslash($_POST['nonce']), 'ggmc_set_default_category')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check permissions.
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized']);
            return;
        }

        // Get and validate category ID.
        $category_id = isset($_POST['category_id']) ? absint($_POST['category_id']) : 0;
        if ($category_id <= 0) {
            wp_send_json_error(['message' => 'Invalid category ID']);
            return;
        }

        // Verify category exists.
        $taxonomy = GGM_Commerce_Taxonomy::get_instance();
        $category = $taxonomy->get_category($category_id);
        if (!$category) {
            wp_send_json_error(['message' => 'Category not found']);
            return;
        }

        // Save as default category.
        $options = get_option('ggm_commerce_catalog_options', []);
        $options['default_category'] = $category_id;
        update_option('ggm_commerce_catalog_options', $options);

        wp_send_json_success([
            'message' => 'Default category set to: ' . $category->name,
            'category_id' => $category_id,
            'category_name' => $category->name
        ]);
    }

    /**
     * AJAX handler for uploading SVG icon for the icon picker.
     */
    public function ajax_upload_svg_icon() {
        // Verify nonce.
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce(wp_unslash($_POST['nonce']), 'ggmc_icon_picker')) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check permissions.
        if (!current_user_can('upload_files')) {
            wp_send_json_error(['message' => 'You do not have permission to upload files']);
            return;
        }

        // Check if file was uploaded.
        if (empty($_FILES['svg_file'])) {
            wp_send_json_error(['message' => 'No file uploaded']);
            return;
        }

        $file = $_FILES['svg_file'];

        // Verify it's an SVG file.
        $file_type = wp_check_filetype($file['name'], array('svg' => 'image/svg+xml'));
        if ($file_type['ext'] !== 'svg') {
            wp_send_json_error(['message' => 'Only SVG files are allowed']);
            return;
        }

        // Allow SVG uploads temporarily.
        add_filter('upload_mimes', function($mimes) {
            $mimes['svg'] = 'image/svg+xml';
            return $mimes;
        });

        // Handle the upload.
        $upload = wp_handle_upload($file, array('test_form' => false));

        if (isset($upload['error'])) {
            wp_send_json_error(['message' => $upload['error']]);
            return;
        }

        // Basic SVG sanitization - check for script tags and event handlers.
        $svg_content = file_get_contents($upload['file']);
        if (preg_match('/<script|onclick|onload|onerror|onmouseover/i', $svg_content)) {
            // Delete the uploaded file.
            wp_delete_file($upload['file']);
            wp_send_json_error(['message' => 'SVG contains potentially unsafe content']);
            return;
        }

        wp_send_json_success([
            'url' => $upload['url'],
            'file' => $upload['file'],
        ]);
    }

    /**
     * AJAX handler for creating kit stock.
     */
    public function ajax_create_kit_stock() {
        // Verify nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( wp_unslash( $_POST['nonce'] ), 'ggmc_kit_stock_action' ) ) {
            wp_send_json_error( array( 'message' => 'Security check failed' ) );
            return;
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Unauthorized' ) );
            return;
        }

        // Check if feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-kits' ) ) {
            wp_send_json_error( array( 'message' => 'Product Kits feature not activated' ) );
            return;
        }

        $kit_id   = isset( $_POST['kit_id'] ) ? absint( $_POST['kit_id'] ) : 0;
        $quantity = isset( $_POST['quantity'] ) ? absint( $_POST['quantity'] ) : 1;
        $override = isset( $_POST['override'] ) && $_POST['override'] === '1';

        if ( ! $kit_id ) {
            wp_send_json_error( array( 'message' => 'Invalid kit ID' ) );
            return;
        }

        $kits_manager = GGM_Commerce_Kits::get_instance();
        $result       = $kits_manager->create_kit_stock( $kit_id, $quantity, $override );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( array( 'message' => sprintf( '%d kit unit(s) created successfully', $quantity ) ) );
    }

    /**
     * AJAX handler for breaking down kit stock.
     */
    public function ajax_breakdown_kit_stock() {
        // Verify nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( wp_unslash( $_POST['nonce'] ), 'ggmc_kit_stock_action' ) ) {
            wp_send_json_error( array( 'message' => 'Security check failed' ) );
            return;
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Unauthorized' ) );
            return;
        }

        // Check if feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-kits' ) ) {
            wp_send_json_error( array( 'message' => 'Product Kits feature not activated' ) );
            return;
        }

        $kit_id   = isset( $_POST['kit_id'] ) ? absint( $_POST['kit_id'] ) : 0;
        $quantity = isset( $_POST['quantity'] ) ? absint( $_POST['quantity'] ) : 1;

        if ( ! $kit_id ) {
            wp_send_json_error( array( 'message' => 'Invalid kit ID' ) );
            return;
        }

        $kits_manager = GGM_Commerce_Kits::get_instance();
        $result       = $kits_manager->breakdown_kit_stock( $kit_id, $quantity );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( array( 'message' => sprintf( '%d kit unit(s) broken down, components returned to stock', $quantity ) ) );
    }

    /**
     * AJAX handler for saving Stripe settings.
     */
    public function ajax_save_stripe_settings() {
        // Verify nonce
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ggm_commerce_stripe_settings' ) ) {
            wp_send_json_error( 'Security check failed' );
            return;
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Unauthorized' );
            return;
        }

        // Check if Stripe is activated
        $license = ggm_commerce_license();
        if ( ! $license->is_widget_activated( 'stripe-gateway' ) ) {
            wp_send_json_error( 'Stripe gateway is not activated' );
            return;
        }

        // Parse form data
        $settings_string = isset( $_POST['settings'] ) ? wp_unslash( $_POST['settings'] ) : '';
        parse_str( $settings_string, $parsed_settings );

        $stripe_data = isset( $parsed_settings['stripe'] ) ? $parsed_settings['stripe'] : array();

        // Get existing settings
        $existing_settings = get_option( 'ggm_commerce_gateway_stripe', array() );

        // Build new settings array
        $live_secret = sanitize_text_field( $stripe_data['live_secret_key'] ?? '' );
        $test_secret = sanitize_text_field( $stripe_data['test_secret_key'] ?? '' );
        $webhook_secret = sanitize_text_field( $stripe_data['webhook_secret'] ?? '' );

        $new_settings = array(
            'enabled'               => isset( $stripe_data['enabled'] ) ? 'yes' : 'no',
            'test_mode'             => isset( $stripe_data['test_mode'] ) ? 'yes' : 'no',
            'live_publishable_key'  => sanitize_text_field( $stripe_data['live_publishable_key'] ?? '' ),
            'live_secret_key'       => '',
            'test_publishable_key'  => sanitize_text_field( $stripe_data['test_publishable_key'] ?? '' ),
            'test_secret_key'       => '',
            'webhook_secret'        => '',
            'enable_apple_pay'      => isset( $stripe_data['enable_apple_pay'] ) ? 'yes' : 'no',
            'enable_google_pay'     => isset( $stripe_data['enable_google_pay'] ) ? 'yes' : 'no',
            'enable_link'           => isset( $stripe_data['enable_link'] ) ? 'yes' : 'no',
        );

        // Encrypt and store secret keys (only if new value provided, otherwise preserve existing)
        if ( ! empty( $live_secret ) ) {
            $new_settings['live_secret_key'] = $this->encrypt_api_key( $live_secret );
        } elseif ( ! empty( $existing_settings['live_secret_key'] ) ) {
            $new_settings['live_secret_key'] = $existing_settings['live_secret_key'];
        }

        if ( ! empty( $test_secret ) ) {
            $new_settings['test_secret_key'] = $this->encrypt_api_key( $test_secret );
        } elseif ( ! empty( $existing_settings['test_secret_key'] ) ) {
            $new_settings['test_secret_key'] = $existing_settings['test_secret_key'];
        }

        if ( ! empty( $webhook_secret ) ) {
            $new_settings['webhook_secret'] = $this->encrypt_api_key( $webhook_secret );
        } elseif ( ! empty( $existing_settings['webhook_secret'] ) ) {
            $new_settings['webhook_secret'] = $existing_settings['webhook_secret'];
        }

        // Save settings
        update_option( 'ggm_commerce_gateway_stripe', $new_settings );

        wp_send_json_success( 'Settings saved successfully' );
    }

    /**
     * AJAX handler for saving PayPal settings.
     */
    public function ajax_save_paypal_settings() {
        // Verify nonce
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'ggm_commerce_paypal_settings' ) ) {
            wp_send_json_error( 'Security check failed' );
            return;
        }

        // Check permissions
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Unauthorized' );
            return;
        }

        // Check if PayPal is activated
        $license = ggm_commerce_license();
        if ( ! $license->is_widget_activated( 'paypal-gateway' ) ) {
            wp_send_json_error( 'PayPal gateway is not activated' );
            return;
        }

        // Parse form data
        $settings_string = isset( $_POST['settings'] ) ? wp_unslash( $_POST['settings'] ) : '';
        parse_str( $settings_string, $parsed_settings );

        $paypal_data = isset( $parsed_settings['paypal'] ) ? $parsed_settings['paypal'] : array();

        // Get existing settings
        $existing_settings = get_option( 'ggm_commerce_gateway_paypal', array() );

        // Build new settings array
        $live_secret = sanitize_text_field( $paypal_data['live_client_secret'] ?? '' );
        $test_secret = sanitize_text_field( $paypal_data['test_client_secret'] ?? '' );

        $new_settings = array(
            'enabled'               => isset( $paypal_data['enabled'] ) ? 'yes' : 'no',
            'test_mode'             => isset( $paypal_data['test_mode'] ) ? 'yes' : 'no',
            'live_client_id'        => sanitize_text_field( $paypal_data['live_client_id'] ?? '' ),
            'live_client_secret'    => '',
            'test_client_id'        => sanitize_text_field( $paypal_data['test_client_id'] ?? '' ),
            'test_client_secret'    => '',
            'webhook_id'            => sanitize_text_field( $paypal_data['webhook_id'] ?? '' ),
            'enable_paypal'         => isset( $paypal_data['enable_paypal'] ) ? 'yes' : 'no',
            'enable_pay_later'      => isset( $paypal_data['enable_pay_later'] ) ? 'yes' : 'no',
            'enable_venmo'          => isset( $paypal_data['enable_venmo'] ) ? 'yes' : 'no',
            'enable_card'           => isset( $paypal_data['enable_card'] ) ? 'yes' : 'no',
            'button_layout'         => sanitize_text_field( $paypal_data['button_layout'] ?? 'vertical' ),
            'button_color'          => sanitize_text_field( $paypal_data['button_color'] ?? 'gold' ),
            'button_shape'          => sanitize_text_field( $paypal_data['button_shape'] ?? 'rect' ),
            'button_label'          => sanitize_text_field( $paypal_data['button_label'] ?? 'paypal' ),
        );

        // Encrypt and store secret keys (only if new value provided, otherwise preserve existing)
        if ( ! empty( $live_secret ) ) {
            $new_settings['live_client_secret'] = $this->encrypt_api_key( $live_secret );
        } elseif ( ! empty( $existing_settings['live_client_secret'] ) ) {
            $new_settings['live_client_secret'] = $existing_settings['live_client_secret'];
        }

        if ( ! empty( $test_secret ) ) {
            $new_settings['test_client_secret'] = $this->encrypt_api_key( $test_secret );
        } elseif ( ! empty( $existing_settings['test_client_secret'] ) ) {
            $new_settings['test_client_secret'] = $existing_settings['test_client_secret'];
        }

        // Save settings
        update_option( 'ggm_commerce_gateway_paypal', $new_settings );

        wp_send_json_success( 'Settings saved successfully' );
    }

    /**
     * Encrypt an API key for secure storage.
     *
     * Uses WordPress AUTH_KEY and AUTH_SALT for AES-256-CBC encryption.
     * This follows Stripe's best practice of encrypting secret keys at rest.
     *
     * @param string $key The API key to encrypt.
     * @return string The encrypted key (base64 encoded).
     */
    private function encrypt_api_key( $key ) {
        if ( empty( $key ) ) {
            return '';
        }

        // Check if WordPress security keys are defined
        if ( ! defined( 'AUTH_KEY' ) || ! defined( 'AUTH_SALT' ) ) {
            // Fallback: store as-is if no encryption keys available
            // This should be rare in production WordPress installations
            return $key;
        }

        // Generate IV from AUTH_SALT (16 bytes required for AES-256-CBC)
        $iv = substr( AUTH_SALT, 0, 16 );
        if ( strlen( $iv ) < 16 ) {
            $iv = str_pad( $iv, 16, '0' );
        }

        // Encrypt using AES-256-CBC
        $encrypted = openssl_encrypt( $key, 'AES-256-CBC', AUTH_KEY, 0, $iv );

        if ( false === $encrypted ) {
            // Encryption failed, return empty to prevent storing plaintext
            return '';
        }

        // Return base64-encoded encrypted value with a prefix to identify encrypted keys
        return 'enc:' . base64_encode( $encrypted );
    }

    /**
     * Decrypt an API key from secure storage.
     *
     * @param string $encrypted_key The encrypted API key.
     * @return string The decrypted key.
     */
    private function decrypt_api_key( $encrypted_key ) {
        if ( empty( $encrypted_key ) ) {
            return '';
        }

        // Check if this is an encrypted key (has our prefix)
        if ( strpos( $encrypted_key, 'enc:' ) !== 0 ) {
            // Not encrypted (legacy or fallback), return as-is
            return $encrypted_key;
        }

        // Check if WordPress security keys are defined
        if ( ! defined( 'AUTH_KEY' ) || ! defined( 'AUTH_SALT' ) ) {
            return '';
        }

        // Remove prefix and decode
        $encoded = substr( $encrypted_key, 4 );
        $decoded = base64_decode( $encoded );

        if ( false === $decoded ) {
            return '';
        }

        // Generate IV from AUTH_SALT
        $iv = substr( AUTH_SALT, 0, 16 );
        if ( strlen( $iv ) < 16 ) {
            $iv = str_pad( $iv, 16, '0' );
        }

        // Decrypt
        $decrypted = openssl_decrypt( $decoded, 'AES-256-CBC', AUTH_KEY, 0, $iv );

        return $decrypted ? $decrypted : '';
    }

    /**
     * Mask an API key for display (show only last 4 characters).
     *
     * @param string $key The API key to mask.
     * @return string The masked key or empty string.
     */
    private function mask_api_key( $key ) {
        if ( empty( $key ) ) {
            return '';
        }

        // For encrypted keys, we can't show partial - just indicate it's set
        if ( strpos( $key, 'enc:' ) === 0 ) {
            return '••••••••••••••••';
        }

        // For unencrypted keys, show last 4 chars
        $length = strlen( $key );
        if ( $length <= 4 ) {
            return str_repeat( '•', $length );
        }

        return str_repeat( '•', $length - 4 ) . substr( $key, -4 );
    }

    /**
     * AJAX handler for getting component images for kit/build gallery population.
     */
    public function ajax_get_component_images() {
        // Verify nonce.
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is being verified not used as data
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( wp_unslash( $_POST['nonce'] ), 'ggmc_get_component_images' ) ) {
            wp_send_json_error( array( 'message' => 'Security check failed' ) );
            return;
        }

        // Check permissions.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Unauthorized' ) );
            return;
        }

        // Check if Product Kits feature is activated.
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-kits' ) ) {
            wp_send_json_error( array( 'message' => 'Product Kits feature not activated' ) );
            return;
        }

        // Get product IDs from request.
        $product_ids = isset( $_POST['product_ids'] ) ? array_map( 'absint', (array) $_POST['product_ids'] ) : array();
        $include_gallery = isset( $_POST['include_gallery'] ) && $_POST['include_gallery'] === '1';

        if ( empty( $product_ids ) ) {
            wp_send_json_error( array( 'message' => 'No product IDs provided' ) );
            return;
        }

        global $wpdb;
        $products_table = $wpdb->prefix . 'ggmc_products';

        // Prepare placeholders for the query.
        $placeholders = implode( ',', array_fill( 0, count( $product_ids ), '%d' ) );

        // Get image_id and gallery_ids for each component product.
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Placeholders are safely generated above
        $products = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT id, name, image_id, gallery_ids FROM {$products_table} WHERE id IN ({$placeholders})",
                $product_ids
            )
        );

        $images = array();
        $added_image_ids = array(); // Track to avoid duplicates

        foreach ( $products as $product ) {
            // Add primary image.
            if ( ! empty( $product->image_id ) && ! in_array( (int) $product->image_id, $added_image_ids, true ) ) {
                $image_url = wp_get_attachment_image_url( $product->image_id, 'medium' );
                if ( $image_url ) {
                    $images[] = array(
                        'id'           => (int) $product->image_id,
                        'url'          => $image_url,
                        'product_id'   => (int) $product->id,
                        'product_name' => $product->name,
                        'type'         => 'primary',
                    );
                    $added_image_ids[] = (int) $product->image_id;
                }
            }

            // Add gallery images if requested.
            if ( $include_gallery && ! empty( $product->gallery_ids ) ) {
                $gallery_ids = array_filter( array_map( 'trim', explode( ',', $product->gallery_ids ) ) );
                foreach ( $gallery_ids as $gallery_image_id ) {
                    $gallery_image_id = (int) $gallery_image_id;
                    if ( $gallery_image_id > 0 && ! in_array( $gallery_image_id, $added_image_ids, true ) ) {
                        $image_url = wp_get_attachment_image_url( $gallery_image_id, 'medium' );
                        if ( $image_url ) {
                            $images[] = array(
                                'id'           => $gallery_image_id,
                                'url'          => $image_url,
                                'product_id'   => (int) $product->id,
                                'product_name' => $product->name,
                                'type'         => 'gallery',
                            );
                            $added_image_ids[] = $gallery_image_id;
                        }
                    }
                }
            }
        }

        wp_send_json_success( array( 'images' => $images ) );
    }

    /**
     * AJAX handler for generating product variations.
     */
    public function ajax_generate_variations() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $product_id = isset( $_POST['product_id'] ) ? intval( $_POST['product_id'] ) : 0;

        if ( ! $product_id ) {
            wp_send_json_error( 'Invalid product ID' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        $variations_manager = GGM_Commerce_Variations::instance();

        // Ensure product has variations enabled
        if ( ! $variations_manager->product_has_variations( $product_id ) ) {
            wp_send_json_error( 'Product does not have variations enabled' );
        }

        // Generate variations
        $created_ids = $variations_manager->bulk_generate_variations( $product_id );

        wp_send_json_success( array(
            'message'     => sprintf( 'Generated %d variations', count( $created_ids ) ),
            'created_ids' => $created_ids,
        ) );
    }

    /**
     * AJAX handler for deleting a product variation.
     */
    public function ajax_delete_product_variation() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $variation_id = isset( $_POST['variation_id'] ) ? intval( $_POST['variation_id'] ) : 0;

        if ( ! $variation_id ) {
            wp_send_json_error( 'Invalid variation ID' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        $variations_manager = GGM_Commerce_Variations::instance();
        $result = $variations_manager->delete_variation( $variation_id );

        if ( $result ) {
            wp_send_json_success( array( 'message' => 'Variation deleted successfully' ) );
        } else {
            wp_send_json_error( 'Failed to delete variation' );
        }
    }

    /**
     * AJAX handler for auto-generating variation SKUs.
     */
    public function ajax_autogenerate_variation_skus() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $product_id = isset( $_POST['product_id'] ) ? intval( $_POST['product_id'] ) : 0;

        if ( ! $product_id ) {
            wp_send_json_error( 'Invalid product ID' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        global $wpdb;

        // Get product SKU as base
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $product_sku = $wpdb->get_var( $wpdb->prepare(
            "SELECT sku FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ) );

        if ( empty( $product_sku ) ) {
            $product_sku = 'PROD-' . $product_id;
        }

        $variations_manager = GGM_Commerce_Variations::instance();
        $variations = $variations_manager->get_variations( $product_id );

        $updated_count = 0;

        foreach ( $variations as $variation ) {
            // Build SKU suffix from attribute values
            $attr_codes = array();
            foreach ( $variation['attributes'] as $attr ) {
                // Get first 3 chars of attribute value, uppercase
                $code = strtoupper( substr( preg_replace( '/[^a-zA-Z0-9]/', '', $attr['attribute_value'] ), 0, 3 ) );
                $attr_codes[] = $code;
            }

            $variation_sku = $product_sku . '-' . implode( '-', $attr_codes );

            // Update variation SKU
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $result = $wpdb->update(
                $wpdb->prefix . 'ggmc_product_variations',
                array( 'sku' => $variation_sku ),
                array( 'id' => $variation['id'] ),
                array( '%s' ),
                array( '%d' )
            );

            if ( false !== $result ) {
                $updated_count++;
            }
        }

        wp_send_json_success( array(
            'message' => sprintf( 'Generated SKUs for %d variations', $updated_count ),
            'count'   => $updated_count,
        ) );
    }

    /**
     * AJAX handler for getting variation details.
     */
    public function ajax_get_variation_details() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $variation_id = isset( $_POST['variation_id'] ) ? intval( $_POST['variation_id'] ) : 0;

        if ( ! $variation_id ) {
            wp_send_json_error( 'Invalid variation ID' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        global $wpdb;

        // Get variation details
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $variation = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}ggmc_product_variations WHERE id = %d",
            $variation_id
        ), ARRAY_A );

        if ( ! $variation ) {
            wp_send_json_error( 'Variation not found' );
        }

        // Get type values
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $type_values = $wpdb->get_results( $wpdb->prepare(
            "SELECT vtv.*, vt.name AS type_name
             FROM {$wpdb->prefix}ggmc_variation_type_values vtv
             JOIN {$wpdb->prefix}ggmc_variation_types vt ON vt.id = vtv.variation_type_id
             WHERE vtv.variation_id = %d",
            $variation_id
        ), ARRAY_A );

        $variation['attributes'] = $type_values;

        // Get image URL if set
        if ( ! empty( $variation['image_id'] ) ) {
            $variation['image_url'] = wp_get_attachment_image_url( $variation['image_id'], 'thumbnail' );
        }

        // Get gallery image URLs if set
        if ( ! empty( $variation['gallery_ids'] ) ) {
            $gallery_ids = array_map( 'intval', explode( ',', $variation['gallery_ids'] ) );
            $gallery_urls = array();
            foreach ( $gallery_ids as $gid ) {
                if ( $gid > 0 ) {
                    $url = wp_get_attachment_image_url( $gid, 'thumbnail' );
                    if ( $url ) {
                        $gallery_urls[] = array( 'id' => $gid, 'url' => $url );
                    }
                }
            }
            $variation['gallery_images'] = $gallery_urls;
        }

        wp_send_json_success( $variation );
    }

    /**
     * AJAX handler for updating a variation.
     */
    public function ajax_update_variation() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $variation_id = isset( $_POST['variation_id'] ) ? intval( $_POST['variation_id'] ) : 0;

        if ( ! $variation_id ) {
            wp_send_json_error( 'Invalid variation ID' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        global $wpdb;

        $update_data = array();
        $formats = array();

        // Collect fields to update
        if ( isset( $_POST['sku'] ) ) {
            $update_data['sku'] = sanitize_text_field( wp_unslash( $_POST['sku'] ) );
            $formats[] = '%s';
        }
        if ( isset( $_POST['price'] ) ) {
            $update_data['price'] = '' !== $_POST['price'] ? floatval( $_POST['price'] ) : null;
            $formats[] = null === $update_data['price'] ? null : '%f';
        }
        if ( isset( $_POST['sale_price'] ) ) {
            $update_data['sale_price'] = '' !== $_POST['sale_price'] ? floatval( $_POST['sale_price'] ) : null;
            $formats[] = null === $update_data['sale_price'] ? null : '%f';
        }
        if ( isset( $_POST['price_type'] ) ) {
            $update_data['price_type'] = sanitize_text_field( wp_unslash( $_POST['price_type'] ) );
            $formats[] = '%s';
        }
        if ( isset( $_POST['stock'] ) ) {
            $update_data['stock'] = '' !== $_POST['stock'] ? intval( $_POST['stock'] ) : null;
            $formats[] = null === $update_data['stock'] ? null : '%d';
        }
        if ( isset( $_POST['image_id'] ) ) {
            $update_data['image_id'] = '' !== $_POST['image_id'] ? intval( $_POST['image_id'] ) : null;
            $formats[] = null === $update_data['image_id'] ? null : '%d';
        }
        if ( isset( $_POST['gallery_ids'] ) ) {
            $update_data['gallery_ids'] = sanitize_text_field( wp_unslash( $_POST['gallery_ids'] ) );
            $formats[] = '%s';
        }
        if ( isset( $_POST['is_default'] ) ) {
            // If setting as default, first clear any existing defaults for this product
            if ( intval( $_POST['is_default'] ) === 1 ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $product_id = $wpdb->get_var( $wpdb->prepare(
                    "SELECT product_id FROM {$wpdb->prefix}ggmc_product_variations WHERE id = %d",
                    $variation_id
                ) );

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $wpdb->update(
                    $wpdb->prefix . 'ggmc_product_variations',
                    array( 'is_default' => 0 ),
                    array( 'product_id' => $product_id ),
                    array( '%d' ),
                    array( '%d' )
                );
            }
            $update_data['is_default'] = intval( $_POST['is_default'] );
            $formats[] = '%d';
        }

        if ( empty( $update_data ) ) {
            wp_send_json_error( 'No data to update' );
        }

        // Filter out null formats (for NULL values)
        $clean_formats = array_filter( $formats, function( $f ) { return null !== $f; } );

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->update(
            $wpdb->prefix . 'ggmc_product_variations',
            $update_data,
            array( 'id' => $variation_id ),
            $clean_formats,
            array( '%d' )
        );

        if ( false !== $result ) {
            wp_send_json_success( array( 'message' => 'Variation updated successfully' ) );
        } else {
            wp_send_json_error( 'Failed to update variation' );
        }
    }

    // =========================================================================
    // INDEPENDENT MODE OPTION AJAX HANDLERS
    // =========================================================================

    /**
     * AJAX handler for removing an Independent mode option from a product.
     */
    public function ajax_remove_independent_option() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $product_id = isset( $_POST['product_id'] ) ? intval( $_POST['product_id'] ) : 0;
        $attribute_id = isset( $_POST['attribute_id'] ) ? intval( $_POST['attribute_id'] ) : 0;
        $option_value = isset( $_POST['option_value'] ) ? sanitize_text_field( wp_unslash( $_POST['option_value'] ) ) : '';

        if ( ! $product_id || ! $attribute_id || '' === $option_value ) {
            wp_send_json_error( 'Invalid parameters' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        $variations_manager = GGM_Commerce_Variations::instance();

        // Delete the option
        $result = $variations_manager->delete_product_variation_option( $product_id, $attribute_id, $option_value );

        if ( ! $result ) {
            wp_send_json_error( 'Failed to remove option' );
        }

        // Ensure there's still a valid default
        $default_result = $variations_manager->ensure_valid_default( $product_id, $attribute_id );

        // Get updated missing options for the dropdown
        $missing_options = $variations_manager->get_missing_variation_options( $product_id, $attribute_id );

        wp_send_json_success( array(
            'message' => 'Option removed successfully',
            'default_changed' => $default_result['changed'],
            'new_default' => $default_result['new_default'],
            'missing_options' => $missing_options,
        ) );
    }

    /**
     * AJAX handler for adding an Independent mode option to a product.
     */
    public function ajax_add_independent_option() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $product_id = isset( $_POST['product_id'] ) ? intval( $_POST['product_id'] ) : 0;
        $attribute_id = isset( $_POST['attribute_id'] ) ? intval( $_POST['attribute_id'] ) : 0;
        $option_value = isset( $_POST['option_value'] ) ? sanitize_text_field( wp_unslash( $_POST['option_value'] ) ) : '';
        $modifier = isset( $_POST['modifier'] ) ? floatval( $_POST['modifier'] ) : 0;

        if ( ! $product_id || ! $attribute_id || '' === $option_value ) {
            wp_send_json_error( 'Invalid parameters' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        $variations_manager = GGM_Commerce_Variations::instance();

        // Add the option
        $option_id = $variations_manager->add_product_variation_option( $product_id, $attribute_id, $option_value, $modifier );

        if ( ! $option_id ) {
            wp_send_json_error( 'Failed to add option' );
        }

        // Get the newly added option details
        $options = $variations_manager->get_variation_options_for_product( $product_id, $attribute_id );
        $added_option = null;
        foreach ( $options as $opt ) {
            if ( $opt['option_value'] === $option_value ) {
                $added_option = $opt;
                break;
            }
        }

        // Get updated missing options
        $missing_options = $variations_manager->get_missing_variation_options( $product_id, $attribute_id );

        wp_send_json_success( array(
            'message' => 'Option added successfully',
            'option_id' => $option_id,
            'option' => $added_option,
            'missing_options' => $missing_options,
        ) );
    }

    /**
     * AJAX handler for adding all missing Independent mode options to a product.
     */
    public function ajax_add_all_missing_options() {
        check_ajax_referer( 'ggmc_variations', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        $product_id = isset( $_POST['product_id'] ) ? intval( $_POST['product_id'] ) : 0;
        $attribute_id = isset( $_POST['attribute_id'] ) ? intval( $_POST['attribute_id'] ) : 0;

        if ( ! $product_id || ! $attribute_id ) {
            wp_send_json_error( 'Invalid parameters' );
        }

        // Check if variations feature is activated
        if ( ! GGM_Commerce_License::instance()->is_widget_activated( 'product-variations' ) ) {
            wp_send_json_error( 'Product Variations feature is not activated' );
        }

        $variations_manager = GGM_Commerce_Variations::instance();

        // Add all missing options
        $added_count = $variations_manager->add_all_missing_options( $product_id, $attribute_id );

        // Get updated options list
        $options = $variations_manager->get_variation_options_for_product( $product_id, $attribute_id );

        wp_send_json_success( array(
            'message' => sprintf( '%d option(s) added successfully', $added_count ),
            'added_count' => $added_count,
            'options' => $options,
        ) );
    }

    /**
     * Product Variations admin page.
     * Manages variations (Color, Size, Material, etc.) for product variations.
     * Includes tabs for Variations and Presets.
     */
    public function variation_attributes_page() {
        global $title;
        $title = 'Product Variations';

        $variations_manager = GGM_Commerce_Variations::instance();
        $variation_attrs = GGM_Commerce_Variation_Attributes::get_instance();

        // Determine active tab
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $active_tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'variations';
        // Support legacy 'attributes' tab name
        if ( 'attributes' === $active_tab ) {
            $active_tab = 'variations';
        }
        // Redirect 'suggestions' to 'presets'
        if ( 'suggestions' === $active_tab ) {
            $active_tab = 'presets';
        }

        // Handle form submissions
        $message = '';
        $message_type = '';

        // Process form actions
        if ( isset( $_POST['action'] ) && isset( $_POST['_wpnonce'] ) ) {
            $nonce = sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) );

            if ( wp_verify_nonce( $nonce, 'ggmc_variation_attributes' ) ) {
                $action = sanitize_text_field( wp_unslash( $_POST['action'] ) );

                if ( 'create' === $action ) {
                    $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
                    $attribute_type = isset( $_POST['attribute_type'] ) ? sanitize_key( wp_unslash( $_POST['attribute_type'] ) ) : 'select';
                    $options_raw = isset( $_POST['options'] ) ? wp_unslash( $_POST['options'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized

                    // Parse options based on type
                    $options = array();
                    if ( ! empty( $options_raw ) ) {
                        $lines = explode( "\n", $options_raw );
                        foreach ( $lines as $line ) {
                            $line = trim( $line );
                            if ( empty( $line ) ) {
                                continue;
                            }

                            // Parse format: value|label|color/image (color/image optional)
                            $parts = array_map( 'trim', explode( '|', $line ) );
                            $option = array(
                                'value' => sanitize_text_field( $parts[0] ),
                                'label' => sanitize_text_field( $parts[0] ),
                            );

                            if ( isset( $parts[1] ) && ! empty( $parts[1] ) ) {
                                $option['label'] = sanitize_text_field( $parts[1] );
                            }

                            if ( isset( $parts[2] ) && ! empty( $parts[2] ) ) {
                                if ( 'color' === $attribute_type ) {
                                    $option['color'] = sanitize_hex_color( $parts[2] );
                                } elseif ( 'image' === $attribute_type ) {
                                    $option['image'] = esc_url_raw( $parts[2] );
                                }
                            }

                            $options[] = $option;
                        }
                    }

                    $result = $variations_manager->create_variation_type( array(
                        'name'       => $name,
                        'input_type' => $attribute_type,
                        'options'    => $options,
                    ) );

                    if ( $result ) {
                        $message = 'Variation created successfully.';
                        $message_type = 'success';
                    } else {
                        $message = 'Failed to create variation.';
                        $message_type = 'error';
                    }
                } elseif ( 'update' === $action ) {
                    $id = isset( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;
                    $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
                    $attribute_type = isset( $_POST['attribute_type'] ) ? sanitize_key( wp_unslash( $_POST['attribute_type'] ) ) : 'select';
                    $options_raw = isset( $_POST['options'] ) ? wp_unslash( $_POST['options'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                    $status = isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : 'active';

                    // Parse options
                    $options = array();
                    if ( ! empty( $options_raw ) ) {
                        $lines = explode( "\n", $options_raw );
                        foreach ( $lines as $line ) {
                            $line = trim( $line );
                            if ( empty( $line ) ) {
                                continue;
                            }

                            $parts = array_map( 'trim', explode( '|', $line ) );
                            $option = array(
                                'value' => sanitize_text_field( $parts[0] ),
                                'label' => sanitize_text_field( $parts[0] ),
                            );

                            if ( isset( $parts[1] ) && ! empty( $parts[1] ) ) {
                                $option['label'] = sanitize_text_field( $parts[1] );
                            }

                            if ( isset( $parts[2] ) && ! empty( $parts[2] ) ) {
                                if ( 'color' === $attribute_type ) {
                                    $option['color'] = sanitize_hex_color( $parts[2] );
                                } elseif ( 'image' === $attribute_type ) {
                                    $option['image'] = esc_url_raw( $parts[2] );
                                }
                            }

                            $options[] = $option;
                        }
                    }

                    $result = $variations_manager->update_variation_type( $id, array(
                        'name'       => $name,
                        'input_type' => $attribute_type,
                        'options'    => $options,
                        'status'     => $status,
                    ) );

                    if ( $result ) {
                        $message = 'Variation updated successfully.';
                        $message_type = 'success';
                    } else {
                        $message = 'Failed to update variation.';
                        $message_type = 'error';
                    }
                } elseif ( 'delete' === $action ) {
                    $id = isset( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;
                    $result = $variation_attrs->delete_attribute( $id ); // Use variation_attrs to also remove from groups

                    if ( $result ) {
                        $message = 'Variation deleted successfully.';
                        $message_type = 'success';
                    } else {
                        $message = 'Failed to delete variation.';
                        $message_type = 'error';
                    }
                } elseif ( 'create_group' === $action ) {
                    $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
                    $description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';

                    $result = $variation_attrs->create_group( array(
                        'name'        => $name,
                        'description' => $description,
                    ) );

                    if ( ! is_wp_error( $result ) ) {
                        $message = 'Group created successfully.';
                        $message_type = 'success';
                    } else {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    }
                } elseif ( 'update_group' === $action ) {
                    $id = isset( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;
                    $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
                    $description = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';
                    $attribute_ids = isset( $_POST['attribute_ids'] ) ? array_map( 'intval', (array) $_POST['attribute_ids'] ) : array();

                    $result = $variation_attrs->update_group( $id, array(
                        'name'        => $name,
                        'description' => $description,
                    ) );

                    // Update group members
                    $variation_attrs->set_group_attributes( $id, $attribute_ids );

                    if ( ! is_wp_error( $result ) ) {
                        $message = 'Group updated successfully.';
                        $message_type = 'success';
                    } else {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    }
                } elseif ( 'delete_group' === $action ) {
                    $id = isset( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;
                    $result = $variation_attrs->delete_group( $id );

                    if ( ! is_wp_error( $result ) ) {
                        $message = 'Group deleted successfully.';
                        $message_type = 'success';
                    } else {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    }
                } elseif ( 'install_suggestion' === $action ) {
                    $suggestion_key = isset( $_POST['suggestion_key'] ) ? sanitize_key( $_POST['suggestion_key'] ) : '';
                    $result = $variation_attrs->install_suggestion( $suggestion_key );

                    if ( ! is_wp_error( $result ) ) {
                        $message = 'Suggestion installed successfully! The group is now available in the Groups tab.';
                        $message_type = 'success';
                    } else {
                        $message = $result->get_error_message();
                        $message_type = 'error';
                    }
                }
            }
        }

        // Get all variation types
        $attributes = $variations_manager->get_variation_types( array( 'status' => 'all' ) );

        // Get all groups (excluding suggestion-created ones from groups list, show them separately)
        $groups = $variation_attrs->get_groups( array( 'status' => 'all' ) );

        // Check if editing variation
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $editing_id = isset( $_GET['edit'] ) ? intval( $_GET['edit'] ) : 0;
        $editing_attr = $editing_id && 'variations' === $active_tab ? $variations_manager->get_variation_type( $editing_id ) : null;

        // Get suggestions
        $suggestions = $variation_attrs->get_suggestions();

        ?>
        <div class="wrap ggmc-admin-wrap">
            <?php self::page_title( $title ); ?>

            <?php if ( $message ) : ?>
                <div class="notice notice-<?php echo esc_attr( $message_type ); ?> is-dismissible">
                    <p><?php echo esc_html( $message ); ?></p>
                </div>
            <?php endif; ?>

            <!-- Tab Navigation -->
            <nav class="nav-tab-wrapper">
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=variations' ) ); ?>"
                   class="nav-tab <?php echo 'variations' === $active_tab ? 'nav-tab-active' : ''; ?>">
                    Variations
                </a>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=presets' ) ); ?>"
                   class="nav-tab <?php echo 'presets' === $active_tab ? 'nav-tab-active' : ''; ?>">
                    Presets
                </a>
            </nav>

            <?php if ( 'variations' === $active_tab ) : ?>
                <!-- VARIATIONS TAB -->
                <?php $this->render_variation_attributes_tab( $attributes, $editing_attr ); ?>

            <?php elseif ( 'presets' === $active_tab ) : ?>
                <!-- PRESETS TAB -->
                <?php $this->render_variation_suggestions_tab( $suggestions, $variation_attrs ); ?>

            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render the Attributes tab content.
     *
     * @param array      $attributes   All variation attributes.
     * @param array|null $editing_attr Attribute being edited.
     */
    private function render_variation_attributes_tab( $attributes, $editing_attr ) {
        ?>
        <!-- Import/Export Section for Variation Types -->
        <div class="ggmc-import-export-section" style="margin: 0 0 20px 0; padding: 15px; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px;">
            <div style="display: flex; gap: 20px; align-items: flex-start; flex-wrap: wrap;">
                <div class="ggmc-export-section">
                    <strong style="display: block; margin-bottom: 8px;">Export Variation Types</strong>
                    <button type="button" class="button ggmc-export-btn" data-type="variation_types" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                        <span class="dashicons dashicons-download" style="margin-top: 4px;"></span> Export CSV
                    </button>
                    <button type="button" class="button ggmc-template-btn" data-type="variation_types" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                        <span class="dashicons dashicons-media-spreadsheet" style="margin-top: 4px;"></span> Download Template
                    </button>
                </div>
                <div class="ggmc-import-section">
                    <strong style="display: block; margin-bottom: 8px;">Import Variation Types</strong>
                    <form id="ggmc-import-variation-types-form" enctype="multipart/form-data" style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                        <input type="file" name="file" accept=".csv" required style="max-width: 200px;">
                        <select name="duplicate_handling">
                            <option value="skip">Skip existing</option>
                            <option value="update">Update existing</option>
                            <option value="create">Create new</option>
                        </select>
                        <button type="submit" class="button button-primary ggmc-import-btn" data-type="variation_types" data-nonce="<?php echo esc_attr( wp_create_nonce( 'ggmc_import_export' ) ); ?>">
                            <span class="dashicons dashicons-upload" style="margin-top: 4px;"></span> Import
                        </button>
                    </form>
                    <div class="ggmc-import-progress" style="display: none; margin-top: 10px;">
                        <div class="ggmc-progress-bar" style="background: #e0e0e0; height: 20px; border-radius: 4px; overflow: hidden;">
                            <div class="ggmc-progress-fill" style="background: #0073aa; height: 100%; width: 0%; transition: width 0.3s;"></div>
                        </div>
                        <div class="ggmc-progress-text" style="margin-top: 5px; font-size: 12px; color: #666;"></div>
                    </div>
                    <div class="ggmc-import-result" style="display: none; margin-top: 10px; padding: 10px; border-radius: 4px;"></div>
                </div>
            </div>
        </div>

        <div class="ggmc-variation-attributes-wrapper" style="display: flex; gap: 30px;">
            <!-- Add/Edit Form -->
            <div class="ggmc-variation-attr-form" style="flex: 0 0 350px;">
                <div class="postbox">
                    <h2 class="hndle" style="cursor: default;">
                        <span><?php echo $editing_attr ? 'Edit Variation' : 'Add New Variation'; ?></span>
                    </h2>
                    <div class="inside">
                        <form method="post" action="">
                            <?php wp_nonce_field( 'ggmc_variation_attributes' ); ?>
                            <input type="hidden" name="action" value="<?php echo $editing_attr ? 'update' : 'create'; ?>">
                            <?php if ( $editing_attr ) : ?>
                                <input type="hidden" name="id" value="<?php echo esc_attr( $editing_attr['id'] ); ?>">
                            <?php endif; ?>

                            <table class="form-table">
                                <tr>
                                    <th><label for="name">Name <span style="color:red;">*</span></label></th>
                                    <td>
                                        <input type="text" name="name" id="name" class="regular-text" required
                                               value="<?php echo esc_attr( $editing_attr['name'] ?? '' ); ?>"
                                               placeholder="e.g., Color, Size, Material">
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="attribute_type">Type</label></th>
                                    <td>
                                        <select name="attribute_type" id="attribute_type">
                                            <option value="select" <?php selected( $editing_attr['input_type'] ?? '', 'select' ); ?>>Dropdown Select</option>
                                            <option value="button" <?php selected( $editing_attr['input_type'] ?? '', 'button' ); ?>>Button/Pill</option>
                                            <option value="color" <?php selected( $editing_attr['input_type'] ?? '', 'color' ); ?>>Color Swatch</option>
                                            <option value="image" <?php selected( $editing_attr['input_type'] ?? '', 'image' ); ?>>Image Swatch</option>
                                        </select>
                                        <p class="description">How options display on frontend.</p>
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="options">Options</label></th>
                                    <td>
                                        <?php
                                        $options_text = '';
                                        $options_data = array();
                                        if ( ! empty( $editing_attr['options'] ) ) {
                                            foreach ( $editing_attr['options'] as $opt ) {
                                                $line = $opt['value'] ?? '';
                                                if ( isset( $opt['label'] ) && $opt['label'] !== $opt['value'] ) {
                                                    $line .= '|' . $opt['label'];
                                                }
                                                if ( isset( $opt['color'] ) ) {
                                                    $line .= '|' . $opt['color'];
                                                } elseif ( isset( $opt['image'] ) ) {
                                                    $line .= '|' . $opt['image'];
                                                }
                                                $options_text .= $line . "\n";
                                                $options_data[] = $opt;
                                            }
                                        }
                                        ?>
                                        <!-- Text-based options (for select/button types) -->
                                        <div id="ggmc-options-text-wrapper">
                                            <textarea name="options" id="options" rows="8" class="large-text"
                                                      placeholder="red|Red|#ff0000&#10;blue|Blue|#0000ff&#10;green|Green|#00ff00"><?php echo esc_textarea( trim( $options_text ) ); ?></textarea>
                                            <p class="description">
                                                One option per line. Format: <code>value|Label|color</code>
                                            </p>
                                        </div>

                                        <!-- Color picker options (for color type) -->
                                        <div id="ggmc-color-options-wrapper" style="display: none;">
                                            <div id="ggmc-color-options-list">
                                                <!-- Color options will be added here dynamically -->
                                            </div>
                                            <button type="button" id="ggmc-add-color-option" class="button" style="margin-top: 10px;">
                                                <span class="dashicons dashicons-plus-alt2" style="vertical-align: middle; margin-right: 4px;"></span>
                                                Add Color Option
                                            </button>
                                            <p class="description" style="margin-top: 8px;">
                                                Click the color swatch to pick a color, or enter a hex code directly.
                                            </p>
                                        </div>
                                    </td>
                                </tr>
                                <script>
                                (function($) {
                                    $(document).ready(function() {
                                        var existingOptions = <?php echo wp_json_encode( $options_data ); ?>;
                                        var $typeSelect = $('#attribute_type');
                                        var $textWrapper = $('#ggmc-options-text-wrapper');
                                        var $colorWrapper = $('#ggmc-color-options-wrapper');
                                        var $colorList = $('#ggmc-color-options-list');
                                        var $textarea = $('#options');

                                        // Color option template
                                        function createColorOption(value, label, color) {
                                            value = value || '';
                                            label = label || '';
                                            color = color || '#3498db';

                                            var $row = $('<div class="ggmc-color-option-row" style="display: flex; gap: 8px; align-items: center; margin-bottom: 8px; padding: 8px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;"></div>');

                                            // Color picker input
                                            var $colorInput = $('<input type="text" class="ggmc-color-picker" value="' + color + '" style="width: 80px;">');

                                            // Value input
                                            var $valueInput = $('<input type="text" class="ggmc-option-value" placeholder="Value (e.g., red)" value="' + value + '" style="width: 100px;">');

                                            // Label input
                                            var $labelInput = $('<input type="text" class="ggmc-option-label" placeholder="Label (e.g., Red)" value="' + label + '" style="width: 100px;">');

                                            // Remove button
                                            var $removeBtn = $('<button type="button" class="button ggmc-remove-color-option" title="Remove"><span class="dashicons dashicons-trash" style="vertical-align: middle;"></span></button>');

                                            $row.append($colorInput);
                                            $row.append($valueInput);
                                            $row.append($labelInput);
                                            $row.append($removeBtn);

                                            $colorList.append($row);

                                            // Initialize WordPress color picker
                                            $colorInput.wpColorPicker({
                                                change: function() {
                                                    syncColorOptionsToTextarea();
                                                },
                                                clear: function() {
                                                    syncColorOptionsToTextarea();
                                                }
                                            });

                                            return $row;
                                        }

                                        // Sync color options to textarea (for form submission)
                                        function syncColorOptionsToTextarea() {
                                            var lines = [];
                                            $colorList.find('.ggmc-color-option-row').each(function() {
                                                var $row = $(this);
                                                var value = $row.find('.ggmc-option-value').val().trim();
                                                var label = $row.find('.ggmc-option-label').val().trim();
                                                var color = $row.find('.ggmc-color-picker').val().trim();

                                                if (value) {
                                                    var line = value;
                                                    if (label && label !== value) {
                                                        line += '|' + label;
                                                    } else if (color) {
                                                        line += '|' + value; // Use value as label if not specified
                                                    }
                                                    if (color) {
                                                        line += '|' + color;
                                                    }
                                                    lines.push(line);
                                                }
                                            });
                                            $textarea.val(lines.join('\n'));
                                        }

                                        // Parse textarea to color options
                                        function parseTextareaToColorOptions() {
                                            $colorList.empty();
                                            var text = $textarea.val().trim();
                                            if (!text) {
                                                // Add one empty row
                                                createColorOption('', '', '#3498db');
                                                return;
                                            }

                                            var lines = text.split('\n');
                                            lines.forEach(function(line) {
                                                line = line.trim();
                                                if (!line) return;

                                                var parts = line.split('|');
                                                var value = parts[0] || '';
                                                var label = parts[1] || value;
                                                var color = parts[2] || '#3498db';

                                                createColorOption(value, label, color);
                                            });

                                            if ($colorList.children().length === 0) {
                                                createColorOption('', '', '#3498db');
                                            }
                                        }

                                        // Toggle between text and color UI based on type
                                        function toggleOptionsUI() {
                                            var type = $typeSelect.val();
                                            if (type === 'color') {
                                                $textWrapper.hide();
                                                $colorWrapper.show();
                                                parseTextareaToColorOptions();
                                            } else {
                                                // Sync back to textarea before hiding
                                                if ($colorWrapper.is(':visible')) {
                                                    syncColorOptionsToTextarea();
                                                }
                                                $colorWrapper.hide();
                                                $textWrapper.show();
                                            }
                                        }

                                        // Event handlers
                                        $typeSelect.on('change', toggleOptionsUI);

                                        $('#ggmc-add-color-option').on('click', function() {
                                            createColorOption('', '', '#3498db');
                                            syncColorOptionsToTextarea();
                                        });

                                        $colorList.on('click', '.ggmc-remove-color-option', function() {
                                            $(this).closest('.ggmc-color-option-row').remove();
                                            syncColorOptionsToTextarea();
                                        });

                                        $colorList.on('input', '.ggmc-option-value, .ggmc-option-label', function() {
                                            syncColorOptionsToTextarea();
                                        });

                                        // Sync before form submit
                                        $('form').on('submit', function() {
                                            if ($typeSelect.val() === 'color') {
                                                syncColorOptionsToTextarea();
                                            }
                                        });

                                        // Initialize on page load
                                        toggleOptionsUI();
                                    });
                                })(jQuery);
                                </script>
                                <?php if ( $editing_attr ) : ?>
                                    <tr>
                                        <th><label for="status">Status</label></th>
                                        <td>
                                            <select name="status" id="status">
                                                <option value="active" <?php selected( $editing_attr['status'] ?? '', 'active' ); ?>>Active</option>
                                                <option value="inactive" <?php selected( $editing_attr['status'] ?? '', 'inactive' ); ?>>Inactive</option>
                                            </select>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary">
                                    <?php echo $editing_attr ? 'Update Attribute' : 'Add Attribute'; ?>
                                </button>
                                <?php if ( $editing_attr ) : ?>
                                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=attributes' ) ); ?>" class="button">Cancel</a>
                                <?php endif; ?>
                            </p>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Variations List -->
            <div class="ggmc-variation-attr-list" style="flex: 1;">
                <div class="postbox">
                    <h2 class="hndle" style="cursor: default;"><span>Variations</span></h2>
                    <div class="inside">
                        <?php if ( empty( $attributes ) ) : ?>
                            <p>No variations found. Create your first one or install from Presets.</p>
                        <?php else : ?>
                            <form id="ggmc-variations-bulk-form" method="post">
                                <?php wp_nonce_field( 'ggmc_bulk_variations_action', 'ggmc_variations_bulk_nonce' ); ?>
                                <div class="tablenav top" style="margin-bottom: 10px;">
                                    <div class="alignleft actions bulkactions">
                                        <select name="bulk_action" id="bulk-action-selector-variations">
                                            <option value="">Bulk Actions</option>
                                            <option value="set_active">Set Active</option>
                                            <option value="set_inactive">Set Inactive</option>
                                            <option value="delete">Delete</option>
                                        </select>
                                        <button type="button" id="ggmc-apply-variations-bulk-action" class="button action">Apply</button>
                                        <span id="ggmc-variations-selected-count" style="margin-left: 10px; font-weight: 500;"></span>
                                    </div>
                                </div>
                                <table class="wp-list-table widefat fixed striped">
                                    <thead>
                                        <tr>
                                            <td class="manage-column column-cb check-column" style="width: 30px;">
                                                <input type="checkbox" id="cb-select-all-variations">
                                            </td>
                                            <th style="width: 22%;">Name</th>
                                            <th style="width: 10%;">Type</th>
                                            <th style="width: 38%;">Options</th>
                                            <th style="width: 10%;">Status</th>
                                            <th style="width: 12%;">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ( $attributes as $attr ) : ?>
                                            <tr>
                                                <th scope="row" class="check-column">
                                                    <input type="checkbox" class="ggmc-bulk-checkbox" value="<?php echo esc_attr( $attr['id'] ); ?>">
                                                </th>
                                                <td>
                                                    <strong><?php echo esc_html( $attr['name'] ); ?></strong>
                                                    <br><code style="font-size: 11px;"><?php echo esc_html( $attr['slug'] ); ?></code>
                                                </td>
                                            <td>
                                                <?php
                                                $type_labels = array(
                                                    'select' => 'Dropdown',
                                                    'button' => 'Button',
                                                    'color'  => 'Color',
                                                    'image'  => 'Image',
                                                );
                                                $input_type = $attr['input_type'] ?? 'select';
                                                echo esc_html( $type_labels[ $input_type ] ?? ucfirst( $input_type ) );
                                                ?>
                                            </td>
                                            <td>
                                                <?php if ( ! empty( $attr['options'] ) ) : ?>
                                                    <div style="display: flex; flex-wrap: wrap; gap: 4px;">
                                                        <?php foreach ( array_slice( $attr['options'], 0, 5 ) as $opt ) : ?>
                                                            <?php
                                                            $label = $opt['label'] ?? $opt['value'] ?? '';
                                                            ?>
                                                            <?php if ( 'color' === $input_type && ! empty( $opt['color'] ) ) : ?>
                                                                <span style="display: inline-flex; align-items: center; gap: 3px; font-size: 12px;">
                                                                    <span style="width: 14px; height: 14px; border-radius: 3px; border: 1px solid #ccc; background: <?php echo esc_attr( $opt['color'] ); ?>;"></span>
                                                                    <?php echo esc_html( $label ); ?>
                                                                </span>
                                                            <?php else : ?>
                                                                <span class="button button-small" style="pointer-events: none; font-size: 11px; padding: 0 6px; min-height: 24px; line-height: 22px;"><?php echo esc_html( $label ); ?></span>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                        <?php if ( count( $attr['options'] ) > 5 ) : ?>
                                                            <span style="color: #666; font-size: 12px;">+<?php echo count( $attr['options'] ) - 5; ?> more</span>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php else : ?>
                                                    <em style="color: #999;">No options</em>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ( 'active' === $attr['status'] ) : ?>
                                                    <span style="color: green;">Active</span>
                                                <?php else : ?>
                                                    <span style="color: #999;">Inactive</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=variations&edit=' . $attr['id'] ) ); ?>"
                                                   class="button button-small">Edit</a>
                                                <button type="button" class="button button-small button-link-delete ggmc-delete-variation-attr"
                                                        data-id="<?php echo esc_attr( $attr['id'] ); ?>"
                                                        data-name="<?php echo esc_attr( $attr['name'] ); ?>">Delete</button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            </form>
                            <!-- Standalone delete form for individual deletes -->
                            <form id="ggmc-variation-attr-delete-form" method="post" action="" style="display: none;">
                                <?php wp_nonce_field( 'ggmc_variation_attributes' ); ?>
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" id="ggmc-variation-attr-delete-id" value="">
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render the Groups tab content.
     *
     * @param array                              $groups             All groups.
     * @param array                              $attributes         All attributes.
     * @param object|null                        $editing_group      Group being edited.
     * @param array                              $editing_group_attrs Attributes in editing group.
     * @param GGM_Commerce_Variation_Attributes $variation_attrs    Variation attributes instance.
     */
    private function render_variation_groups_tab( $groups, $attributes, $editing_group, $editing_group_attrs, $variation_attrs ) {
        $editing_attr_ids = array_column( $editing_group_attrs, 'id' );
        ?>
        <div class="ggmc-variation-groups-wrapper" style="display: flex; gap: 30px;">
            <!-- Add/Edit Form -->
            <div class="ggmc-variation-group-form" style="flex: 0 0 400px;">
                <div class="postbox">
                    <h2 class="hndle" style="cursor: default;">
                        <span><?php echo $editing_group ? 'Edit Group' : 'Add New Group'; ?></span>
                    </h2>
                    <div class="inside">
                        <form method="post" action="">
                            <?php wp_nonce_field( 'ggmc_variation_attributes' ); ?>
                            <input type="hidden" name="action" value="<?php echo $editing_group ? 'update_group' : 'create_group'; ?>">
                            <?php if ( $editing_group ) : ?>
                                <input type="hidden" name="id" value="<?php echo esc_attr( $editing_group->id ); ?>">
                            <?php endif; ?>

                            <table class="form-table">
                                <tr>
                                    <th><label for="name">Name <span style="color:red;">*</span></label></th>
                                    <td>
                                        <input type="text" name="name" id="name" class="regular-text" required
                                               value="<?php echo esc_attr( $editing_group->name ?? '' ); ?>"
                                               placeholder="e.g., T-Shirt Variations">
                                    </td>
                                </tr>
                                <tr>
                                    <th><label for="description">Description</label></th>
                                    <td>
                                        <textarea name="description" id="description" rows="3" class="large-text"
                                                  placeholder="Optional description"><?php echo esc_textarea( $editing_group->description ?? '' ); ?></textarea>
                                    </td>
                                </tr>
                                <?php if ( $editing_group && ! empty( $attributes ) ) : ?>
                                    <tr>
                                        <th><label>Attributes in Group</label></th>
                                        <td>
                                            <div style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; background: #fafafa;">
                                                <?php foreach ( $attributes as $attr ) : ?>
                                                    <label style="display: block; margin-bottom: 5px;">
                                                        <input type="checkbox" name="attribute_ids[]"
                                                               value="<?php echo esc_attr( $attr['id'] ); ?>"
                                                               <?php checked( in_array( $attr['id'], $editing_attr_ids, true ) ); ?>>
                                                        <?php echo esc_html( $attr['name'] ); ?>
                                                        <span style="color: #666; font-size: 11px;">(<?php echo count( $attr['options'] ); ?> options)</span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                            <p class="description">Select which attributes belong to this group.</p>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </table>

                            <p class="submit">
                                <button type="submit" class="button button-primary">
                                    <?php echo $editing_group ? 'Update Group' : 'Create Group'; ?>
                                </button>
                                <?php if ( $editing_group ) : ?>
                                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=groups' ) ); ?>" class="button">Cancel</a>
                                <?php endif; ?>
                            </p>
                        </form>

                        <?php if ( ! $editing_group && empty( $attributes ) ) : ?>
                            <div class="notice notice-info inline" style="margin: 15px 0 0;">
                                <p>Create some attributes first in the <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=attributes' ) ); ?>">Attributes tab</a> or install from <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=suggestions' ) ); ?>">Suggestions</a>.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Groups List -->
            <div class="ggmc-variation-groups-list" style="flex: 1;">
                <div class="postbox">
                    <h2 class="hndle" style="cursor: default;"><span>Variation Attribute Groups</span></h2>
                    <div class="inside">
                        <?php if ( empty( $groups ) ) : ?>
                            <p>No groups found. Create your first group or install from <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=suggestions' ) ); ?>">Suggestions</a>.</p>
                        <?php else : ?>
                            <table class="wp-list-table widefat fixed striped">
                                <thead>
                                    <tr>
                                        <th style="width: 25%;">Name</th>
                                        <th style="width: 30%;">Description</th>
                                        <th style="width: 30%;">Attributes</th>
                                        <th style="width: 15%;">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ( $groups as $group ) :
                                        $group_attrs = $variation_attrs->get_group_attributes( $group->id );
                                    ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo esc_html( $group->name ); ?></strong>
                                                <?php if ( $group->is_suggestion ) : ?>
                                                    <br><span style="background: #e0e0ff; padding: 1px 6px; border-radius: 3px; font-size: 10px;">From Suggestions</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php echo esc_html( $group->description ?: '-' ); ?>
                                            </td>
                                            <td>
                                                <?php if ( ! empty( $group_attrs ) ) : ?>
                                                    <?php
                                                    $attr_names = array_column( $group_attrs, 'name' );
                                                    echo esc_html( implode( ', ', $attr_names ) );
                                                    ?>
                                                <?php else : ?>
                                                    <em style="color: #999;">No attributes</em>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=groups&edit_group=' . $group->id ) ); ?>"
                                                   class="button button-small">Edit</a>
                                                <form method="post" action="" style="display: inline;"
                                                      onsubmit="return confirm('Delete this group? (Attributes will not be deleted)');">
                                                    <?php wp_nonce_field( 'ggmc_variation_attributes' ); ?>
                                                    <input type="hidden" name="action" value="delete_group">
                                                    <input type="hidden" name="id" value="<?php echo esc_attr( $group->id ); ?>">
                                                    <button type="submit" class="button button-small button-link-delete">Delete</button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Help Section -->
                <div class="postbox" style="margin-top: 20px;">
                    <h2 class="hndle" style="cursor: default;"><span>How to Use Groups</span></h2>
                    <div class="inside">
                        <ol style="margin-left: 20px;">
                            <li><strong>Create a group</strong> - Give it a descriptive name like "T-Shirt Options"</li>
                            <li><strong>Add attributes</strong> - Edit the group and check which attributes belong to it</li>
                            <li><strong>Use on products</strong> - When editing a product, use "Add from Group" to quickly add all attributes from the group</li>
                        </ol>
                        <p><strong>Tip:</strong> Install pre-made groups from the <a href="<?php echo esc_url( admin_url( 'admin.php?page=ggmc-variation-attributes&tab=suggestions' ) ); ?>">Suggestions tab</a> for common variation types!</p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render the Presets tab content.
     *
     * @param array                              $suggestions      Available presets.
     * @param GGM_Commerce_Variation_Attributes $variation_attrs Variation attributes instance.
     */
    private function render_variation_suggestions_tab( $suggestions, $variation_attrs ) {
        // Category icons for display
        $category_icons = array(
            'clothing'    => 'dashicons-buddicons-activity',
            'electronics' => 'dashicons-laptop',
            'automotive'  => 'dashicons-car',
            'general'     => 'dashicons-tag',
        );

        // Group suggestions by category
        $categories = array(
            'clothing'    => array( 'name' => 'Clothing & Apparel', 'items' => array() ),
            'electronics' => array( 'name' => 'Electronics & Tech', 'items' => array() ),
            'automotive'  => array( 'name' => 'Automotive', 'items' => array() ),
            'general'     => array( 'name' => 'General Purpose', 'items' => array() ),
        );

        foreach ( $suggestions as $key => $suggestion ) {
            $cat = $suggestion['category'] ?? 'general';
            if ( ! isset( $categories[ $cat ] ) ) {
                $cat = 'general';
            }
            $categories[ $cat ]['items'][ $key ] = $suggestion;
        }
        ?>
        <p class="description">Quickly set up common variation types for your products. Select a preset to auto-generate variations with pre-defined options.</p>

        <?php foreach ( $categories as $cat_key => $category ) : ?>
            <?php if ( ! empty( $category['items'] ) ) : ?>
                <h3 style="margin: 25px 0 15px; padding-bottom: 10px; border-bottom: 1px solid #ddd; display: flex; align-items: center; gap: 8px;">
                    <span class="dashicons <?php echo esc_attr( $category_icons[ $cat_key ] ); ?>" style="color: #0F766E;"></span>
                    <?php echo esc_html( $category['name'] ); ?>
                </h3>

                <div class="ggmc-presets-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px;">
                    <?php foreach ( $category['items'] as $key => $suggestion ) :
                        $installed = $variation_attrs->is_suggestion_installed( $key );
                        $attr_count = count( $suggestion['attributes'] );
                    ?>
                        <div class="ggmc-preset-card" style="background: #fff; border: 1px solid <?php echo $installed ? '#00a32a' : '#ddd'; ?>; border-radius: 8px; padding: 20px; transition: all 0.2s;">
                            <div style="display: flex; align-items: flex-start; gap: 12px; margin-bottom: 15px;">
                                <span style="width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; font-size: 20px; color: <?php echo $installed ? '#00a32a' : '#0F766E'; ?>; background: <?php echo $installed ? '#f0fff0' : '#e6f4f3'; ?>; border-radius: 50%; flex-shrink: 0;">
                                    <span class="dashicons <?php echo esc_attr( $category_icons[ $cat_key ] ); ?>"></span>
                                </span>
                                <div style="flex: 1;">
                                    <h3 style="margin: 0 0 4px; font-size: 16px; color: #1E293B; display: flex; align-items: center; gap: 8px;">
                                        <?php echo esc_html( $suggestion['name'] ); ?>
                                        <?php if ( $installed ) : ?>
                                            <span style="background: #00a32a; color: #fff; padding: 2px 8px; border-radius: 3px; font-size: 11px; font-weight: normal;">Installed</span>
                                        <?php endif; ?>
                                    </h3>
                                    <span style="font-size: 13px; color: #666;"><?php echo esc_html( $attr_count ); ?> variation<?php echo $attr_count !== 1 ? 's' : ''; ?></span>
                                </div>
                            </div>
                            <p style="color: #666; font-size: 13px; margin-bottom: 15px;"><?php echo esc_html( $suggestion['description'] ); ?></p>

                            <!-- Show preview of variations -->
                            <div style="margin-bottom: 15px; max-height: 120px; overflow-y: auto; padding: 10px; background: #f9f9f9; border-radius: 4px;">
                                <?php foreach ( $suggestion['attributes'] as $attr ) : ?>
                                    <div style="display: flex; align-items: flex-start; gap: 8px; margin-bottom: 8px; font-size: 12px;">
                                        <span class="dashicons dashicons-tag" style="color: #0F766E; font-size: 14px; width: 14px; height: 14px; margin-top: 2px;"></span>
                                        <div>
                                            <strong><?php echo esc_html( $attr['name'] ); ?>:</strong>
                                            <span style="color: #666;">
                                                <?php
                                                $preview_opts = array_slice( $attr['options'], 0, 4 );
                                                $opt_values = array_map( function( $o ) { return $o['value']; }, $preview_opts );
                                                echo esc_html( implode( ', ', $opt_values ) );
                                                if ( count( $attr['options'] ) > 4 ) {
                                                    echo ' +' . esc_html( count( $attr['options'] ) - 4 ) . ' more';
                                                }
                                                ?>
                                            </span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <?php if ( ! $installed ) : ?>
                                <form method="post" action="" onsubmit="return confirm('This will create <?php echo esc_js( $attr_count ); ?> variation(s) with pre-defined options. Continue?');">
                                    <?php wp_nonce_field( 'ggmc_variation_attributes' ); ?>
                                    <input type="hidden" name="action" value="install_suggestion">
                                    <input type="hidden" name="suggestion_key" value="<?php echo esc_attr( $key ); ?>">
                                    <button type="submit" class="button button-primary" style="width: 100%;">
                                        <span class="dashicons dashicons-download" style="vertical-align: middle; margin-top: -2px;"></span>
                                        Install Preset
                                    </button>
                                </form>
                            <?php else : ?>
                                <button type="button" class="button" style="width: 100%; pointer-events: none; opacity: 0.6;">
                                    <span class="dashicons dashicons-yes-alt" style="vertical-align: middle; margin-top: -2px; color: #00a32a;"></span>
                                    Already Installed
                                </button>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endforeach; ?>

        <?php
    }

    /**
     * AJAX handler for exporting products
     */
    public function ajax_export_products() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Load exporter
        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-exporter.php';
        $exporter = new GGM_Commerce_CSV_Exporter();

        // Get options
        $options = isset($_POST['options']) ? $_POST['options'] : [];

        // Export products
        $result = $exporter->export_products([
            'format' => isset($options['format']) ? sanitize_text_field($options['format']) : 'simple',
            'product_ids' => isset($options['product_ids']) ? array_map('intval', $options['product_ids']) : [],
            'include_categories' => !empty($options['include_categories']),
            'include_tags' => !empty($options['include_tags']),
            'include_attributes' => !empty($options['include_attributes']),
            'include_variations' => !empty($options['include_variations']),
            'include_barcodes' => !empty($options['include_barcodes']),
            'include_kits' => !empty($options['include_kits']),
            'include_downloads' => !empty($options['include_downloads']),
        ]);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
            return;
        }

        // Generate download URL
        $upload_dir = wp_upload_dir();
        $download_url = str_replace($upload_dir['basedir'], $upload_dir['baseurl'], $result['file']);

        wp_send_json_success([
            'download_url' => $download_url,
            'filename' => $result['filename'],
            'count' => $result['count'],
            'format' => $result['format']
        ]);
    }

    /**
     * AJAX handler for JSON export
     */
    public function ajax_export_json() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Load exporter
        require_once plugin_dir_path(__FILE__) . 'import-export/class-json-exporter.php';
        $exporter = new GGM_Commerce_JSON_Exporter();

        // Get options
        $options = isset($_POST['options']) ? $_POST['options'] : [];
        $export_images = !empty($options['export_image_package']);

        // Set exporter options
        $exporter->set_options([
            'include_tax_rates' => true,
            'include_attribute_groups' => true,
            'include_attributes' => true,
            'include_variation_attributes' => true,
            'include_categories' => true,
            'include_tags' => true,
            'include_products' => true,
            'include_variations' => true,
            'include_barcodes' => true,
            'include_downloads' => true,
            'include_kits' => true,
            'export_image_package' => $export_images,
            'include_trashed' => !empty($options['include_trashed']),
        ]);

        // Get product IDs if specified
        $product_ids = [];
        if (!empty($options['product_ids'])) {
            $product_ids = array_map('intval', $options['product_ids']);
        }

        // Export to file
        $result = $exporter->export_to_file($product_ids);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
            return;
        }

        $response = [
            'download_url' => $result['file_url'],
            'filename' => basename($result['file_path']),
            'file_size' => size_format($result['file_size']),
            'counts' => $result['counts'],
            'format' => 'json',
        ];

        // If exporting images, note that they can export the image package separately
        if ($export_images) {
            $response['image_package_ready'] = true;
            $response['image_count'] = count($exporter->get_image_manifest());
        }

        wp_send_json_success($response);
    }

    /**
     * AJAX handler for exporting image package
     */
    public function ajax_export_image_package() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Load exporter
        require_once plugin_dir_path(__FILE__) . 'import-export/class-json-exporter.php';
        $exporter = new GGM_Commerce_JSON_Exporter();

        // Get product IDs if specified
        $options = isset($_POST['options']) ? $_POST['options'] : [];
        $product_ids = [];
        if (!empty($options['product_ids'])) {
            $product_ids = array_map('intval', $options['product_ids']);
        }

        // Set options with image package enabled
        $exporter->set_options([
            'export_image_package' => true,
        ]);

        // Run export to build image manifest
        $exporter->export($product_ids);

        // Now export the image package
        $result = $exporter->export_image_package();

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
            return;
        }

        wp_send_json_success([
            'download_url' => $result['file_url'],
            'filename' => basename($result['file_path']),
            'file_size' => size_format($result['file_size']),
            'images_added' => $result['images_added'],
            'images_failed' => $result['images_failed'],
            'errors' => $result['errors'],
        ]);
    }

    /**
     * AJAX handler for uploading JSON import file
     */
    public function ajax_upload_json_import() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Check for file
        if (empty($_FILES['file'])) {
            wp_send_json_error(['message' => __('No file uploaded', 'ggm-commerce')]);
            return;
        }

        $file = $_FILES['file'];

        // Validate file type
        if (!preg_match('/\.json$/i', $file['name'])) {
            wp_send_json_error(['message' => __('Invalid file type. Please upload a JSON file.', 'ggm-commerce')]);
            return;
        }

        // Validate file size (50MB max for JSON)
        if ($file['size'] > 50 * 1024 * 1024) {
            wp_send_json_error(['message' => __('File size exceeds 50MB limit.', 'ggm-commerce')]);
            return;
        }

        // Move uploaded file to temp location
        $upload_dir = wp_upload_dir();
        $import_dir = $upload_dir['basedir'] . '/ggm-imports/';

        if (!file_exists($import_dir)) {
            wp_mkdir_p($import_dir);
        }

        $filename = sanitize_file_name($file['name']);
        $filepath = $import_dir . time() . '-' . $filename;

        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            wp_send_json_error(['message' => __('Failed to save uploaded file', 'ggm-commerce')]);
            return;
        }

        // Load JSON importer
        require_once plugin_dir_path(__FILE__) . 'import-export/class-json-importer.php';
        $importer = new GGM_Commerce_JSON_Importer();

        // Parse and validate
        $data = $importer->parse_file($filepath);

        if (is_wp_error($data)) {
            @unlink($filepath);
            wp_send_json_error(['message' => $data->get_error_message()]);
            return;
        }

        // Get summary
        $summary = $importer->get_summary($data);

        // Store file path in transient for later processing
        set_transient('ggmc_json_import_file_' . get_current_user_id(), $filepath, HOUR_IN_SECONDS);

        wp_send_json_success([
            'file_path' => $filepath,
            'summary' => $summary,
            'format' => 'json',
            'counts' => $summary['counts'],
        ]);
    }

    /**
     * AJAX handler for processing JSON import
     */
    public function ajax_process_json_import() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Get options
        $options = isset($_POST['options']) ? $_POST['options'] : [];
        $file_path = isset($_POST['file_path']) ? sanitize_text_field($_POST['file_path']) : '';

        // Validate file path
        if (empty($file_path) || !file_exists($file_path)) {
            // Try to get from transient
            $file_path = get_transient('ggmc_json_import_file_' . get_current_user_id());
            if (empty($file_path) || !file_exists($file_path)) {
                wp_send_json_error(['message' => __('Import file not found. Please upload again.', 'ggm-commerce')]);
                return;
            }
        }

        // Increase execution time limit
        @set_time_limit(600);
        @ini_set('memory_limit', '512M');

        // Load JSON importer
        require_once plugin_dir_path(__FILE__) . 'import-export/class-json-importer.php';
        $importer = new GGM_Commerce_JSON_Importer();

        // Set options
        $importer->set_options([
            'duplicate_handling' => isset($options['duplicate_handling']) ? sanitize_text_field($options['duplicate_handling']) : 'update',
            'download_images' => !empty($options['download_images']),
            'create_missing_entities' => true,
        ]);

        // Parse file
        $data = $importer->parse_file($file_path);

        if (is_wp_error($data)) {
            wp_send_json_error(['message' => $data->get_error_message()]);
            return;
        }

        // Run import
        $results = $importer->import($data);

        // Clean up
        @unlink($file_path);
        delete_transient('ggmc_json_import_file_' . get_current_user_id());

        if (!$results['success'] && !empty($results['errors'])) {
            wp_send_json_error([
                'message' => __('Import completed with errors', 'ggm-commerce'),
                'results' => $results,
            ]);
            return;
        }

        wp_send_json_success([
            'message' => __('Import completed successfully', 'ggm-commerce'),
            'results' => $results,
        ]);
    }

    /**
     * AJAX handler to start a background import
     */
    public function ajax_start_background_import() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Get file path from transient
        $file_path = get_transient('ggmc_json_import_file_' . get_current_user_id());
        if (empty($file_path) || !file_exists($file_path)) {
            wp_send_json_error(['message' => __('Import file not found. Please upload again.', 'ggm-commerce')]);
            return;
        }

        // Get options
        $options = isset($_POST['options']) ? $_POST['options'] : [];
        $sanitized_options = [
            'duplicate_handling' => isset($options['duplicate_handling']) ? sanitize_text_field($options['duplicate_handling']) : 'update',
            'download_images' => !empty($options['download_images']),
        ];

        // Load background import handler
        require_once plugin_dir_path(__FILE__) . 'import-export/class-background-import.php';
        $background_importer = new GGM_Commerce_Background_Import();

        // Start background import
        $job_id = $background_importer->start_background_import($file_path, $sanitized_options);

        if (is_wp_error($job_id)) {
            wp_send_json_error(['message' => $job_id->get_error_message()]);
            return;
        }

        // Don't delete the transient - the background process needs the file
        // It will clean up when complete

        wp_send_json_success([
            'message' => __('Background import started', 'ggm-commerce'),
            'job_id' => $job_id,
        ]);
    }

    /**
     * AJAX handler to get background import status
     */
    public function ajax_get_background_import_status() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $job_id = isset($_POST['job_id']) ? sanitize_text_field($_POST['job_id']) : '';

        if (empty($job_id)) {
            wp_send_json_error(['message' => __('Job ID required', 'ggm-commerce')]);
            return;
        }

        // Load background import handler
        require_once plugin_dir_path(__FILE__) . 'import-export/class-background-import.php';
        $background_importer = new GGM_Commerce_Background_Import();

        // Get job status
        $job_data = $background_importer->get_job_status($job_id);

        if (!$job_data) {
            wp_send_json_error(['message' => __('Job not found', 'ggm-commerce')]);
            return;
        }

        wp_send_json_success([
            'status' => $job_data['status'],
            'progress' => $job_data['progress'],
            'started_at' => $job_data['started_at'] ?? null,
            'completed_at' => $job_data['completed_at'] ?? null,
        ]);
    }

    /**
     * AJAX handler to cancel a background import
     */
    public function ajax_cancel_background_import() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $job_id = isset($_POST['job_id']) ? sanitize_text_field($_POST['job_id']) : '';

        if (empty($job_id)) {
            wp_send_json_error(['message' => __('Job ID required', 'ggm-commerce')]);
            return;
        }

        // Load background import handler
        require_once plugin_dir_path(__FILE__) . 'import-export/class-background-import.php';
        $background_importer = new GGM_Commerce_Background_Import();

        // Cancel job
        $cancelled = $background_importer->cancel_job($job_id);

        if (!$cancelled) {
            wp_send_json_error(['message' => __('Failed to cancel job', 'ggm-commerce')]);
            return;
        }

        wp_send_json_success([
            'message' => __('Import cancelled', 'ggm-commerce'),
        ]);
    }

    /**
     * AJAX handler for bulk product actions
     */
    public function ajax_bulk_products_action() {
        global $wpdb;

        // Verify nonce
        if (!check_ajax_referer('ggmc_bulk_products_action', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $action = isset($_POST['bulk_action']) ? sanitize_text_field($_POST['bulk_action']) : '';
        $product_ids = isset($_POST['product_ids']) ? array_map('intval', (array) $_POST['product_ids']) : [];

        if (empty($action)) {
            wp_send_json_error(['message' => __('No action selected', 'ggm-commerce')]);
            return;
        }

        if (empty($product_ids)) {
            wp_send_json_error(['message' => __('No products selected', 'ggm-commerce')]);
            return;
        }

        $products_table = $wpdb->prefix . 'ggmc_products';
        $affected = 0;

        switch ($action) {
            case 'set_draft':
                $affected = $this->bulk_update_product_status($product_ids, self::PRODUCT_STATUS_DRAFT);
                break;

            case 'set_for_review':
                $affected = $this->bulk_update_product_status($product_ids, self::PRODUCT_STATUS_FOR_REVIEW);
                break;

            case 'set_active':
                $affected = $this->bulk_update_product_status($product_ids, self::PRODUCT_STATUS_ACTIVE);
                break;

            case 'set_inactive':
                $affected = $this->bulk_update_product_status($product_ids, self::PRODUCT_STATUS_INACTIVE);
                break;

            case 'move_to_trash':
                $affected = $this->bulk_update_product_status($product_ids, self::PRODUCT_STATUS_TRASH);
                break;

            case 'restore_from_trash':
                $affected = $this->bulk_update_product_status($product_ids, self::PRODUCT_STATUS_DRAFT);
                break;

            case 'delete_permanently':
                $affected = $this->bulk_delete_products_permanently($product_ids);
                break;

            default:
                wp_send_json_error(['message' => __('Invalid action', 'ggm-commerce')]);
                return;
        }

        wp_send_json_success([
            'message' => sprintf(
                /* translators: %d: number of products affected */
                _n('%d product updated', '%d products updated', $affected, 'ggm-commerce'),
                $affected
            ),
            'affected' => $affected,
        ]);
    }

    /**
     * Bulk update product status
     *
     * @param array $product_ids Array of product IDs
     * @param string $status New status
     * @return int Number of affected rows
     */
    private function bulk_update_product_status($product_ids, $status) {
        global $wpdb;

        if (empty($product_ids)) {
            return 0;
        }

        $products_table = $wpdb->prefix . 'ggmc_products';
        $placeholders = implode(',', array_fill(0, count($product_ids), '%d'));

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $affected = $wpdb->query($wpdb->prepare(
            "UPDATE {$products_table} SET status = %s, updated_at = %s WHERE id IN ({$placeholders})",
            array_merge([$status, current_time('mysql')], $product_ids)
        ));

        return $affected !== false ? $affected : 0;
    }

    /**
     * Permanently delete products
     *
     * @param array $product_ids Array of product IDs
     * @return int Number of deleted products
     */
    private function bulk_delete_products_permanently($product_ids) {
        global $wpdb;

        if (empty($product_ids)) {
            return 0;
        }

        $deleted = 0;

        foreach ($product_ids as $product_id) {
            // Delete related data
            $wpdb->delete("{$wpdb->prefix}ggmc_product_categories", ['product_id' => $product_id]);
            $wpdb->delete("{$wpdb->prefix}ggmc_product_tags", ['product_id' => $product_id]);
            $wpdb->delete("{$wpdb->prefix}ggmc_product_barcodes", ['product_id' => $product_id]);
            $wpdb->delete("{$wpdb->prefix}ggmc_product_reviews", ['product_id' => $product_id]);
            $wpdb->delete("{$wpdb->prefix}ggmc_product_attribute_values", ['product_id' => $product_id]);

            // Delete variations if they exist
            $variations = $wpdb->get_col($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_product_variations WHERE product_id = %d",
                $product_id
            ));

            if (!empty($variations)) {
                foreach ($variations as $variation_id) {
                    $wpdb->delete("{$wpdb->prefix}ggmc_variation_type_values", ['variation_id' => $variation_id]);
                }
                $wpdb->delete("{$wpdb->prefix}ggmc_product_variations", ['product_id' => $product_id]);
            }

            // Delete kit components if product is a kit
            $wpdb->delete("{$wpdb->prefix}ggmc_kit_components", ['kit_product_id' => $product_id]);

            // Delete the product
            $result = $wpdb->delete("{$wpdb->prefix}ggmc_products", ['id' => $product_id]);

            if ($result) {
                $deleted++;
            }
        }

        // Clear filter caches (price range may have changed after deletions)
        if ( $deleted > 0 ) {
            GGM_Commerce_Taxonomy::clear_price_range_cache();
        }

        return $deleted;
    }

    /**
     * AJAX handler for bulk category actions
     */
    public function ajax_bulk_categories_action() {
        global $wpdb;

        // Verify nonce
        if (!check_ajax_referer('ggmc_bulk_categories_action', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $action = isset($_POST['bulk_action']) ? sanitize_text_field($_POST['bulk_action']) : '';
        $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : [];

        if (empty($action)) {
            wp_send_json_error(['message' => __('No action selected', 'ggm-commerce')]);
            return;
        }

        if (empty($category_ids)) {
            wp_send_json_error(['message' => __('No categories selected', 'ggm-commerce')]);
            return;
        }

        $affected = 0;

        switch ($action) {
            case 'delete':
                $affected = $this->bulk_delete_categories($category_ids);
                break;

            default:
                wp_send_json_error(['message' => __('Invalid action', 'ggm-commerce')]);
                return;
        }

        wp_send_json_success([
            'message' => sprintf(
                /* translators: %d: number of categories affected */
                _n('%d category deleted', '%d categories deleted', $affected, 'ggm-commerce'),
                $affected
            ),
            'affected' => $affected,
        ]);
    }

    /**
     * Bulk delete categories
     *
     * @param array $category_ids Array of category IDs
     * @return int Number of deleted categories
     */
    private function bulk_delete_categories($category_ids) {
        global $wpdb;

        if (empty($category_ids)) {
            return 0;
        }

        // Get protected category IDs (uncategorised and default)
        $taxonomy = GGM_Commerce_Taxonomy::get_instance();
        $uncategorised = $taxonomy->get_uncategorised_category();
        $uncategorised_id = $uncategorised ? intval($uncategorised->id) : 0;

        $catalog_options = get_option('ggm_commerce_catalog_options');
        $default_category_id = isset($catalog_options['default_category']) ? intval($catalog_options['default_category']) : 0;

        // Determine which category to move orphaned products to
        $fallback_category_id = $default_category_id > 0 ? $default_category_id : $uncategorised_id;

        // If no default is set, uncategorised acts as default
        $protected_ids = [];
        if ($uncategorised_id && !$default_category_id) {
            $protected_ids[] = $uncategorised_id;
        }
        if ($default_category_id) {
            $protected_ids[] = $default_category_id;
        }

        $deleted = 0;

        foreach ($category_ids as $category_id) {
            // Skip protected categories
            if (in_array($category_id, $protected_ids, true)) {
                continue;
            }

            // Find products that ONLY have this category (need to add fallback category)
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $products_only_this = $wpdb->get_col($wpdb->prepare(
                "SELECT pc.product_id FROM {$wpdb->prefix}ggmc_product_categories pc
                 WHERE pc.category_id = %d
                 AND NOT EXISTS (
                     SELECT 1 FROM {$wpdb->prefix}ggmc_product_categories pc2
                     WHERE pc2.product_id = pc.product_id AND pc2.category_id != %d
                 )",
                $category_id,
                $category_id
            ));

            // Add fallback category to products that will be orphaned
            if ($fallback_category_id && !empty($products_only_this)) {
                foreach ($products_only_this as $product_id) {
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                    $wpdb->insert(
                        "{$wpdb->prefix}ggmc_product_categories",
                        ['product_id' => $product_id, 'category_id' => $fallback_category_id],
                        ['%d', '%d']
                    );
                }
            }

            // Delete category-product relationships
            $wpdb->delete("{$wpdb->prefix}ggmc_product_categories", ['category_id' => $category_id]);

            // Delete the category
            $result = $wpdb->delete("{$wpdb->prefix}ggmc_categories", ['id' => $category_id]);

            if ($result) {
                $deleted++;
            }
        }

        return $deleted;
    }

    /**
     * AJAX handler for bulk tag actions
     */
    public function ajax_bulk_tags_action() {
        global $wpdb;

        // Verify nonce
        if (!check_ajax_referer('ggmc_bulk_tags_action', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $action = isset($_POST['bulk_action']) ? sanitize_text_field($_POST['bulk_action']) : '';
        $tag_ids = isset($_POST['tag_ids']) ? array_map('intval', (array) $_POST['tag_ids']) : [];

        if (empty($action)) {
            wp_send_json_error(['message' => __('No action selected', 'ggm-commerce')]);
            return;
        }

        if (empty($tag_ids)) {
            wp_send_json_error(['message' => __('No tags selected', 'ggm-commerce')]);
            return;
        }

        $affected = 0;

        switch ($action) {
            case 'delete':
                $affected = $this->bulk_delete_tags($tag_ids);
                break;

            default:
                wp_send_json_error(['message' => __('Invalid action', 'ggm-commerce')]);
                return;
        }

        wp_send_json_success([
            'message' => sprintf(
                /* translators: %d: number of tags affected */
                _n('%d tag deleted', '%d tags deleted', $affected, 'ggm-commerce'),
                $affected
            ),
            'affected' => $affected,
        ]);
    }

    /**
     * Bulk delete tags
     *
     * @param array $tag_ids Array of tag IDs
     * @return int Number of deleted tags
     */
    private function bulk_delete_tags($tag_ids) {
        global $wpdb;

        if (empty($tag_ids)) {
            return 0;
        }

        $deleted = 0;

        foreach ($tag_ids as $tag_id) {
            // Delete tag-product relationships
            $wpdb->delete("{$wpdb->prefix}ggmc_product_tags", ['tag_id' => $tag_id]);

            // Delete the tag
            $result = $wpdb->delete("{$wpdb->prefix}ggmc_tags", ['id' => $tag_id]);

            if ($result) {
                $deleted++;
            }
        }

        return $deleted;
    }

    /**
     * AJAX handler for bulk attribute actions
     */
    public function ajax_bulk_attributes_action() {
        global $wpdb;

        // Verify nonce
        if (!check_ajax_referer('ggmc_bulk_attributes_action', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $action = isset($_POST['bulk_action']) ? sanitize_text_field($_POST['bulk_action']) : '';
        $attribute_ids = isset($_POST['attribute_ids']) ? array_map('intval', (array) $_POST['attribute_ids']) : [];
        $attribute_type = isset($_POST['attribute_type']) ? sanitize_text_field($_POST['attribute_type']) : 'group';

        if (empty($action)) {
            wp_send_json_error(['message' => __('No action selected', 'ggm-commerce')]);
            return;
        }

        if (empty($attribute_ids)) {
            wp_send_json_error(['message' => __('No attributes selected', 'ggm-commerce')]);
            return;
        }

        $affected = 0;

        switch ($action) {
            case 'delete':
                if ($attribute_type === 'group') {
                    $affected = $this->bulk_delete_attribute_groups($attribute_ids);
                } else {
                    $affected = $this->bulk_delete_attributes($attribute_ids);
                }
                $message = sprintf(
                    /* translators: %d: number of attributes affected */
                    _n('%d attribute deleted', '%d attributes deleted', $affected, 'ggm-commerce'),
                    $affected
                );
                break;

            case 'set_filterable':
                if ($attribute_type === 'group') {
                    wp_send_json_error(['message' => __('Filterable cannot be set on attribute groups', 'ggm-commerce')]);
                    return;
                }
                $affected = $this->bulk_set_attributes_filterable($attribute_ids, true);
                $message = sprintf(
                    /* translators: %d: number of attributes affected */
                    _n('%d attribute set to filterable', '%d attributes set to filterable', $affected, 'ggm-commerce'),
                    $affected
                );
                break;

            case 'set_not_filterable':
                if ($attribute_type === 'group') {
                    wp_send_json_error(['message' => __('Filterable cannot be set on attribute groups', 'ggm-commerce')]);
                    return;
                }
                $affected = $this->bulk_set_attributes_filterable($attribute_ids, false);
                $message = sprintf(
                    /* translators: %d: number of attributes affected */
                    _n('%d attribute set to not filterable', '%d attributes set to not filterable', $affected, 'ggm-commerce'),
                    $affected
                );
                break;

            default:
                wp_send_json_error(['message' => __('Invalid action', 'ggm-commerce')]);
                return;
        }

        wp_send_json_success([
            'message' => $message,
            'affected' => $affected,
        ]);
    }

    /**
     * AJAX handler for toggling attribute filterable status
     */
    public function ajax_toggle_attribute_filterable() {
        global $wpdb;

        // Verify nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is verified, not used as data
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'ggmc_toggle_filterable')) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $attribute_id = isset($_POST['attribute_id']) ? absint($_POST['attribute_id']) : 0;
        $filterable = isset($_POST['filterable']) ? absint($_POST['filterable']) : 0;

        if (empty($attribute_id)) {
            wp_send_json_error(['message' => __('Invalid attribute ID', 'ggm-commerce')]);
            return;
        }

        // Update the filterable status
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Commerce plugin requires custom table queries
        $updated = $wpdb->update(
            "{$wpdb->prefix}ggmc_attributes",
            ['filterable' => $filterable ? 1 : 0],
            ['id' => $attribute_id],
            ['%d'],
            ['%d']
        );

        if ($updated !== false) {
            wp_send_json_success([
                'message' => __('Filterable status updated', 'ggm-commerce'),
                'filterable' => $filterable,
            ]);
        } else {
            wp_send_json_error(['message' => __('Failed to update filterable status', 'ggm-commerce')]);
        }
    }

    /**
     * Bulk delete attribute groups
     *
     * @param array $group_ids Array of attribute group IDs
     * @return int Number of deleted groups
     */
    private function bulk_delete_attribute_groups($group_ids) {
        global $wpdb;

        if (empty($group_ids)) {
            return 0;
        }

        $deleted = 0;

        foreach ($group_ids as $group_id) {
            // Get all attributes in this group
            $attribute_ids = $wpdb->get_col($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_attributes WHERE group_id = %d",
                $group_id
            ));

            // Delete attribute values for all attributes in this group
            if (!empty($attribute_ids)) {
                $this->bulk_delete_attributes($attribute_ids);
            }

            // Delete the group
            $result = $wpdb->delete("{$wpdb->prefix}ggmc_attribute_groups", ['id' => $group_id]);

            if ($result) {
                $deleted++;
            }
        }

        return $deleted;
    }

    /**
     * Bulk delete attributes
     *
     * @param array $attribute_ids Array of attribute IDs
     * @return int Number of deleted attributes
     */
    private function bulk_delete_attributes($attribute_ids) {
        global $wpdb;

        if (empty($attribute_ids)) {
            return 0;
        }

        $deleted = 0;

        foreach ($attribute_ids as $attribute_id) {
            // Delete product attribute values
            $wpdb->delete("{$wpdb->prefix}ggmc_product_attribute_values", ['attribute_id' => $attribute_id]);

            // Delete the attribute
            $result = $wpdb->delete("{$wpdb->prefix}ggmc_attributes", ['id' => $attribute_id]);

            if ($result) {
                $deleted++;
            }
        }

        return $deleted;
    }

    /**
     * Bulk set attributes filterable status
     *
     * @param array $attribute_ids Array of attribute IDs
     * @param bool  $filterable    Whether to set filterable (true) or not filterable (false)
     * @return int Number of updated attributes
     */
    private function bulk_set_attributes_filterable($attribute_ids, $filterable) {
        global $wpdb;

        if (empty($attribute_ids)) {
            return 0;
        }

        $updated = 0;
        $filterable_value = $filterable ? 1 : 0;

        foreach ($attribute_ids as $attribute_id) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Commerce plugin requires custom table queries
            $result = $wpdb->update(
                "{$wpdb->prefix}ggmc_attributes",
                ['filterable' => $filterable_value],
                ['id' => $attribute_id],
                ['%d'],
                ['%d']
            );

            if ($result !== false) {
                $updated++;
            }
        }

        return $updated;
    }

    /**
     * AJAX handler for bulk variation attributes action
     */
    public function ajax_bulk_variations_action() {
        global $wpdb;

        // Verify nonce
        if (!check_ajax_referer('ggmc_bulk_variations_action', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $action = isset($_POST['bulk_action']) ? sanitize_text_field($_POST['bulk_action']) : '';
        $variation_ids = isset($_POST['variation_ids']) ? array_map('intval', (array) $_POST['variation_ids']) : [];

        if (empty($action)) {
            wp_send_json_error(['message' => __('No action selected', 'ggm-commerce')]);
            return;
        }

        if (empty($variation_ids)) {
            wp_send_json_error(['message' => __('No variations selected', 'ggm-commerce')]);
            return;
        }

        $affected = 0;

        switch ($action) {
            case 'set_active':
                $affected = $this->bulk_update_variation_status($variation_ids, 'active');
                $message = sprintf(
                    /* translators: %d: number of variations */
                    _n( '%d variation set to active', '%d variations set to active', $affected, 'ggm-commerce' ),
                    $affected
                );
                break;

            case 'set_inactive':
                $affected = $this->bulk_update_variation_status($variation_ids, 'inactive');
                $message = sprintf(
                    /* translators: %d: number of variations */
                    _n( '%d variation set to inactive', '%d variations set to inactive', $affected, 'ggm-commerce' ),
                    $affected
                );
                break;

            case 'delete':
                $affected = $this->bulk_delete_variation_attributes($variation_ids);
                $message = sprintf(
                    /* translators: %d: number of variations */
                    _n( '%d variation deleted', '%d variations deleted', $affected, 'ggm-commerce' ),
                    $affected
                );
                break;

            default:
                wp_send_json_error(['message' => __('Invalid action', 'ggm-commerce')]);
                return;
        }

        wp_send_json_success([
            'message' => $message,
            'affected' => $affected,
        ]);
    }

    /**
     * Bulk update variation type status
     *
     * @param array  $type_ids Array of variation type IDs
     * @param string $status   New status
     * @return int Number of updated types
     */
    private function bulk_update_variation_status($type_ids, $status) {
        global $wpdb;

        if (empty($type_ids)) {
            return 0;
        }

        $updated = 0;

        foreach ($type_ids as $type_id) {
            $result = $wpdb->update(
                "{$wpdb->prefix}ggmc_variation_types",
                ['status' => $status],
                ['id' => $type_id]
            );

            if ($result !== false) {
                $updated++;
            }
        }

        return $updated;
    }

    /**
     * Bulk delete variation types
     *
     * @param array $type_ids Array of variation type IDs
     * @return int Number of deleted variation types
     */
    private function bulk_delete_variation_attributes($type_ids) {
        global $wpdb;

        if (empty($type_ids)) {
            return 0;
        }

        $deleted = 0;
        $variations_manager = GGM_Commerce_Variations::instance();

        foreach ($type_ids as $type_id) {
            // Delete using the variations manager which handles cleanup
            $result = $variations_manager->delete_variation_type($type_id);

            if ($result) {
                $deleted++;
            }
        }

        return $deleted;
    }

    /**
     * AJAX handler for downloading template
     */
    public function ajax_download_template() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Load exporter
        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-exporter.php';
        $exporter = new GGM_Commerce_CSV_Exporter();

        // Get format
        $format = isset($_POST['format']) ? sanitize_text_field($_POST['format']) : 'simple';

        // Generate template
        $result = $exporter->generate_template($format);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
            return;
        }

        // Generate download URL
        $upload_dir = wp_upload_dir();
        $download_url = str_replace($upload_dir['basedir'], $upload_dir['baseurl'], $result['file']);

        wp_send_json_success([
            'download_url' => $download_url,
            'filename' => $result['filename'],
            'format' => $result['format']
        ]);
    }

    /**
     * AJAX handler for uploading import file
     */
    public function ajax_upload_import_file() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Check for file
        if (empty($_FILES['file'])) {
            wp_send_json_error(['message' => __('No file uploaded', 'ggm-commerce')]);
            return;
        }

        $file = $_FILES['file'];

        // Validate file type
        $allowed_types = ['text/csv', 'application/csv', 'text/plain'];
        if (!in_array($file['type'], $allowed_types) && !preg_match('/\.csv$/i', $file['name'])) {
            wp_send_json_error(['message' => __('Invalid file type. Please upload a CSV file.', 'ggm-commerce')]);
            return;
        }

        // Validate file size (10MB max)
        if ($file['size'] > 10 * 1024 * 1024) {
            wp_send_json_error(['message' => __('File size exceeds 10MB limit.', 'ggm-commerce')]);
            return;
        }

        // Load importer and field mapper
        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-importer.php';
        require_once plugin_dir_path(__FILE__) . 'import-export/class-field-mapper.php';
        require_once plugin_dir_path(__FILE__) . 'import-export/class-woocommerce-mapper.php';

        $importer = new GGM_Commerce_CSV_Importer();
        $field_mapper = new GGM_Commerce_Field_Mapper();
        $woo_mapper = new GGM_Commerce_WooCommerce_Mapper();

        // Move uploaded file
        $upload_dir = $importer->get_upload_directory();
        $filename = sanitize_file_name($file['name']);
        $filepath = $upload_dir . uniqid('import_') . '_' . $filename;

        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            wp_send_json_error(['message' => __('Failed to save uploaded file.', 'ggm-commerce')]);
            return;
        }

        // Parse CSV
        $csv_data = $importer->parse_csv($filepath);

        if (is_wp_error($csv_data)) {
            @unlink($filepath);
            wp_send_json_error(['message' => $csv_data->get_error_message()]);
            return;
        }

        // Detect format
        $detected_format = 'unknown';
        if ($woo_mapper->is_woocommerce_format($csv_data['headers'])) {
            $detected_format = 'woocommerce';
            $auto_mapping = $woo_mapper->generate_mapping($csv_data['headers']);
        } else {
            $detected_format = $importer->detect_format($csv_data['headers']);
            $auto_mapping = $field_mapper->auto_map($csv_data['headers']);
        }

        wp_send_json_success([
            'headers' => $csv_data['headers'],
            'row_count' => $csv_data['row_count'],
            'sample_rows' => $csv_data['sample_rows'],
            'file_path' => $filepath,
            'detected_format' => $detected_format,
            'auto_mapping' => $auto_mapping
        ]);
    }

    /**
     * AJAX handler for initializing import (starts the batch process)
     */
    public function ajax_process_import() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        // Get parameters
        $file_path = isset($_POST['file_path']) ? sanitize_text_field($_POST['file_path']) : '';
        $mapping = isset($_POST['mapping']) ? $_POST['mapping'] : [];
        $options = isset($_POST['options']) ? $_POST['options'] : [];

        // Validate file exists
        if (empty($file_path) || !file_exists($file_path)) {
            wp_send_json_error(['message' => __('Import file not found. Please upload again.', 'ggm-commerce')]);
            return;
        }

        // Sanitize mapping
        $sanitized_mapping = [];
        foreach ($mapping as $csv_col => $field) {
            $sanitized_mapping[sanitize_text_field($csv_col)] = sanitize_text_field($field);
        }

        // Load importer
        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-importer.php';
        $importer = new GGM_Commerce_CSV_Importer();

        // Use smaller batch size when downloading images to avoid gateway timeouts
        $download_images = !empty($options['download_images']);
        $batch_size = $download_images ? 1 : 10;

        // Initialize import session
        $result = $importer->init_import($file_path, $sanitized_mapping, [
            'duplicate_handling' => isset($options['duplicate_handling']) ? sanitize_text_field($options['duplicate_handling']) : 'update',
            'download_images' => $download_images,
            'create_categories' => !empty($options['create_categories']),
            'create_tags' => !empty($options['create_tags']),
            'create_attributes' => !empty($options['create_attributes']),
            'batch_size' => $batch_size,
        ]);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
            return;
        }

        // Process the first batch immediately
        $batch_result = $importer->process_batch();

        if (is_wp_error($batch_result)) {
            wp_send_json_error(['message' => $batch_result->get_error_message()]);
            return;
        }

        wp_send_json_success($batch_result);
    }

    /**
     * AJAX handler for processing the next batch of imports
     */
    public function ajax_get_import_progress() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }

        // Load importer
        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-importer.php';
        $importer = new GGM_Commerce_CSV_Importer();

        // Get current progress
        $progress = $importer->get_progress();

        // If still running, process next batch
        if (!empty($progress) && isset($progress['status']) && $progress['status'] === 'running') {
            $batch_result = $importer->process_batch();

            if (is_wp_error($batch_result)) {
                wp_send_json_error(['message' => $batch_result->get_error_message()]);
                return;
            }

            // If complete, clean up the file
            if ($batch_result['status'] === 'complete' && !empty($progress['file_path'])) {
                @unlink($progress['file_path']);
            }

            wp_send_json_success($batch_result);
            return;
        }

        // Return current progress (already complete or no session)
        wp_send_json_success($progress);
    }

    /**
     * AJAX handler to get import reports
     */
    public function ajax_get_import_reports() {
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-importer.php';
        wp_send_json_success(GGM_Commerce_CSV_Importer::get_import_reports());
    }

    /**
     * AJAX handler to delete a specific import report
     */
    public function ajax_delete_import_report() {
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        $index = isset($_POST['index']) ? intval($_POST['index']) : -1;
        if ($index < 0) {
            wp_send_json_error(['message' => __('Invalid report index', 'ggm-commerce')]);
            return;
        }

        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-importer.php';
        GGM_Commerce_CSV_Importer::delete_import_report($index);
        wp_send_json_success();
    }

    /**
     * AJAX handler to delete all import reports
     */
    public function ajax_delete_all_import_reports() {
        if (!check_ajax_referer('ggmc_import_export', 'nonce', false)) {
            wp_send_json_error(['message' => __('Security check failed', 'ggm-commerce')]);
            return;
        }
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'ggm-commerce')]);
            return;
        }

        require_once plugin_dir_path(__FILE__) . 'import-export/class-csv-importer.php';
        GGM_Commerce_CSV_Importer::delete_all_import_reports();
        wp_send_json_success();
    }

    /**
     * Show data cleanup warning notice on WordPress plugins page.
     *
     * Displays appropriate warnings based on the cleanup setting to inform
     * users what will happen to their data if the plugin is deleted.
     */
    public function show_cleanup_warning_on_plugins_page() {
        $screen = get_current_screen();

        // Only show on the plugins page.
        if ( ! $screen || 'plugins' !== $screen->id ) {
            return;
        }

        $cleanup_setting = get_option( 'ggm_commerce_cleanup_on_uninstall', 'keep' );
        $settings_url    = admin_url( 'admin.php?page=ggmc-settings&tab=business' );

        if ( 'remove' === $cleanup_setting ) {
            // Warning: Data will be deleted.
            ?>
            <div class="notice notice-warning">
                <p>
                    <strong><?php esc_html_e( 'Goose Commerce:', 'ggm-commerce' ); ?></strong>
                    <?php esc_html_e( 'Data cleanup is enabled.', 'ggm-commerce' ); ?>
                    <strong><?php esc_html_e( 'If you delete this plugin, ALL products, orders, customers, and settings will be permanently removed.', 'ggm-commerce' ); ?></strong>
                    <a href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Change this setting', 'ggm-commerce' ); ?></a>
                </p>
            </div>
            <?php
        } else {
            // Info: Data will be kept (dismissible).
            ?>
            <div class="notice notice-info is-dismissible">
                <p>
                    <strong><?php esc_html_e( 'Goose Commerce:', 'ggm-commerce' ); ?></strong>
                    <?php esc_html_e( 'Your data is safe. If you deactivate or delete this plugin, your products, orders, and settings will be preserved for future reinstallation.', 'ggm-commerce' ); ?>
                    <a href="<?php echo esc_url( $settings_url ); ?>"><?php esc_html_e( 'Change cleanup settings', 'ggm-commerce' ); ?></a>
                </p>
            </div>
            <?php
        }
    }

    /**
     * AJAX handler for exporting categories
     */
    public function ajax_export_categories() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Load exporter.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-taxonomy-csv-exporter.php';
        $exporter = new GGM_Commerce_Taxonomy_CSV_Exporter( 'categories' );

        // Export categories.
        $result = $exporter->export();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        // Generate download URL.
        $upload_dir   = wp_upload_dir();
        $download_url = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $result['file'] );

        wp_send_json_success(
            array(
                'download_url' => $download_url,
                'filename'     => $result['filename'],
                'count'        => $result['count'],
                'type'         => $result['type'],
            )
        );
    }

    /**
     * AJAX handler for exporting tags
     */
    public function ajax_export_tags() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Load exporter.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-taxonomy-csv-exporter.php';
        $exporter = new GGM_Commerce_Taxonomy_CSV_Exporter( 'tags' );

        // Export tags.
        $result = $exporter->export();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        // Generate download URL.
        $upload_dir   = wp_upload_dir();
        $download_url = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $result['file'] );

        wp_send_json_success(
            array(
                'download_url' => $download_url,
                'filename'     => $result['filename'],
                'count'        => $result['count'],
                'type'         => $result['type'],
            )
        );
    }

    /**
     * AJAX handler for exporting attribute groups
     */
    public function ajax_export_attribute_groups() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Load exporter.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-attribute-csv-exporter.php';
        $exporter = new GGM_Commerce_Attribute_CSV_Exporter( 'groups' );

        // Export attribute groups.
        $result = $exporter->export();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        // Generate download URL.
        $upload_dir   = wp_upload_dir();
        $download_url = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $result['file'] );

        wp_send_json_success(
            array(
                'download_url' => $download_url,
                'filename'     => $result['filename'],
                'count'        => $result['count'],
                'type'         => $result['type'],
            )
        );
    }

    /**
     * AJAX handler for exporting attributes
     */
    public function ajax_export_attributes() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Load exporter.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-attribute-csv-exporter.php';
        $exporter = new GGM_Commerce_Attribute_CSV_Exporter( 'attributes' );

        // Export attributes.
        $result = $exporter->export();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        // Generate download URL.
        $upload_dir   = wp_upload_dir();
        $download_url = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $result['file'] );

        wp_send_json_success(
            array(
                'download_url' => $download_url,
                'filename'     => $result['filename'],
                'count'        => $result['count'],
                'type'         => $result['type'],
            )
        );
    }

    /**
     * AJAX handler for exporting variation types
     */
    public function ajax_export_variation_types() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Load exporter.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-variation-type-csv-exporter.php';
        $exporter = new GGM_Commerce_Variation_Type_CSV_Exporter();

        // Export variation types.
        $result = $exporter->export();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        // Generate download URL.
        $upload_dir   = wp_upload_dir();
        $download_url = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $result['file'] );

        wp_send_json_success(
            array(
                'download_url' => $download_url,
                'filename'     => $result['filename'],
                'count'        => $result['count'],
                'type'         => $result['type'],
            )
        );
    }

    /**
     * AJAX handler for downloading taxonomy templates
     */
    public function ajax_download_taxonomy_template() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';

        switch ( $type ) {
            case 'categories':
            case 'tags':
                require_once plugin_dir_path( __FILE__ ) . 'import-export/class-taxonomy-csv-exporter.php';
                $exporter = new GGM_Commerce_Taxonomy_CSV_Exporter( $type );
                break;

            case 'attribute_groups':
                require_once plugin_dir_path( __FILE__ ) . 'import-export/class-attribute-csv-exporter.php';
                $exporter = new GGM_Commerce_Attribute_CSV_Exporter( 'groups' );
                break;

            case 'attributes':
                require_once plugin_dir_path( __FILE__ ) . 'import-export/class-attribute-csv-exporter.php';
                $exporter = new GGM_Commerce_Attribute_CSV_Exporter( 'attributes' );
                break;

            case 'variation_types':
                require_once plugin_dir_path( __FILE__ ) . 'import-export/class-variation-type-csv-exporter.php';
                $exporter = new GGM_Commerce_Variation_Type_CSV_Exporter();
                break;

            default:
                wp_send_json_error( array( 'message' => __( 'Invalid template type', 'ggm-commerce' ) ) );
                return;
        }

        $result = $exporter->generate_template();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        // Generate download URL.
        $upload_dir   = wp_upload_dir();
        $download_url = str_replace( $upload_dir['basedir'], $upload_dir['baseurl'], $result['file'] );

        wp_send_json_success(
            array(
                'download_url' => $download_url,
                'filename'     => $result['filename'],
                'type'         => $result['type'],
            )
        );
    }

    /**
     * AJAX handler for initializing taxonomy import
     */
    public function ajax_import_taxonomy_init() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Check for file upload.
        if ( empty( $_FILES['file'] ) || ! empty( $_FILES['file']['error'] ) ) {
            wp_send_json_error( array( 'message' => __( 'No file uploaded or upload error', 'ggm-commerce' ) ) );
            return;
        }

        $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
        if ( ! in_array( $type, array( 'categories', 'tags' ), true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid import type', 'ggm-commerce' ) ) );
            return;
        }

        // Move uploaded file to temp location.
        $upload_dir = wp_upload_dir();
        $temp_dir   = $upload_dir['basedir'] . '/ggm-commerce-imports/';

        if ( ! file_exists( $temp_dir ) ) {
            wp_mkdir_p( $temp_dir );
        }

        $filename  = 'import-' . $type . '-' . time() . '.csv';
        $file_path = $temp_dir . $filename;

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        if ( ! move_uploaded_file( $_FILES['file']['tmp_name'], $file_path ) ) {
            wp_send_json_error( array( 'message' => __( 'Failed to save uploaded file', 'ggm-commerce' ) ) );
            return;
        }

        // Load importer and initialize.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-taxonomy-csv-importer.php';
        $importer = new GGM_Commerce_Taxonomy_CSV_Importer( $type );

        $options = array(
            'duplicate_handling' => isset( $_POST['duplicate_handling'] ) ? sanitize_text_field( wp_unslash( $_POST['duplicate_handling'] ) ) : 'skip',
            'download_images'    => ! empty( $_POST['download_images'] ),
        );

        $result = $importer->init_import( $file_path, $options );

        if ( is_wp_error( $result ) ) {
            wp_delete_file( $file_path );
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( $result );
    }

    /**
     * AJAX handler for processing taxonomy import batch
     */
    public function ajax_import_taxonomy_batch() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
        if ( ! in_array( $type, array( 'categories', 'tags' ), true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid import type', 'ggm-commerce' ) ) );
            return;
        }

        // Load importer and process batch.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-taxonomy-csv-importer.php';
        $importer = new GGM_Commerce_Taxonomy_CSV_Importer( $type );

        $result = $importer->process_batch();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( $result );
    }

    /**
     * AJAX handler for initializing attributes import
     */
    public function ajax_import_attributes_init() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Check for file upload.
        if ( empty( $_FILES['file'] ) || ! empty( $_FILES['file']['error'] ) ) {
            wp_send_json_error( array( 'message' => __( 'No file uploaded or upload error', 'ggm-commerce' ) ) );
            return;
        }

        $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
        if ( ! in_array( $type, array( 'groups', 'attributes' ), true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid import type', 'ggm-commerce' ) ) );
            return;
        }

        // Move uploaded file to temp location.
        $upload_dir = wp_upload_dir();
        $temp_dir   = $upload_dir['basedir'] . '/ggm-commerce-imports/';

        if ( ! file_exists( $temp_dir ) ) {
            wp_mkdir_p( $temp_dir );
        }

        $filename  = 'import-' . $type . '-' . time() . '.csv';
        $file_path = $temp_dir . $filename;

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        if ( ! move_uploaded_file( $_FILES['file']['tmp_name'], $file_path ) ) {
            wp_send_json_error( array( 'message' => __( 'Failed to save uploaded file', 'ggm-commerce' ) ) );
            return;
        }

        // Load importer and initialize.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-attribute-csv-importer.php';
        $importer = new GGM_Commerce_Attribute_CSV_Importer( $type );

        $options = array(
            'duplicate_handling' => isset( $_POST['duplicate_handling'] ) ? sanitize_text_field( wp_unslash( $_POST['duplicate_handling'] ) ) : 'skip',
            'create_groups'      => ! empty( $_POST['create_groups'] ),
        );

        $result = $importer->init_import( $file_path, $options );

        if ( is_wp_error( $result ) ) {
            wp_delete_file( $file_path );
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( $result );
    }

    /**
     * AJAX handler for processing attributes import batch
     */
    public function ajax_import_attributes_batch() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        $type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
        if ( ! in_array( $type, array( 'groups', 'attributes' ), true ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid import type', 'ggm-commerce' ) ) );
            return;
        }

        // Load importer and process batch.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-attribute-csv-importer.php';
        $importer = new GGM_Commerce_Attribute_CSV_Importer( $type );

        $result = $importer->process_batch();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( $result );
    }

    /**
     * AJAX handler for initializing variation types import
     */
    public function ajax_import_variation_types_init() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Check for file upload.
        if ( empty( $_FILES['file'] ) || ! empty( $_FILES['file']['error'] ) ) {
            wp_send_json_error( array( 'message' => __( 'No file uploaded or upload error', 'ggm-commerce' ) ) );
            return;
        }

        // Move uploaded file to temp location.
        $upload_dir = wp_upload_dir();
        $temp_dir   = $upload_dir['basedir'] . '/ggm-commerce-imports/';

        if ( ! file_exists( $temp_dir ) ) {
            wp_mkdir_p( $temp_dir );
        }

        $filename  = 'import-variation-types-' . time() . '.csv';
        $file_path = $temp_dir . $filename;

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        if ( ! move_uploaded_file( $_FILES['file']['tmp_name'], $file_path ) ) {
            wp_send_json_error( array( 'message' => __( 'Failed to save uploaded file', 'ggm-commerce' ) ) );
            return;
        }

        // Load importer and initialize.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-variation-type-csv-importer.php';
        $importer = new GGM_Commerce_Variation_Type_CSV_Importer();

        $options = array(
            'duplicate_handling' => isset( $_POST['duplicate_handling'] ) ? sanitize_text_field( wp_unslash( $_POST['duplicate_handling'] ) ) : 'skip',
        );

        $result = $importer->init_import( $file_path, $options );

        if ( is_wp_error( $result ) ) {
            wp_delete_file( $file_path );
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( $result );
    }

    /**
     * Subscriptions admin page
     */
    public function subscriptions_page() {
        global $title, $wpdb;
        $title = 'Subscriptions';

        if ( ! class_exists( 'GGM_Commerce_Subscriptions' ) ) {
            echo '<div class="wrap"><h1>Subscriptions</h1><p>Subscription module not available.</p></div>';
            return;
        }

        $subs = GGM_Commerce_Subscriptions::instance();

        // Check if viewing a single subscription.
        $view_id = isset( $_GET['subscription_id'] ) ? intval( $_GET['subscription_id'] ) : 0;
        if ( $view_id ) {
            $this->render_subscription_detail( $view_id );
            return;
        }

        // Handle bulk actions.
        if ( isset( $_POST['ggmc_subscription_bulk_action'] ) && check_admin_referer( 'ggmc_subscription_bulk' ) ) {
            $bulk_action = isset( $_POST['bulk_action'] ) ? sanitize_text_field( wp_unslash( $_POST['bulk_action'] ) ) : '';
            $ids = isset( $_POST['subscription_ids'] ) ? array_map( 'intval', (array) $_POST['subscription_ids'] ) : array();

            if ( ! empty( $ids ) && ! empty( $bulk_action ) ) {
                $count = 0;
                foreach ( $ids as $sub_id ) {
                    switch ( $bulk_action ) {
                        case 'pause':
                            if ( $subs->pause_subscription( $sub_id, 'admin' ) ) {
                                $count++;
                            }
                            break;
                        case 'resume':
                            if ( $subs->resume_subscription( $sub_id, 'admin' ) ) {
                                $count++;
                            }
                            break;
                        case 'cancel':
                            if ( $subs->cancel_subscription( $sub_id, 'Bulk action by admin', 'admin' ) ) {
                                $count++;
                            }
                            break;
                    }
                }
                if ( $count > 0 ) {
                    echo '<div class="notice notice-success"><p>' . esc_html( sprintf( '%d subscription(s) updated.', $count ) ) . '</p></div>';
                }
            }
        }

        // Get filter parameters.
        $status_filter = isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '';
        $search        = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
        $current_page  = isset( $_GET['paged'] ) ? max( 1, intval( $_GET['paged'] ) ) : 1;
        $per_page      = 20;

        // Get subscriptions.
        $result = $subs->get_subscriptions( array(
            'status'   => $status_filter,
            'search'   => $search,
            'per_page' => $per_page,
            'page'     => $current_page,
        ) );

        $subscriptions = $result['subscriptions'];
        $total         = $result['total'];
        $total_pages   = ceil( $total / $per_page );

        // Get stats for status tabs.
        $stats    = $subs->get_stats();
        $statuses = GGM_Commerce_Subscriptions::get_statuses();

        // Status colours for badges.
        $status_colors = array(
            'pending'        => '#FFA500',
            'active'         => '#46B450',
            'on_hold'        => '#DC3232',
            'paused'         => '#D97706',
            'cancelled'      => '#999',
            'expired'        => '#666',
            'pending_cancel' => '#E65100',
            'trial'          => '#8B5CF6',
            'failed_payment' => '#DC3232',
        );

        // Get per-status counts.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count_rows = $wpdb->get_results(
            "SELECT status, COUNT(*) as cnt FROM {$wpdb->prefix}ggmc_subscriptions GROUP BY status"
        );
        $status_counts = array();
        foreach ( $count_rows as $row ) {
            $status_counts[ $row->status ] = (int) $row->cnt;
        }
        $total_all = array_sum( $status_counts );

        ?>
        <div class="wrap">
            <?php self::page_title( 'Subscriptions' ); ?>

            <!-- Status Filter Tabs -->
            <ul class="subsubsub">
                <li><a href="?page=ggmc-subscriptions" class="<?php echo ! $status_filter ? 'current' : ''; ?>">All <span class="count">(<?php echo esc_html( $total_all ); ?>)</span></a> |</li>
                <?php
                $tab_statuses = array( 'active', 'trial', 'paused', 'on_hold', 'pending_cancel', 'cancelled', 'expired', 'failed_payment' );
                $last_key     = end( $tab_statuses );
                foreach ( $tab_statuses as $s ) :
                    $cnt   = $status_counts[ $s ] ?? 0;
                    $label = $statuses[ $s ] ?? ucfirst( str_replace( '_', ' ', $s ) );
                    ?>
                    <li>
                        <a href="?page=ggmc-subscriptions&status=<?php echo esc_attr( $s ); ?>"
                           class="<?php echo $status_filter === $s ? 'current' : ''; ?>">
                            <?php echo esc_html( $label ); ?>
                            <span class="count">(<?php echo esc_html( $cnt ); ?>)</span>
                        </a><?php echo $s !== $last_key ? ' |' : ''; ?>
                    </li>
                <?php endforeach; ?>
            </ul>

            <!-- Search & Bulk Actions -->
            <form method="post" id="ggmc-subscriptions-form">
                <?php wp_nonce_field( 'ggmc_subscription_bulk' ); ?>

                <div class="tablenav top" style="clear: both;">
                    <div class="alignleft actions bulkactions">
                        <select name="bulk_action">
                            <option value="">Bulk Actions</option>
                            <option value="pause">Pause</option>
                            <option value="resume">Resume</option>
                            <option value="cancel">Cancel</option>
                        </select>
                        <input type="submit" name="ggmc_subscription_bulk_action" class="button action" value="Apply">
                    </div>

                    <div class="alignright">
                        <label class="screen-reader-text" for="subscription-search-input">Search Subscriptions</label>
                        <input type="search" id="subscription-search-input" name="s" value="<?php echo esc_attr( $search ); ?>"
                               placeholder="Search by # or email..." style="width: 250px;">
                        <input type="hidden" name="page" value="ggmc-subscriptions">
                        <?php if ( $status_filter ) : ?>
                            <input type="hidden" name="status" value="<?php echo esc_attr( $status_filter ); ?>">
                        <?php endif; ?>
                        <input type="submit" class="button" value="Search" formmethod="get" formaction="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>">
                    </div>
                </div>

                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <td class="manage-column column-cb check-column" style="width: 30px;">
                                <input type="checkbox" id="cb-select-all-1">
                            </td>
                            <th style="width: 120px;">Subscription</th>
                            <th>Customer</th>
                            <th>Product</th>
                            <th style="width: 100px;">Status</th>
                            <th style="width: 100px;">Amount</th>
                            <th style="width: 130px;">Billing Cycle</th>
                            <th style="width: 130px;">Next Payment</th>
                            <th style="width: 80px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ( $subscriptions ) : ?>
                            <?php foreach ( $subscriptions as $sub ) : ?>
                                <tr>
                                    <th class="check-column">
                                        <input type="checkbox" name="subscription_ids[]" value="<?php echo esc_attr( $sub->id ); ?>">
                                    </th>
                                    <td>
                                        <strong>
                                            <a href="?page=ggmc-subscriptions&subscription_id=<?php echo esc_attr( $sub->id ); ?>">
                                                #<?php echo esc_html( $sub->subscription_number ); ?>
                                            </a>
                                        </strong>
                                    </td>
                                    <td>
                                        <?php echo esc_html( $sub->customer_email ); ?>
                                    </td>
                                    <td>
                                        <?php
                                        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                                        $product = $wpdb->get_row( $wpdb->prepare(
                                            "SELECT name FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
                                            $sub->product_id
                                        ) );
                                        echo $product ? esc_html( $product->name ) : '<em>Deleted</em>';
                                        ?>
                                    </td>
                                    <td>
                                        <?php
                                        $color = $status_colors[ $sub->status ] ?? '#999';
                                        $label = $statuses[ $sub->status ] ?? ucfirst( str_replace( '_', ' ', $sub->status ) );
                                        printf(
                                            '<span style="display:inline-block;padding:4px 8px;background:%s;color:#fff;border-radius:3px;font-size:12px;font-weight:600;">%s</span>',
                                            esc_attr( $color ),
                                            esc_html( $label )
                                        );
                                        ?>
                                    </td>
                                    <td><?php echo esc_html( ggm_commerce_format_price( $sub->recurring_total ) ); ?></td>
                                    <td>
                                        <?php
                                        $period_label = GGM_Commerce_Subscriptions::get_billing_periods()[ $sub->billing_period ] ?? $sub->billing_period;
                                        printf(
                                            'Every %d %s',
                                            (int) $sub->billing_interval,
                                            esc_html( $period_label )
                                        );
                                        ?>
                                    </td>
                                    <td>
                                        <?php
                                        if ( ! empty( $sub->next_payment_date ) && '0000-00-00 00:00:00' !== $sub->next_payment_date ) {
                                            echo esc_html( gmdate( 'M j, Y', strtotime( $sub->next_payment_date ) ) );
                                        } else {
                                            echo '&mdash;';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <a href="?page=ggmc-subscriptions&subscription_id=<?php echo esc_attr( $sub->id ); ?>" class="button button-small">View</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else : ?>
                            <tr><td colspan="9" style="text-align: center; padding: 40px;">No subscriptions found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>

                <?php if ( $total_pages > 1 ) : ?>
                    <div class="tablenav bottom">
                        <div class="tablenav-pages">
                            <span class="displaying-num"><?php echo esc_html( $total ); ?> item(s)</span>
                            <span class="pagination-links">
                                <?php
                                $base_url = admin_url( 'admin.php?page=ggmc-subscriptions' );
                                if ( $status_filter ) {
                                    $base_url .= '&status=' . urlencode( $status_filter );
                                }
                                if ( $search ) {
                                    $base_url .= '&s=' . urlencode( $search );
                                }

                                if ( $current_page > 1 ) :
                                    ?>
                                    <a class="first-page button" href="<?php echo esc_url( $base_url . '&paged=1' ); ?>">&laquo;</a>
                                    <a class="prev-page button" href="<?php echo esc_url( $base_url . '&paged=' . ( $current_page - 1 ) ); ?>">&lsaquo;</a>
                                <?php else : ?>
                                    <span class="tablenav-pages-navspan button disabled">&laquo;</span>
                                    <span class="tablenav-pages-navspan button disabled">&lsaquo;</span>
                                <?php endif; ?>

                                <span class="paging-input">
                                    <span class="tablenav-paging-text">
                                        <?php echo esc_html( $current_page ); ?> of <?php echo esc_html( $total_pages ); ?>
                                    </span>
                                </span>

                                <?php if ( $current_page < $total_pages ) : ?>
                                    <a class="next-page button" href="<?php echo esc_url( $base_url . '&paged=' . ( $current_page + 1 ) ); ?>">&rsaquo;</a>
                                    <a class="last-page button" href="<?php echo esc_url( $base_url . '&paged=' . $total_pages ); ?>">&raquo;</a>
                                <?php else : ?>
                                    <span class="tablenav-pages-navspan button disabled">&rsaquo;</span>
                                    <span class="tablenav-pages-navspan button disabled">&raquo;</span>
                                <?php endif; ?>
                            </span>
                        </div>
                    </div>
                <?php endif; ?>
            </form>
        </div>

        <script>
        document.getElementById('cb-select-all-1').addEventListener('change', function() {
            var checkboxes = document.querySelectorAll('input[name="subscription_ids[]"]');
            for (var i = 0; i < checkboxes.length; i++) {
                checkboxes[i].checked = this.checked;
            }
        });
        </script>
        <?php
    }

    /**
     * Render single subscription detail page
     *
     * @param int $subscription_id Subscription ID.
     */
    private function render_subscription_detail( $subscription_id ) {
        global $wpdb;

        $subs = GGM_Commerce_Subscriptions::instance();
        $sub  = $subs->get_subscription( $subscription_id );

        if ( ! $sub ) {
            echo '<div class="wrap"><h1>Subscription not found</h1><p><a href="?page=ggmc-subscriptions">Back to Subscriptions</a></p></div>';
            return;
        }

        // Handle admin actions.
        if ( isset( $_POST['ggmc_subscription_action'] ) && check_admin_referer( 'ggmc_subscription_action_' . $subscription_id ) ) {
            $action = sanitize_text_field( wp_unslash( $_POST['ggmc_subscription_action'] ) );
            $result = false;

            switch ( $action ) {
                case 'activate':
                    $result = $subs->activate_subscription( $subscription_id );
                    break;
                case 'pause':
                    $result = $subs->pause_subscription( $subscription_id, 'admin' );
                    break;
                case 'resume':
                    $result = $subs->resume_subscription( $subscription_id, 'admin' );
                    break;
                case 'cancel':
                    $reason = isset( $_POST['cancel_reason'] ) ? sanitize_text_field( wp_unslash( $_POST['cancel_reason'] ) ) : '';
                    $result = $subs->cancel_subscription( $subscription_id, $reason, 'admin' );
                    break;
                case 'hold':
                    $result = $subs->hold_subscription( $subscription_id, 'Placed on hold by admin' );
                    break;
            }

            if ( $result ) {
                // Refresh subscription data after action.
                $sub = $subs->get_subscription( $subscription_id );
                echo '<div class="notice notice-success"><p>Subscription updated successfully.</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>Could not update subscription.</p></div>';
            }
        }

        $statuses = GGM_Commerce_Subscriptions::get_statuses();
        $status_colors = array(
            'pending'        => '#FFA500',
            'active'         => '#46B450',
            'on_hold'        => '#DC3232',
            'paused'         => '#D97706',
            'cancelled'      => '#999',
            'expired'        => '#666',
            'pending_cancel' => '#E65100',
            'trial'          => '#8B5CF6',
            'failed_payment' => '#DC3232',
        );

        // Get product name.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $product = $wpdb->get_row( $wpdb->prepare(
            "SELECT name FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $sub->product_id
        ) );

        // Get subscription items.
        $items = $subs->get_subscription_items( $subscription_id );

        // Get related orders.
        $related_orders = $subs->get_related_orders( $subscription_id );

        // Get activity log.
        $log = $subs->get_subscription_log( $subscription_id );

        $billing_periods = GGM_Commerce_Subscriptions::get_billing_periods();
        $period_label    = $billing_periods[ $sub->billing_period ] ?? $sub->billing_period;
        $color           = $status_colors[ $sub->status ] ?? '#999';
        $status_label    = $statuses[ $sub->status ] ?? ucfirst( str_replace( '_', ' ', $sub->status ) );

        ?>
        <div class="wrap">
            <p><a href="?page=ggmc-subscriptions">&larr; Back to Subscriptions</a></p>
            <?php self::page_title( 'Subscription #' . esc_html( $sub->subscription_number ) ); ?>
            <span style="display:inline-block;padding:4px 10px;background:<?php echo esc_attr( $color ); ?>;color:#fff;border-radius:3px;font-size:13px;font-weight:600;vertical-align:middle;margin-left:8px;">
                <?php echo esc_html( $status_label ); ?>
            </span>

            <div id="poststuff">
                <div id="post-body" class="metabox-holder columns-2">

                    <!-- Main Content -->
                    <div id="post-body-content" style="position: relative;">

                        <!-- Subscription Details -->
                        <div class="postbox">
                            <h2 class="hndle" style="padding: 10px 12px;">Subscription Details</h2>
                            <div class="inside">
                                <table class="form-table">
                                    <tr>
                                        <th>Customer Email</th>
                                        <td><?php echo esc_html( $sub->customer_email ); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Product</th>
                                        <td><?php echo $product ? esc_html( $product->name ) : '<em>Deleted</em>'; ?></td>
                                    </tr>
                                    <tr>
                                        <th>Billing Cycle</th>
                                        <td>Every <?php echo (int) $sub->billing_interval . ' ' . esc_html( $period_label ); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Recurring Amount</th>
                                        <td><?php echo esc_html( ggm_commerce_format_price( $sub->recurring_amount ) ); ?></td>
                                    </tr>
                                    <?php if ( (float) $sub->tax_amount > 0 ) : ?>
                                    <tr>
                                        <th>Tax</th>
                                        <td><?php echo esc_html( ggm_commerce_format_price( $sub->tax_amount ) ); ?></td>
                                    </tr>
                                    <?php endif; ?>
                                    <?php if ( (float) $sub->shipping_amount > 0 ) : ?>
                                    <tr>
                                        <th>Shipping</th>
                                        <td><?php echo esc_html( ggm_commerce_format_price( $sub->shipping_amount ) ); ?></td>
                                    </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <th>Recurring Total</th>
                                        <td><strong><?php echo esc_html( ggm_commerce_format_price( $sub->recurring_total ) ); ?></strong></td>
                                    </tr>
                                    <tr>
                                        <th>Payment Gateway</th>
                                        <td><?php echo esc_html( ucfirst( $sub->payment_gateway ?: 'None' ) ); ?></td>
                                    </tr>
                                    <?php if ( ! empty( $sub->gateway_subscription_id ) ) : ?>
                                    <tr>
                                        <th>Gateway Subscription ID</th>
                                        <td><code><?php echo esc_html( $sub->gateway_subscription_id ); ?></code></td>
                                    </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <th>Quantity</th>
                                        <td><?php echo (int) $sub->quantity; ?></td>
                                    </tr>
                                    <?php if ( ! empty( $sub->trial_length ) && (int) $sub->trial_length > 0 ) : ?>
                                    <tr>
                                        <th>Trial</th>
                                        <td>
                                            <?php
                                            $trial_period_label = $billing_periods[ $sub->trial_period ] ?? $sub->trial_period;
                                            echo (int) $sub->trial_length . ' ' . esc_html( $trial_period_label );
                                            if ( ! empty( $sub->trial_end_date ) && '0000-00-00 00:00:00' !== $sub->trial_end_date ) {
                                                echo ' (ends ' . esc_html( gmdate( 'M j, Y', strtotime( $sub->trial_end_date ) ) ) . ')';
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </table>
                            </div>
                        </div>

                        <!-- Key Dates -->
                        <div class="postbox">
                            <h2 class="hndle" style="padding: 10px 12px;">Key Dates</h2>
                            <div class="inside">
                                <table class="form-table">
                                    <tr>
                                        <th>Start Date</th>
                                        <td><?php echo ! empty( $sub->start_date ) ? esc_html( gmdate( 'M j, Y g:i a', strtotime( $sub->start_date ) ) ) : '&mdash;'; ?></td>
                                    </tr>
                                    <tr>
                                        <th>Next Payment</th>
                                        <td>
                                            <?php
                                            if ( ! empty( $sub->next_payment_date ) && '0000-00-00 00:00:00' !== $sub->next_payment_date ) {
                                                echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $sub->next_payment_date ) ) );
                                            } else {
                                                echo '&mdash;';
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Last Payment</th>
                                        <td>
                                            <?php
                                            if ( ! empty( $sub->last_payment_date ) && '0000-00-00 00:00:00' !== $sub->last_payment_date ) {
                                                echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $sub->last_payment_date ) ) );
                                            } else {
                                                echo '&mdash;';
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                    <?php if ( ! empty( $sub->end_date ) && '0000-00-00 00:00:00' !== $sub->end_date ) : ?>
                                    <tr>
                                        <th>End Date</th>
                                        <td><?php echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $sub->end_date ) ) ); ?></td>
                                    </tr>
                                    <?php endif; ?>
                                    <?php if ( ! empty( $sub->cancelled_at ) && '0000-00-00 00:00:00' !== $sub->cancelled_at ) : ?>
                                    <tr>
                                        <th>Cancelled At</th>
                                        <td>
                                            <?php echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $sub->cancelled_at ) ) ); ?>
                                            <?php if ( ! empty( $sub->cancellation_reason ) ) : ?>
                                                <br><small>Reason: <?php echo esc_html( $sub->cancellation_reason ); ?></small>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                    <?php if ( ! empty( $sub->paused_at ) && '0000-00-00 00:00:00' !== $sub->paused_at ) : ?>
                                    <tr>
                                        <th>Paused At</th>
                                        <td><?php echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $sub->paused_at ) ) ); ?></td>
                                    </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <th>Created</th>
                                        <td><?php echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $sub->created_at ) ) ); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        <!-- Subscription Items -->
                        <?php if ( $items ) : ?>
                        <div class="postbox">
                            <h2 class="hndle" style="padding: 10px 12px;">Subscription Items</h2>
                            <div class="inside">
                                <table class="wp-list-table widefat fixed striped">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>SKU</th>
                                            <th style="width: 60px;">Qty</th>
                                            <th style="width: 100px;">Price</th>
                                            <th style="width: 100px;">Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ( $items as $item ) : ?>
                                        <tr>
                                            <td>
                                                <?php echo esc_html( $item->product_name ); ?>
                                                <?php if ( ! empty( $item->variation_data ) ) : ?>
                                                    <br><small><?php echo esc_html( $item->variation_data ); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo esc_html( $item->product_sku ?: '&mdash;' ); ?></td>
                                            <td><?php echo (int) $item->quantity; ?></td>
                                            <td><?php echo esc_html( ggm_commerce_format_price( $item->recurring_price ) ); ?></td>
                                            <td><?php echo esc_html( ggm_commerce_format_price( $item->recurring_total ) ); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Related Orders -->
                        <div class="postbox">
                            <h2 class="hndle" style="padding: 10px 12px;">Related Orders</h2>
                            <div class="inside">
                                <?php if ( $related_orders ) : ?>
                                <table class="wp-list-table widefat fixed striped">
                                    <thead>
                                        <tr>
                                            <th style="width: 100px;">Order</th>
                                            <th style="width: 80px;">Type</th>
                                            <th style="width: 100px;">Total</th>
                                            <th style="width: 100px;">Status</th>
                                            <th style="width: 100px;">Payment</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ( $related_orders as $order ) : ?>
                                        <tr>
                                            <td>
                                                <a href="?page=ggmc-orders&order_id=<?php echo esc_attr( $order->id ); ?>">
                                                    #<?php echo esc_html( $order->order_number ); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php echo ! empty( $order->is_renewal ) ? '<span style="color:#0073aa;font-weight:600;">Renewal</span>' : 'Initial'; ?>
                                            </td>
                                            <td><?php echo esc_html( ggm_commerce_format_price( $order->total_amount ) ); ?></td>
                                            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_status_badge() returns escaped HTML ?>
                                            <td><?php echo $this->render_status_badge( $order->status ); ?></td>
                                            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_payment_status_badge() returns escaped HTML ?>
                                            <td><?php echo $this->render_payment_status_badge( $order->payment_status ); ?></td>
                                            <td><?php echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $order->created_at ) ) ); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <?php else : ?>
                                    <p>No related orders found.</p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Activity Log -->
                        <div class="postbox">
                            <h2 class="hndle" style="padding: 10px 12px;">Activity Log</h2>
                            <div class="inside">
                                <?php if ( $log ) : ?>
                                <table class="wp-list-table widefat fixed striped">
                                    <thead>
                                        <tr>
                                            <th style="width: 150px;">Date</th>
                                            <th style="width: 130px;">Event</th>
                                            <th>Description</th>
                                            <th style="width: 80px;">By</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ( $log as $entry ) : ?>
                                        <tr>
                                            <td><?php echo esc_html( gmdate( 'M j, Y g:i a', strtotime( $entry->created_at ) ) ); ?></td>
                                            <td>
                                                <code><?php echo esc_html( $entry->event_type ); ?></code>
                                            </td>
                                            <td>
                                                <?php echo esc_html( $entry->description ); ?>
                                                <?php if ( ! empty( $entry->order_id ) ) : ?>
                                                    <br><small>Order: <a href="?page=ggmc-orders&order_id=<?php echo esc_attr( $entry->order_id ); ?>">#<?php echo esc_html( $entry->order_id ); ?></a></small>
                                                <?php endif; ?>
                                                <?php if ( ! empty( $entry->amount ) && (float) $entry->amount > 0 ) : ?>
                                                    <br><small>Amount: <?php echo esc_html( ggm_commerce_format_price( $entry->amount ) ); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo esc_html( ucfirst( $entry->initiated_by ?: 'system' ) ); ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <?php else : ?>
                                    <p>No activity recorded yet.</p>
                                <?php endif; ?>
                            </div>
                        </div>

                    </div><!-- /post-body-content -->

                    <!-- Sidebar -->
                    <div id="postbox-container-1" class="postbox-container" style="width: 280px;">
                        <div class="postbox">
                            <h2 class="hndle" style="padding: 10px 12px;">Actions</h2>
                            <div class="inside">
                                <form method="post">
                                    <?php wp_nonce_field( 'ggmc_subscription_action_' . $subscription_id ); ?>

                                    <?php
                                    // Show available actions based on current status.
                                    $available_actions = array();
                                    switch ( $sub->status ) {
                                        case 'pending':
                                            $available_actions = array( 'activate' => 'Activate' );
                                            break;
                                        case 'active':
                                        case 'trial':
                                            $available_actions = array(
                                                'pause'  => 'Pause',
                                                'hold'   => 'Put On Hold',
                                                'cancel' => 'Cancel',
                                            );
                                            break;
                                        case 'paused':
                                            $available_actions = array(
                                                'resume' => 'Resume',
                                                'cancel' => 'Cancel',
                                            );
                                            break;
                                        case 'on_hold':
                                        case 'failed_payment':
                                            $available_actions = array(
                                                'activate' => 'Reactivate',
                                                'cancel'   => 'Cancel',
                                            );
                                            break;
                                        case 'pending_cancel':
                                            $available_actions = array(
                                                'activate' => 'Reactivate',
                                            );
                                            break;
                                    }
                                    ?>

                                    <?php if ( ! empty( $available_actions ) ) : ?>
                                        <div style="margin-bottom: 10px;">
                                            <?php foreach ( $available_actions as $action_key => $action_label ) : ?>
                                                <button type="submit" name="ggmc_subscription_action" value="<?php echo esc_attr( $action_key ); ?>"
                                                    class="button <?php echo 'cancel' === $action_key ? '' : 'button-primary'; ?>"
                                                    style="width: 100%; margin-bottom: 6px; text-align: center;
                                                    <?php echo 'cancel' === $action_key ? 'color: #dc3232; border-color: #dc3232;' : ''; ?>"
                                                    <?php echo 'cancel' === $action_key ? 'onclick="return confirm(\'Are you sure you want to cancel this subscription?\');"' : ''; ?>>
                                                    <?php echo esc_html( $action_label ); ?>
                                                </button>
                                            <?php endforeach; ?>
                                        </div>

                                        <?php if ( isset( $available_actions['cancel'] ) ) : ?>
                                            <div style="margin-top: 8px;">
                                                <label for="cancel_reason" style="display: block; margin-bottom: 4px; font-size: 12px;">Cancellation Reason (optional):</label>
                                                <input type="text" name="cancel_reason" id="cancel_reason" style="width: 100%;" placeholder="Reason for cancellation">
                                            </div>
                                        <?php endif; ?>
                                    <?php else : ?>
                                        <p style="color: #666; font-style: italic;">No actions available for this status.</p>
                                    <?php endif; ?>
                                </form>
                            </div>
                        </div>

                        <!-- Quick Info -->
                        <div class="postbox">
                            <h2 class="hndle" style="padding: 10px 12px;">Quick Info</h2>
                            <div class="inside">
                                <ul style="margin: 0; padding: 0; list-style: none;">
                                    <li style="padding: 6px 0; border-bottom: 1px solid #eee;">
                                        <strong>ID:</strong> <?php echo (int) $sub->id; ?>
                                    </li>
                                    <li style="padding: 6px 0; border-bottom: 1px solid #eee;">
                                        <strong>Customer ID:</strong> <?php echo (int) $sub->customer_id; ?>
                                    </li>
                                    <?php if ( ! empty( $sub->parent_order_id ) ) : ?>
                                    <li style="padding: 6px 0; border-bottom: 1px solid #eee;">
                                        <strong>Parent Order:</strong>
                                        <a href="?page=ggmc-orders&order_id=<?php echo esc_attr( $sub->parent_order_id ); ?>">
                                            #<?php echo (int) $sub->parent_order_id; ?>
                                        </a>
                                    </li>
                                    <?php endif; ?>
                                    <li style="padding: 6px 0; border-bottom: 1px solid #eee;">
                                        <strong>Currency:</strong> <?php echo esc_html( strtoupper( $sub->currency ?: 'GBP' ) ); ?>
                                    </li>
                                    <li style="padding: 6px 0;">
                                        <strong>Manual Renewal:</strong> <?php echo ! empty( $sub->requires_manual_renewal ) ? 'Yes' : 'No'; ?>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div><!-- /postbox-container-1 -->

                </div><!-- /post-body -->
            </div><!-- /poststuff -->
        </div>
        <?php
    }

    /**
     * AJAX handler for processing variation types import batch
     */
    public function ajax_import_variation_types_batch() {
        // Verify nonce.
        if ( ! check_ajax_referer( 'ggmc_import_export', 'nonce', false ) ) {
            wp_send_json_error( array( 'message' => __( 'Security check failed', 'ggm-commerce' ) ) );
            return;
        }

        // Check capabilities.
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Permission denied', 'ggm-commerce' ) ) );
            return;
        }

        // Load importer and process batch.
        require_once plugin_dir_path( __FILE__ ) . 'import-export/class-variation-type-csv-importer.php';
        $importer = new GGM_Commerce_Variation_Type_CSV_Importer();

        $result = $importer->process_batch();

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
            return;
        }

        wp_send_json_success( $result );
    }

}