<?php
/**
 * GGM Commerce Test Data Generator
 * Creates sample products, categories, and tags for testing
 */

// 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_Test_Data_Generator {

    private $categories = [];
    private $tags = [];
    private $product_map = [];
    private $customers = [];
    private $registry_table = 'ggmc_test_data_registry';

    public function __construct() {
        add_action('wp_ajax_ggm_commerce_generate_test_data', [$this, 'generate_test_data']);
        // Note: Menu integration is handled in the main settings page

        // Ensure registry table exists
        $this->create_registry_table();
    }

    /**
     * Create registry table to track test data
     */
    private function create_registry_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . $this->registry_table;
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            item_type varchar(50) NOT NULL,
            item_id bigint(20) NOT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY item_type (item_type),
            KEY item_id (item_id),
            UNIQUE KEY type_id (item_type, item_id)
        ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Register test data item in registry
     */
    private function register_test_item($type, $id) {
        global $wpdb;
        $table_name = $wpdb->prefix . $this->registry_table;

        $wpdb->replace(
            $table_name,
            [
                'item_type' => $type,
                'item_id' => $id,
                'created_at' => current_time('mysql')
            ]
        );
    }

    /**
     * Get all test data IDs by type
     */
    private function get_test_items($type) {
        global $wpdb;
        $table_name = $wpdb->prefix . $this->registry_table;

        return $wpdb->get_col($wpdb->prepare(
            "SELECT item_id FROM $table_name WHERE item_type = %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names are safely constructed
            $type
        ));
    }
    
    public function generate_test_data() {
        // Verify nonce
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Nonce is verified
        if (!isset($_POST['nonce']) || !wp_verify_nonce(wp_unslash($_POST['nonce']), 'ggm_commerce_test_data')) {
            wp_die('Security check failed');
        }

        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }

        // Increase time limit for this operation
        set_time_limit(300); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- set_time_limit needed for batch data generation

        try {
            $results = [];

            // Clear existing data if requested
            if (isset($_POST['clear_existing']) && $_POST['clear_existing'] === 'true' || isset($_POST['clear_only'])) {

                // Get clear options
                $clear_categories = isset($_POST['clear_categories']) ? $_POST['clear_categories'] === 'true' : false;
                $clear_tags = isset($_POST['clear_tags']) ? $_POST['clear_tags'] === 'true' : false;
                $clear_attributes = isset($_POST['clear_attributes']) ? $_POST['clear_attributes'] === 'true' : false;
                $clear_variations = isset($_POST['clear_variations']) ? $_POST['clear_variations'] === 'true' : false;
                $clear_kits = isset($_POST['clear_kits']) ? $_POST['clear_kits'] === 'true' : false;
                $clear_downloads = isset($_POST['clear_downloads']) ? $_POST['clear_downloads'] === 'true' : false;
                $clear_custom_attributes = isset($_POST['clear_custom_attributes']) ? $_POST['clear_custom_attributes'] === 'true' : false;
                $clear_reviews = isset($_POST['clear_reviews']) ? $_POST['clear_reviews'] === 'true' : false;
                $clear_orders = isset($_POST['clear_orders']) ? $_POST['clear_orders'] === 'true' : false;
                $clear_customers = isset($_POST['clear_customers']) ? $_POST['clear_customers'] === 'true' : false;

                $this->clear_test_data($clear_categories, $clear_tags, $clear_reviews, $clear_attributes, $clear_variations, $clear_kits, $clear_downloads, $clear_custom_attributes, $clear_orders, $clear_customers);
                $results[] = 'Cleared existing test data';

                if (isset($_POST['clear_only'])) {
                    wp_send_json_success(['message' => 'Test data cleared successfully']);
                    return;
                }
            }

            // Generate categories first
            if (isset($_POST['generate_categories']) && $_POST['generate_categories'] === 'true') {
                $categories_created = $this->create_categories();
                $results[] = "Created {$categories_created} categories";
            }

            // Generate tags
            if (isset($_POST['generate_tags']) && $_POST['generate_tags'] === 'true') {
                $tags_created = $this->create_tags();
                $results[] = "Created {$tags_created} tags";
            }

            // Generate variation attributes (before products, so variations can reference them)
            if (isset($_POST['generate_attributes']) && $_POST['generate_attributes'] === 'true') {
                $attributes_created = $this->create_variation_attributes();
                $results[] = "Created {$attributes_created} variation attributes";
            }

            // Generate products
            if (isset($_POST['generate_products']) && $_POST['generate_products'] === 'true') {
                $products_created = $this->create_products();
                $results[] = "Created {$products_created} products";
            }

            // Apply variations to products (after products exist)
            if (isset($_POST['generate_variations']) && $_POST['generate_variations'] === 'true') {
                $product_map = $this->get_product_map();
                if (!empty($product_map)) {
                    $var_results = $this->apply_product_variations($product_map);
                    if (isset($var_results['skipped'])) {
                        $results[] = "Variations skipped: {$var_results['skipped']}";
                    } else {
                        $results[] = "Applied variations: {$var_results['combined']} combined, {$var_results['independent']} independent ({$var_results['variations_created']} variation records)";
                    }
                }
            }

            // Create kits and builds (after products exist)
            if (isset($_POST['generate_kits']) && $_POST['generate_kits'] === 'true') {
                $product_map = $this->get_product_map();
                if (!empty($product_map)) {
                    $kit_results = $this->create_kits_and_builds($product_map);
                    if (isset($kit_results['skipped'])) {
                        $results[] = "Kits skipped: {$kit_results['skipped']}";
                    } else {
                        $msg = "Created {$kit_results['kits']} kits, {$kit_results['builds']} builds";
                        if (!empty($kit_results['errors'])) {
                            $msg .= ' (Errors: ' . implode('; ', $kit_results['errors']) . ')';
                        }
                        $results[] = $msg;
                    }
                }
            }

            // Create downloads for digital products
            if (isset($_POST['generate_downloads']) && $_POST['generate_downloads'] === 'true') {
                $product_map = $this->get_product_map();
                if (!empty($product_map)) {
                    $dl_results = $this->create_product_downloads($product_map);
                    if (isset($dl_results['skipped'])) {
                        $results[] = "Downloads skipped: {$dl_results['skipped']}";
                    } else {
                        $results[] = "Created {$dl_results['downloads']} downloads, {$dl_results['licenses']} licenses";
                    }
                }
            }

            // Create custom attributes (groups, attributes, and assign to products)
            if (isset($_POST['generate_custom_attributes']) && $_POST['generate_custom_attributes'] === 'true') {
                $ca_results = $this->create_custom_attributes();
                if (isset($ca_results['skipped'])) {
                    $results[] = "Custom attributes skipped: {$ca_results['skipped']}";
                } else {
                    $results[] = "Created {$ca_results['groups']} attribute groups, {$ca_results['attributes']} attributes";

                    // Assign attributes to products
                    $product_map = $this->get_product_map();
                    if (!empty($product_map)) {
                        $assign_results = $this->assign_custom_attributes_to_products($product_map);
                        if (!isset($assign_results['skipped'])) {
                            $results[] = "Assigned custom attributes to {$assign_results['products_updated']} products ({$assign_results['values_assigned']} values)";
                        }
                    }
                }
            }

            // Generate reviews (after products exist)
            if (isset($_POST['generate_reviews']) && $_POST['generate_reviews'] === 'true') {
                $reviews_created = $this->create_reviews();
                $results[] = "Created {$reviews_created} reviews";
            }

            // Generate customers
            if (isset($_POST['generate_customers']) && $_POST['generate_customers'] === 'true') {
                $customers_created = $this->create_customers();
                $results[] = "Created {$customers_created} customers";
            }

            // Generate orders (after products and customers)
            if (isset($_POST['generate_orders']) && $_POST['generate_orders'] === 'true') {
                $orders_created = $this->create_orders();
                $results[] = "Created {$orders_created} orders";
            }

            $message = implode('. ', $results) . '.';
            wp_send_json_success(['message' => $message]);

        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for test data generation errors
                error_log('GGMC Test Data Exception: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
            }
            wp_send_json_error(['message' => 'Error: ' . $e->getMessage() . ' Check error logs for details.']);
        } catch (Error $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for test data generation errors
                error_log('GGMC Test Data Fatal Error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
            }
            wp_send_json_error(['message' => 'Fatal error: ' . $e->getMessage() . ' in ' . basename($e->getFile()) . ':' . $e->getLine()]);
        }
    }
    
    /**
     * Clear test data using registry
     *
     * @param bool $clear_categories Whether to delete categories
     * @param bool $clear_tags Whether to delete tags
     * @param bool $clear_reviews Whether to delete reviews
     * @param bool $clear_attributes Whether to delete variation attributes
     * @param bool $clear_variations Whether to delete variations
     * @param bool $clear_kits Whether to delete kits/builds
     * @param bool $clear_downloads Whether to delete downloads/licenses
     * @param bool $clear_custom_attributes Whether to delete custom attributes
     * @param bool $clear_orders Whether to delete orders
     * @param bool $clear_customers Whether to delete customers
     */
    private function clear_test_data($clear_categories = false, $clear_tags = false, $clear_reviews = false, $clear_attributes = false, $clear_variations = false, $clear_kits = false, $clear_downloads = false, $clear_custom_attributes = false, $clear_orders = false, $clear_customers = false) {
        global $wpdb;

        // Clear custom attributes first (before products, after products they reference)
        if ($clear_custom_attributes) {
            // Clear product attribute values
            $test_pav_ids = $this->get_test_items('product_attribute_value');
            if (!empty($test_pav_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_pav_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_attribute_values WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }

            // Clear custom attributes
            $test_ca_ids = $this->get_test_items('custom_attribute');
            if (!empty($test_ca_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_ca_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_attributes WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }

            // Clear custom attribute groups
            $test_cag_ids = $this->get_test_items('custom_attribute_group');
            if (!empty($test_cag_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_cag_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_attribute_groups WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }
        }

        // Clear orders (before customers and products)
        if ($clear_orders) {
            $test_order_item_ids = $this->get_test_items('order_item');
            if (!empty($test_order_item_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_order_item_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_order_items WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }

            $test_order_ids = $this->get_test_items('order');
            if (!empty($test_order_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_order_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_orders WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }
        }

        // Clear customers (before products, after orders)
        if ($clear_customers) {
            $test_address_ids = $this->get_test_items('customer_address');
            if (!empty($test_address_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_address_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_customer_addresses WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }

            $test_customer_ids = $this->get_test_items('customer');
            if (!empty($test_customer_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_customer_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_customers WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }

            // Delete WordPress user accounts
            $test_wp_user_ids = $this->get_test_items('wp_user');
            if (!empty($test_wp_user_ids)) {
                require_once ABSPATH . 'wp-admin/includes/user.php';
                foreach ($test_wp_user_ids as $wp_user_id) {
                    wp_delete_user((int) $wp_user_id);
                }
            }
        }

        // Clear downloads/licenses first (before products)
        if ($clear_downloads) {
            $test_download_ids = $this->get_test_items('product_download');
            if (!empty($test_download_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_download_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_downloads WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }

            $test_license_ids = $this->get_test_items('product_license');
            if (!empty($test_license_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_license_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_licenses WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }
        }

        // Clear kits (before products)
        if ($clear_kits) {
            $test_kit_ids = $this->get_test_items('product_kit');
            if (!empty($test_kit_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_kit_ids));
                // Delete kit components first
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_kit_components WHERE kit_id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                // Delete kit definitions
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_kits WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }
        }

        // Clear variations (before products)
        if ($clear_variations) {
            // Clear product variation records
            $test_variation_ids = $this->get_test_items('product_variation');
            if (!empty($test_variation_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_variation_ids));
                // Delete variation type values first
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_variation_type_values WHERE variation_id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                // Delete variations
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_variations WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }

            // Clear product variation configs
            $test_config_product_ids = $this->get_test_items('product_variation_config');
            if (!empty($test_config_product_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_config_product_ids));
                // Delete product variation types
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_variation_types WHERE product_id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                // Delete product variation options (Independent mode)
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_variation_options WHERE product_id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                // Reset product variation settings
                $wpdb->query("UPDATE {$wpdb->prefix}ggmc_products SET has_variations = 0, variation_mode = NULL, variation_stock_mode = 'parent' WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }
        }

        // Get test product IDs from registry
        $test_product_ids = $this->get_test_items('product');

        if (!empty($test_product_ids)) {
            $ids_placeholder = implode(',', array_map('intval', $test_product_ids));

            // Delete product-category relationships from relationship table
            $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_categories WHERE product_id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed

            // Delete product-tag relationships from relationship table
            $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_tags WHERE product_id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed

            // Delete ONLY test products from products table
            $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_products WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed

            // Delete product images from media library
            foreach ($test_product_ids as $product_id) {
                $this->delete_product_media($product_id);
            }
        }

        // Clear categories if requested
        if ($clear_categories) {
            $test_category_ids = $this->get_test_items('category');
            if (!empty($test_category_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_category_ids));
                // Don't delete uncategorised
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_categories WHERE id IN ($ids_placeholder) AND slug != 'uncategorised'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed
            }
        }

        // Clear tags if requested
        if ($clear_tags) {
            $test_tag_ids = $this->get_test_items('tag');
            if (!empty($test_tag_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_tag_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_tags WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed
            }
        }

        // Clear variation types if requested (after products cleared)
        if ($clear_attributes) {
            $test_attr_ids = $this->get_test_items('variation_attribute');
            if (!empty($test_attr_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_attr_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_variation_types WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            }
        }

        // Clear reviews if requested
        if ($clear_reviews) {
            $test_review_ids = $this->get_test_items('review');
            if (!empty($test_review_ids)) {
                $ids_placeholder = implode(',', array_map('intval', $test_review_ids));
                $wpdb->query("DELETE FROM {$wpdb->prefix}ggmc_product_reviews WHERE id IN ($ids_placeholder)"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed

                // Recalculate ratings for affected products
                $affected_products = $wpdb->get_col("SELECT DISTINCT product_id FROM {$wpdb->prefix}ggmc_product_reviews");
                foreach ($affected_products as $product_id) {
                    if (class_exists('GGM_Commerce_Reviews')) {
                        GGM_Commerce_Reviews::recalculate_product_rating($product_id);
                    }
                }
            }
        }

        // Clear registry entries
        $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'product'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed
        if ($clear_categories) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'category'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed
        }
        if ($clear_tags) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'tag'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed
        }
        if ($clear_attributes) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'variation_attribute'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }
        if ($clear_variations) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'product_variation'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'product_variation_config'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }
        if ($clear_kits) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'product_kit'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }
        if ($clear_downloads) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'product_download'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'product_license'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }
        if ($clear_custom_attributes) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'custom_attribute_group'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'custom_attribute'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'product_attribute_value'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }
        if ($clear_reviews) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'review'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names/placeholders are safely constructed
        }
        if ($clear_orders) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'order'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'order_item'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }
        if ($clear_customers) {
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'customer'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'customer_address'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query("DELETE FROM {$wpdb->prefix}{$this->registry_table} WHERE item_type = 'wp_user'"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }

    }

    /**
     * Delete media attachments for a product
     */
    private function delete_product_media($product_id) {
        global $wpdb;

        // Get product image IDs
        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT image_id, gallery_ids FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ));

        if ($product) {
            // Delete main image
            if ($product->image_id) {
                wp_delete_attachment($product->image_id, true);
            }

            // Delete gallery images
            if ($product->gallery_ids) {
                $gallery_ids = explode(',', $product->gallery_ids);
                foreach ($gallery_ids as $gallery_id) {
                    if ($gallery_id) {
                        wp_delete_attachment($gallery_id, true);
                    }
                }
            }
        }
    }
    
    private function create_categories() {
        global $wpdb;

        $categories_data = [
            [
                'name' => 'Electronics',
                'description' => 'Smartphones, laptops, tablets, and electronic gadgets',
                'slug' => 'electronics'
            ],
            [
                'name' => 'Clothing & Fashion',
                'description' => 'Men\'s, women\'s, and children\'s clothing and accessories',
                'slug' => 'clothing-fashion'
            ],
            [
                'name' => 'Books & Media',
                'description' => 'Books, audiobooks, movies, and educational materials',
                'slug' => 'books-media'
            ],
            [
                'name' => 'Home & Garden',
                'description' => 'Furniture, home decor, gardening tools, and appliances',
                'slug' => 'home-garden'
            ],
            [
                'name' => 'Sports & Outdoors',
                'description' => 'Sports equipment, outdoor gear, and fitness accessories',
                'slug' => 'sports-outdoors'
            ],
            [
                'name' => 'Beauty & Personal Care',
                'description' => 'Cosmetics, skincare, hair care, and personal hygiene',
                'slug' => 'beauty-personal-care'
            ],
            [
                'name' => 'Toys & Games',
                'description' => 'Children\'s toys, board games, and educational games',
                'slug' => 'toys-games'
            ],
            [
                'name' => 'Food & Beverages',
                'description' => 'Gourmet foods, snacks, beverages, and specialty items',
                'slug' => 'food-beverages'
            ]
        ];

        $created = 0;
        foreach ($categories_data as $category) {
            // Check if category already exists
            $existing = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_categories WHERE slug = %s",
                $category['slug']
            ));

            if ($existing) {
                $this->categories[] = $existing;
                continue;
            }

            // Insert into custom categories table
            $result = $wpdb->insert(
                "{$wpdb->prefix}ggmc_categories",
                [
                    'name' => $category['name'],
                    'slug' => $category['slug'],
                    'description' => $category['description'],
                    'status' => 'active',
                    'display_order' => 0,
                    'parent_id' => 0
                ]
            );

            if ($result) {
                $category_id = $wpdb->insert_id;
                $this->categories[] = $category_id;
                // Register in test data registry
                $this->register_test_item('category', $category_id);
                $created++;
            }
        }

        return $created;
    }
    
    private function create_tags() {
        global $wpdb;

        $tags_data = [
            'Popular', 'Sale', 'New Arrival', 'Limited Edition', 'Best Seller',
            'Premium', 'Eco-Friendly', 'Trending', 'Featured', 'Clearance',
            'Seasonal', 'Gift Idea', 'Professional', 'Budget-Friendly', 'Luxury'
        ];

        $created = 0;
        foreach ($tags_data as $tag) {
            $slug = sanitize_title($tag);

            // Check if tag already exists
            $existing = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_tags WHERE slug = %s",
                $slug
            ));

            if ($existing) {
                $this->tags[] = $existing;
                continue;
            }

            // Insert into custom tags table
            $result = $wpdb->insert(
                "{$wpdb->prefix}ggmc_tags",
                [
                    'name' => $tag,
                    'slug' => $slug,
                    'description' => '',
                    'status' => 'active'
                ]
            );

            if ($result) {
                $tag_id = $wpdb->insert_id;
                $this->tags[] = $tag_id;
                // Register in test data registry
                $this->register_test_item('tag', $tag_id);
                $created++;
            }
        }

        return $created;
    }
    
    private function create_products() {
        global $wpdb;
        
        // Ensure we have categories and tags loaded from custom tables
        if (empty($this->categories)) {
            $categories = $wpdb->get_results("SELECT id FROM {$wpdb->prefix}ggmc_categories");
            $this->categories = wp_list_pluck($categories, 'id');
        }

        if (empty($this->tags)) {
            $tags = $wpdb->get_results("SELECT id FROM {$wpdb->prefix}ggmc_tags");
            $this->tags = wp_list_pluck($tags, 'id');
        }

        // Pre-cache category and tag lookups for performance
        $category_map = [];
        $categories = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}ggmc_categories");
        foreach ($categories as $category) {
            $category_map[$category->name] = $category->id;
        }

        $tag_map = [];
        $tags = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}ggmc_tags");
        foreach ($tags as $tag) {
            $tag_map[$tag->name] = $tag->id;
        }
        
        $products_data = [
            [
                'name' => 'iPhone 15 Pro Max',
                'sku' => 'IP15PM-256',
                'short_description' => 'Latest iPhone with titanium design and advanced camera system',
                'description' => 'The iPhone 15 Pro Max features a stunning titanium design, A17 Pro chip, and professional camera system with 5x telephoto zoom. Perfect for photography enthusiasts and power users.',
                'price' => 1199.99,
                'sale_price' => 1099.99,
                'stock' => 25,
                'weight' => 0.221,
                'dimensions' => '6.33 x 3.02 x 0.32 inches',
                'featured' => true,
                'categories' => ['Electronics'],
                'tags' => ['Popular', 'New Arrival', 'Premium']
            ],
            [
                'name' => 'Wireless Bluetooth Headphones',
                'sku' => 'WBH-001',
                'short_description' => 'High-quality noise-canceling wireless headphones',
                'description' => 'Experience crystal-clear audio with these premium wireless headphones featuring active noise cancellation, 30-hour battery life, and comfortable over-ear design.',
                'price' => 249.99,
                'sale_price' => 199.99,
                'stock' => 50,
                'weight' => 0.6,
                'dimensions' => '7.5 x 6.8 x 3.2 inches',
                'featured' => true,
                'categories' => ['Electronics'],
                'tags' => ['Popular', 'Sale', 'Best Seller']
            ],
            [
                'name' => 'MacBook Air M3',
                'sku' => 'MBA-M3-13',
                'short_description' => '13-inch MacBook Air with M3 chip',
                'description' => 'The new MacBook Air with M3 chip delivers incredible performance and all-day battery life in an ultraportable design. Perfect for students and professionals.',
                'price' => 1299.99,
                'stock' => 15,
                'weight' => 2.7,
                'dimensions' => '11.97 x 8.46 x 0.44 inches',
                'featured' => false,
                'categories' => ['Electronics'],
                'tags' => ['New Arrival', 'Professional', 'Premium']
            ],
            [
                'name' => 'Cotton Blend T-Shirt',
                'sku' => 'CT-001-M',
                'short_description' => 'Comfortable everyday cotton t-shirt',
                'description' => 'Soft and breathable cotton blend t-shirt perfect for casual wear. Available in multiple colors and sizes. Machine washable and pre-shrunk.',
                'price' => 24.99,
                'sale_price' => 19.99,
                'stock' => 100,
                'weight' => 0.2,
                'dimensions' => 'Medium size',
                'featured' => false,
                'categories' => ['Clothing & Fashion'],
                'tags' => ['Sale', 'Budget-Friendly', 'Popular']
            ],
            [
                'name' => 'Designer Leather Jacket',
                'sku' => 'DLJ-BLK-L',
                'short_description' => 'Premium genuine leather jacket',
                'description' => 'Handcrafted genuine leather jacket with premium finishing. Features multiple pockets, adjustable waist, and classic design that never goes out of style.',
                'price' => 399.99,
                'stock' => 12,
                'weight' => 2.1,
                'dimensions' => 'Large size',
                'featured' => true,
                'categories' => ['Clothing & Fashion'],
                'tags' => ['Premium', 'Luxury', 'Featured']
            ],
            [
                'name' => 'Running Sneakers',
                'sku' => 'RS-2024-42',
                'short_description' => 'Professional running shoes with advanced cushioning',
                'description' => 'High-performance running sneakers with advanced cushioning technology, breathable mesh upper, and durable rubber outsole. Perfect for long-distance running.',
                'price' => 129.99,
                'sale_price' => 99.99,
                'stock' => 35,
                'weight' => 0.8,
                'dimensions' => 'Size 42 EU',
                'featured' => false,
                'categories' => ['Sports & Outdoors'],
                'tags' => ['Sale', 'Professional', 'Popular']
            ],
            [
                'name' => 'The Complete Guide to Web Development',
                'sku' => 'BOOK-WD-2024',
                'short_description' => 'Comprehensive guide to modern web development',
                'description' => 'Learn HTML, CSS, JavaScript, and modern frameworks in this comprehensive 800-page guide. Includes practical projects and real-world examples.',
                'price' => 49.99,
                'stock' => 75,
                'weight' => 1.2,
                'dimensions' => '9 x 7 x 2 inches',
                'featured' => false,
                'categories' => ['Books & Media'],
                'tags' => ['Professional', 'New Arrival', 'Gift Idea']
            ],
            [
                'name' => 'Smart Coffee Maker',
                'sku' => 'SCM-WiFi-001',
                'short_description' => 'WiFi-enabled programmable coffee maker',
                'description' => 'Start your day right with this smart coffee maker. Features WiFi connectivity, programmable brewing, thermal carafe, and mobile app control.',
                'price' => 179.99,
                'sale_price' => 149.99,
                'stock' => 20,
                'weight' => 4.5,
                'dimensions' => '12 x 8 x 14 inches',
                'featured' => true,
                'categories' => ['Home & Garden'],
                'tags' => ['Sale', 'Trending', 'Featured']
            ],
            [
                'name' => 'Ergonomic Office Chair',
                'sku' => 'EOC-MESH-BLK',
                'short_description' => 'Comfortable mesh office chair with lumbar support',
                'description' => 'Professional office chair with breathable mesh back, adjustable lumbar support, armrests, and seat height. Perfect for long work sessions.',
                'price' => 299.99,
                'stock' => 18,
                'weight' => 22,
                'dimensions' => '26 x 26 x 40-44 inches',
                'featured' => false,
                'categories' => ['Home & Garden'],
                'tags' => ['Professional', 'Ergonomic', 'Popular']
            ],
            [
                'name' => 'Yoga Mat Premium',
                'sku' => 'YM-PREM-6MM',
                'short_description' => '6mm premium non-slip yoga mat',
                'description' => 'High-quality TPE yoga mat with excellent grip and cushioning. Eco-friendly, lightweight, and includes carrying strap. Perfect for yoga and pilates.',
                'price' => 39.99,
                'sale_price' => 29.99,
                'stock' => 60,
                'weight' => 1.1,
                'dimensions' => '72 x 24 x 0.24 inches',
                'featured' => false,
                'categories' => ['Sports & Outdoors'],
                'tags' => ['Sale', 'Eco-Friendly', 'Popular']
            ],
            [
                'name' => 'Anti-Aging Face Serum',
                'sku' => 'AFS-VIT-C-30ML',
                'short_description' => 'Vitamin C anti-aging serum for radiant skin',
                'description' => 'Powerful anti-aging serum with Vitamin C, hyaluronic acid, and peptides. Reduces fine lines, brightens skin, and provides deep hydration.',
                'price' => 79.99,
                'stock' => 45,
                'weight' => 0.1,
                'dimensions' => '1.5 x 1.5 x 4 inches',
                'featured' => true,
                'categories' => ['Beauty & Personal Care'],
                'tags' => ['Premium', 'Best Seller', 'Featured']
            ],
            [
                'name' => 'Educational Building Blocks Set',
                'sku' => 'EBB-500PCS',
                'short_description' => '500-piece educational building blocks for kids - Kit bundle (components can be purchased separately)',
                'description' => 'Creative building blocks set that enhances problem-solving skills and creativity. Includes instruction manual with 50+ project ideas. Ages 6+. This is a kit product - the bundle can be broken down into its individual components.',
                'price' => 59.99,
                'sale_price' => 44.99,
                'stock' => 30,
                'weight' => 2.2,
                'dimensions' => '15 x 12 x 8 inches',
                'featured' => false,
                'categories' => ['Toys & Games'],
                'tags' => ['Sale', 'Gift Idea', 'Educational'],
                'product_type' => 'kit'
            ],
            [
                'name' => 'Organic Green Tea',
                'sku' => 'OGT-SENCHA-100G',
                'short_description' => 'Premium organic sencha green tea',
                'description' => 'High-quality organic sencha green tea sourced from Japanese tea gardens. Rich in antioxidants and delivers a smooth, refreshing taste.',
                'price' => 24.99,
                'stock' => 80,
                'weight' => 0.1,
                'dimensions' => '4 x 3 x 6 inches',
                'featured' => false,
                'categories' => ['Food & Beverages'],
                'tags' => ['Organic', 'Premium', 'Popular']
            ],
            [
                'name' => 'Gaming Mechanical Keyboard',
                'sku' => 'GMK-RGB-87',
                'short_description' => 'RGB mechanical gaming keyboard with blue switches',
                'description' => 'Professional gaming keyboard with mechanical blue switches, RGB backlighting, anti-ghosting, and programmable keys. Perfect for gaming and typing.',
                'price' => 149.99,
                'sale_price' => 119.99,
                'stock' => 25,
                'weight' => 1.3,
                'dimensions' => '17 x 5 x 1.5 inches',
                'featured' => true,
                'categories' => ['Electronics'],
                'tags' => ['Sale', 'Gaming', 'Professional']
            ],
            [
                'name' => 'Wireless Charging Pad',
                'sku' => 'WCP-15W-001',
                'short_description' => '15W fast wireless charging pad',
                'description' => 'Universal wireless charging pad with 15W fast charging capability. Compatible with all Qi-enabled devices. Includes LED charging indicator.',
                'price' => 34.99,
                'sale_price' => 24.99,
                'stock' => 70,
                'weight' => 0.3,
                'dimensions' => '4 x 4 x 0.5 inches',
                'featured' => false,
                'categories' => ['Electronics'],
                'tags' => ['Sale', 'Trending', 'Budget-Friendly']
            ],
            [
                'name' => 'Stainless Steel Water Bottle',
                'sku' => 'SSWB-750ML',
                'short_description' => '750ml insulated stainless steel water bottle',
                'description' => 'Double-wall vacuum insulated water bottle keeps drinks cold for 24 hours or hot for 12 hours. BPA-free and leak-proof design.',
                'price' => 29.99,
                'stock' => 90,
                'weight' => 0.4,
                'dimensions' => '3 x 3 x 10 inches',
                'featured' => false,
                'categories' => ['Sports & Outdoors'],
                'tags' => ['Eco-Friendly', 'Popular', 'Budget-Friendly']
            ],
            [
                'name' => 'Smart Fitness Watch',
                'sku' => 'SFW-HR-GPS',
                'short_description' => 'Fitness tracker with heart rate and GPS',
                'description' => 'Advanced fitness watch with heart rate monitoring, GPS tracking, sleep analysis, and 7-day battery life. Water-resistant up to 50 meters.',
                'price' => 199.99,
                'sale_price' => 159.99,
                'stock' => 40,
                'weight' => 0.05,
                'dimensions' => '1.5 x 1.5 x 0.5 inches',
                'featured' => true,
                'categories' => ['Electronics', 'Sports & Outdoors'],
                'tags' => ['Sale', 'Popular', 'Featured']
            ],
            [
                'name' => 'Luxury Silk Scarf',
                'sku' => 'LSS-FLORAL-90',
                'short_description' => '90cm premium silk scarf with floral pattern',
                'description' => '100% mulberry silk scarf with hand-rolled edges and beautiful floral print. Adds elegance to any outfit. Comes with luxury gift box.',
                'price' => 89.99,
                'stock' => 22,
                'weight' => 0.05,
                'dimensions' => '35 x 35 inches',
                'featured' => false,
                'categories' => ['Clothing & Fashion'],
                'tags' => ['Luxury', 'Premium', 'Gift Idea']
            ],
            [
                'name' => 'LED Desk Lamp',
                'sku' => 'LDL-TOUCH-DIM',
                'short_description' => 'Touch-control dimmable LED desk lamp',
                'description' => 'Modern LED desk lamp with touch controls, adjustable brightness, color temperature control, and USB charging port. Perfect for office or study.',
                'price' => 69.99,
                'sale_price' => 54.99,
                'stock' => 35,
                'weight' => 1.8,
                'dimensions' => '18 x 8 x 3 inches',
                'featured' => false,
                'categories' => ['Home & Garden'],
                'tags' => ['Sale', 'Professional', 'Modern']
            ],
            [
                'name' => 'Organic Face Moisturizer',
                'sku' => 'OFM-ALOE-50ML',
                'short_description' => 'Organic aloe vera face moisturizer',
                'description' => 'Natural face moisturizer with organic aloe vera, jojoba oil, and vitamin E. Suitable for all skin types. Cruelty-free and paraben-free.',
                'price' => 34.99,
                'stock' => 55,
                'weight' => 0.08,
                'dimensions' => '2 x 2 x 4 inches',
                'featured' => false,
                'categories' => ['Beauty & Personal Care'],
                'tags' => ['Organic', 'Eco-Friendly', 'Popular']
            ],
            [
                'name' => 'Bluetooth Speaker Portable',
                'sku' => 'BSP-WATER-20W',
                'short_description' => '20W waterproof Bluetooth speaker',
                'description' => 'Compact waterproof Bluetooth speaker with 20W output, 12-hour battery life, and enhanced bass. Perfect for outdoor activities and parties.',
                'price' => 79.99,
                'sale_price' => 59.99,
                'stock' => 45,
                'weight' => 0.6,
                'dimensions' => '7 x 3 x 3 inches',
                'featured' => false,
                'categories' => ['Electronics'],
                'tags' => ['Sale', 'Waterproof', 'Popular']
            ],
            [
                'name' => 'Puzzle 1000 Pieces',
                'sku' => 'PZ-NATURE-1000',
                'short_description' => '1000-piece nature landscape jigsaw puzzle',
                'description' => 'Beautiful 1000-piece jigsaw puzzle featuring stunning nature photography. High-quality pieces with precise fit. Includes reference poster.',
                'price' => 19.99,
                'stock' => 65,
                'weight' => 0.7,
                'dimensions' => '10 x 8 x 2 inches',
                'featured' => false,
                'categories' => ['Toys & Games'],
                'tags' => ['Budget-Friendly', 'Gift Idea', 'Relaxing']
            ],
            [
                'name' => 'Gourmet Coffee Beans',
                'sku' => 'GCB-ARABICA-500G',
                'short_description' => '500g premium single-origin arabica coffee beans',
                'description' => 'Premium single-origin arabica coffee beans from Colombian highlands. Medium roast with notes of chocolate and caramel. Freshly roasted to order.',
                'price' => 32.99,
                'stock' => 40,
                'weight' => 0.5,
                'dimensions' => '5 x 3 x 8 inches',
                'featured' => true,
                'categories' => ['Food & Beverages'],
                'tags' => ['Premium', 'Gourmet', 'Featured']
            ],
            [
                'name' => 'Camping Sleeping Bag',
                'sku' => 'CSB-3SEASON',
                'short_description' => '3-season lightweight camping sleeping bag - Build product (permanent assembly)',
                'description' => 'Lightweight and compact sleeping bag suitable for 3-season camping. Temperature rating down to 20°F. Includes compression sack. This is a build product - the components are permanently assembled.',
                'price' => 89.99,
                'sale_price' => 69.99,
                'stock' => 28,
                'weight' => 2.1,
                'dimensions' => '15 x 8 x 8 inches (packed)',
                'featured' => false,
                'categories' => ['Sports & Outdoors'],
                'tags' => ['Sale', 'Outdoor', 'Lightweight'],
                'product_type' => 'build'
            ],
            [
                'name' => 'Essential Oils Starter Set',
                'sku' => 'EOS-STARTER-6',
                'short_description' => '6-piece essential oils starter set - Kit bundle (components can be purchased separately)',
                'description' => 'Complete starter set with 6 popular essential oils: lavender, peppermint, eucalyptus, tea tree, lemon, and orange. 100% pure and therapeutic grade. This is a kit product - individual oils can be purchased separately.',
                'price' => 44.99,
                'stock' => 50,
                'weight' => 0.3,
                'dimensions' => '8 x 6 x 2 inches',
                'featured' => false,
                'categories' => ['Beauty & Personal Care'],
                'tags' => ['Natural', 'Gift Idea', 'Popular'],
                'product_type' => 'kit'
            ],
            // Virtual products (services, no shipping)
            [
                'name' => 'Online Photography Course',
                'sku' => 'COURSE-PHOTO-001',
                'short_description' => 'Complete online photography masterclass',
                'description' => 'Learn professional photography from beginner to advanced level. Includes 50+ video lessons, assignments, and lifetime access to course updates.',
                'price' => 149.99,
                'sale_price' => 99.99,
                'stock' => 999,
                'weight' => 0,
                'dimensions' => '',
                'featured' => true,
                'categories' => ['Books & Media'],
                'tags' => ['Premium', 'Professional', 'Featured'],
                'product_type' => 'virtual',
                'is_virtual' => 1,
                'requires_shipping' => 0
            ],
            [
                'name' => 'Premium Software License',
                'sku' => 'LICENSE-PREM-001',
                'short_description' => 'Premium software license with 1 year updates',
                'description' => 'Full license for our premium software suite. Includes all features, priority support, and 1 year of free updates. Activates on up to 3 devices.',
                'price' => 299.99,
                'stock' => 999,
                'weight' => 0,
                'dimensions' => '',
                'featured' => false,
                'categories' => ['Electronics'],
                'tags' => ['Premium', 'Professional', 'Digital'],
                'product_type' => 'digital',
                'is_downloadable' => 1,
                'requires_shipping' => 0
            ],
            [
                'name' => 'Consultation Session',
                'sku' => 'SERVICE-CONSULT-1HR',
                'short_description' => '1-hour professional consultation session',
                'description' => 'One-on-one consultation session with our expert team. Available via video call. Perfect for personalized advice and strategy planning.',
                'price' => 75.00,
                'stock' => 999,
                'weight' => 0,
                'dimensions' => '',
                'featured' => false,
                'categories' => ['Books & Media'],
                'tags' => ['Professional', 'Premium', 'Service'],
                'product_type' => 'virtual',
                'is_virtual' => 1,
                'requires_shipping' => 0
            ]
        ];
        
        $created = 0;
        $table_name = $wpdb->prefix . 'ggmc_products';

        // Get tax rates for random assignment
        $tax_rates = $wpdb->get_col("SELECT id FROM {$wpdb->prefix}ggmc_tax_rates WHERE status = 'active'");

        foreach ($products_data as $index => $product) {
            // Log progress every 5 products
            if ($index % 5 == 0) {
            }
            
            // Parse dimensions from string like "6.33 x 3.02 x 0.32 inches"
            $length = null;
            $width = null;
            $height = null;
            
            if (!empty($product['dimensions'])) {
                $dim_parts = explode(' x ', strtolower(str_replace(' inches', '', $product['dimensions'])));
                if (count($dim_parts) >= 3) {
                    $length = floatval(trim($dim_parts[0]));
                    $width = floatval(trim($dim_parts[1]));
                    $height = floatval(trim($dim_parts[2]));
                }
            }
            
            // Get all category IDs for this product (supports multiple categories)
            $category_ids = [];
            if (!empty($product['categories'])) {
                foreach ($product['categories'] as $cat_name) {
                    if (isset($category_map[$cat_name])) {
                        $category_ids[] = $category_map[$cat_name];
                    }
                }
            }
            // Default to uncategorised if no categories found
            if (empty($category_ids)) {
                $category_ids = [1];
            }

            // Collect tag IDs for junction table
            $tag_ids_array = [];
            if (!empty($product['tags'])) {
                foreach ($product['tags'] as $tag_name) {
                    if (isset($tag_map[$tag_name])) {
                        $tag_ids_array[] = $tag_map[$tag_name];
                    }
                }
            }

            // Generate unique slug for this product
            $slug = GGM_Commerce_Database::generate_unique_slug($product['name']);

            // Select a random tax rate (most products get standard rate, some get reduced or zero)
            $tax_rate_id = null;
            if (!empty($tax_rates)) {
                // Weight the selection: 70% standard (first), 20% reduced, 10% zero
                $random = wp_rand(1, 100);
                if ($random <= 70 && isset($tax_rates[0])) {
                    $tax_rate_id = $tax_rates[0]; // Standard rate (default)
                } elseif ($random <= 90 && isset($tax_rates[1])) {
                    $tax_rate_id = $tax_rates[1]; // Reduced rate
                } elseif (isset($tax_rates[2])) {
                    $tax_rate_id = $tax_rates[2]; // Zero rate
                } else {
                    $tax_rate_id = $tax_rates[0]; // Fallback to first rate
                }
            }

            // Build product data array
            $product_data = [
                'name' => $product['name'],
                'slug' => $slug,
                'sku' => $product['sku'],
                'short_description' => $product['short_description'],
                'description' => $product['description'],
                'price' => $product['price'],
                'sale_price' => $product['sale_price'] ?? null,
                'stock' => $product['stock'],
                'stock_status' => $product['stock'] > 0 ? 'instock' : 'outofstock',
                'weight' => $product['weight'],
                'length' => $length,
                'width' => $width,
                'height' => $height,
                'image_id' => $this->create_product_images($product['name']),
                'gallery_ids' => $this->create_gallery_images($product['name']),
                'manage_stock' => 1,
                'featured' => $product['featured'] ? 1 : 0,
                'tax_rate_id' => $tax_rate_id,
                'status' => 'active',
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            ];

            // Add product type fields if specified
            if (isset($product['product_type'])) {
                $product_data['product_type'] = $product['product_type'];
            }
            if (isset($product['is_virtual'])) {
                $product_data['is_virtual'] = $product['is_virtual'];
            }
            if (isset($product['is_downloadable'])) {
                $product_data['is_downloadable'] = $product['is_downloadable'];
            }
            if (isset($product['requires_shipping'])) {
                $product_data['requires_shipping'] = $product['requires_shipping'];
            }

            // Insert into products table
            $result = $wpdb->insert($table_name, $product_data);

            if ($result !== false) {
                $product_id = $wpdb->insert_id;
                // Register in test data registry
                $this->register_test_item('product', $product_id);

                // Insert into product_categories relationship table (supports multiple categories)
                foreach ($category_ids as $cat_id) {
                    $wpdb->insert(
                        "{$wpdb->prefix}ggmc_product_categories",
                        [
                            'product_id' => $product_id,
                            'category_id' => $cat_id
                        ],
                        ['%d', '%d']
                    );
                }

                // Insert into product_tags relationship table (supports multiple tags)
                foreach ($tag_ids_array as $tag_id) {
                    $wpdb->insert(
                        "{$wpdb->prefix}ggmc_product_tags",
                        [
                            'product_id' => $product_id,
                            'tag_id' => $tag_id
                        ],
                        ['%d', '%d']
                    );
                }

                // Store product ID with name for variation/kit assignment
                $this->product_map[$product_id] = $product['name'];

                $created++;
            } else {
            }
        }

        return $created;
    }

    /**
     * Get the product map (product_id => product_name)
     *
     * @return array
     */
    public function get_product_map() {
        return $this->product_map;
    }
    
    /**
     * Create product image from bundled plugin images
     */
    private function create_product_images($product_name) {
        // Get a bundled image file for this product
        $image_file = $this->get_bundled_image_path($product_name, 'main');

        if (!$image_file || !file_exists($image_file)) {
            return 0;
        }

        // Copy to media library
        return $this->copy_image_to_media_library($image_file, $product_name . ' - Main Image');
    }

    /**
     * Create gallery images from bundled plugin images
     */
    private function create_gallery_images($product_name) {
        $gallery_ids = [];

        // Get 2-4 gallery images for variety
        $num_gallery_images = wp_rand(2, 4);

        for ($i = 1; $i <= $num_gallery_images; $i++) {
            $image_file = $this->get_bundled_image_path($product_name, 'gallery', $i);

            if ($image_file && file_exists($image_file)) {
                $attachment_id = $this->copy_image_to_media_library(
                    $image_file,
                    $product_name . ' - Gallery Image ' . $i
                );
                if ($attachment_id) {
                    $gallery_ids[] = $attachment_id;
                }
            }
        }

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

    /**
     * Get path to a product image, downloading from remote if needed.
     *
     * Images are fetched from wpgoose.com and cached locally in the uploads
     * directory so they are only downloaded once.
     */
    private function get_bundled_image_path($product_name, $type = 'main', $index = 1) {
        $slug     = sanitize_title($product_name);
        $filename = ($type === 'main') ? $slug . '.jpg' : $slug . '-' . $index . '.jpg';

        // Local cache directory inside uploads (survives plugin updates).
        $upload_dir = wp_upload_dir();
        $cache_dir  = $upload_dir['basedir'] . '/ggmc-test-images';

        if (!is_dir($cache_dir)) {
            wp_mkdir_p($cache_dir);
        }

        $local_path = $cache_dir . '/' . $filename;

        // Return cached copy if it already exists.
        if (file_exists($local_path)) {
            return $local_path;
        }

        // Try downloading from wpgoose.com.
        $remote_url = 'https://wpgoose.com/assets/test-images/' . $filename;
        $response   = wp_remote_get($remote_url, array(
            'timeout'  => 30,
            'stream'   => true,
            'filename' => $local_path,
        ));

        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            return $local_path;
        }

        // Clean up failed download.
        if (file_exists($local_path)) {
            @unlink($local_path);
        }

        // Fallback: try placeholder.
        if ($filename !== 'placeholder.jpg') {
            return $this->get_bundled_image_path('placeholder', 'main');
        }

        return false;
    }

    /**
     * Copy bundled image to WordPress media library
     */
    private function copy_image_to_media_library($source_file, $title) {
        if (!file_exists($source_file)) {
            return 0;
        }

        // Check if already uploaded by checking title
        global $wpdb;
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = 'attachment'",
            $title
        ));

        if ($existing) {
            return $existing;
        }

        // Include WordPress file handling functions
        if (!function_exists('wp_handle_upload')) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
        }
        if (!function_exists('wp_generate_attachment_metadata')) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        }

        $upload_dir = wp_upload_dir();
        $filename = basename($source_file);
        $new_file_path = $upload_dir['path'] . '/' . $filename;

        // Copy file to uploads directory
        if (!copy($source_file, $new_file_path)) {
            return 0;
        }

        // Get file type
        $file_type = wp_check_filetype($filename, null);

        // Prepare attachment data
        $attachment = [
            'post_mime_type' => $file_type['type'] ?: 'image/jpeg',
            'post_title'     => sanitize_file_name($title),
            'post_content'   => '',
            'post_status'    => 'inherit'
        ];

        // Insert attachment
        $attachment_id = wp_insert_attachment($attachment, $new_file_path);

        if ($attachment_id) {
            // Generate metadata and thumbnails
            $attach_data = wp_generate_attachment_metadata($attachment_id, $new_file_path);
            wp_update_attachment_metadata($attachment_id, $attach_data);

            // Register this as a test image so it gets cleaned up
            $this->register_test_item('image', $attachment_id);
        }

        return $attachment_id ?: 0;
    }

    /**
     * Create sample reviews for products
     */
    private function create_reviews() {
        global $wpdb;

        // Sample reviewer names
        $reviewers = [
            ['name' => 'John Smith', 'email' => 'john.smith@example.com'],
            ['name' => 'Sarah Johnson', 'email' => 'sarah.j@example.com'],
            ['name' => 'Mike Williams', 'email' => 'mike.w@example.com'],
            ['name' => 'Emily Brown', 'email' => 'emily.b@example.com'],
            ['name' => 'David Lee', 'email' => 'david.lee@example.com'],
            ['name' => 'Jessica Garcia', 'email' => 'jessica.g@example.com'],
            ['name' => 'Chris Martinez', 'email' => 'chris.m@example.com'],
            ['name' => 'Amanda Wilson', 'email' => 'amanda.w@example.com'],
            ['name' => 'Ryan Taylor', 'email' => 'ryan.t@example.com'],
            ['name' => 'Nicole Anderson', 'email' => 'nicole.a@example.com'],
            ['name' => 'Kevin Thomas', 'email' => 'kevin.t@example.com'],
            ['name' => 'Laura Jackson', 'email' => 'laura.j@example.com'],
        ];

        // Review content templates by rating
        $review_templates = [
            5 => [
                ['title' => 'Absolutely fantastic!', 'content' => 'This exceeded all my expectations. The quality is outstanding and it arrived quickly. Highly recommend to anyone looking for this type of product.'],
                ['title' => 'Best purchase ever', 'content' => 'I have been using this for weeks now and I am extremely satisfied. Worth every penny! Would buy again in a heartbeat.'],
                ['title' => 'Perfect in every way', 'content' => 'Exactly what I was looking for. The build quality is excellent and it works flawlessly. Five stars well deserved.'],
                ['title' => 'Outstanding quality', 'content' => 'I did a lot of research before buying and this was the right choice. Premium materials and attention to detail are evident.'],
                ['title' => 'Love it!', 'content' => 'Could not be happier with this purchase. It has made such a difference in my daily routine. Shipping was fast too!'],
            ],
            4 => [
                ['title' => 'Very good product', 'content' => 'Overall a great purchase. A few minor things could be improved but nothing major. Would recommend to others.'],
                ['title' => 'Solid choice', 'content' => 'Does exactly what it says on the tin. Good value for money and decent quality. Happy with my purchase.'],
                ['title' => 'Great but not perfect', 'content' => 'Really like this product. The only reason I am not giving 5 stars is because the packaging could be better. Otherwise excellent!'],
                ['title' => 'Impressed', 'content' => 'Better than expected for the price. Works well and looks good. Would consider buying from this brand again.'],
                ['title' => 'Good value', 'content' => 'Happy with the quality considering the price point. Does everything I need it to do. Recommended.'],
            ],
            3 => [
                ['title' => 'Decent but could be better', 'content' => 'It is okay for the price. Does the job but there is definitely room for improvement. Average quality.'],
                ['title' => 'Average product', 'content' => 'Not bad, not great. It works but I have seen better options out there. Might try a different brand next time.'],
                ['title' => 'Mixed feelings', 'content' => 'Some aspects are good, others not so much. The product works but the quality is inconsistent in places.'],
                ['title' => 'It is alright', 'content' => 'Nothing special really. Gets the job done but do not expect premium quality at this price point.'],
            ],
            2 => [
                ['title' => 'Disappointed', 'content' => 'Not what I expected based on the description. Quality is below average and it took a while to arrive.'],
                ['title' => 'Could be much better', 'content' => 'Had high hopes but was let down. The product feels cheap and did not perform as advertised.'],
                ['title' => 'Not worth the money', 'content' => 'Regret this purchase. The quality does not match the price. Would not recommend to others.'],
            ],
            1 => [
                ['title' => 'Very poor quality', 'content' => 'Extremely disappointed with this purchase. Broke within a week of use. Complete waste of money.'],
                ['title' => 'Do not buy', 'content' => 'Worst product I have ever purchased. Does not work as described and customer service was unhelpful.'],
            ],
        ];

        // Get all products
        $products = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}ggmc_products ORDER BY id ASC");

        if (empty($products)) {
            return 0;
        }

        $created = 0;
        $reviews_table = $wpdb->prefix . 'ggmc_product_reviews';

        foreach ($products as $product) {
            // Random number of reviews per product (1-6)
            $num_reviews = wp_rand(1, 6);

            // Bias toward positive reviews (realistic distribution)
            $rating_weights = [
                5 => 40,  // 40% chance
                4 => 30,  // 30% chance
                3 => 15,  // 15% chance
                2 => 10,  // 10% chance
                1 => 5,   // 5% chance
            ];

            for ($i = 0; $i < $num_reviews; $i++) {
                // Select weighted random rating
                $rating = $this->weighted_random($rating_weights);

                // Get random reviewer
                $reviewer = $reviewers[array_rand($reviewers)];

                // Get random review template for this rating
                $templates = $review_templates[$rating];
                $template = $templates[array_rand($templates)];

                // Random verified purchase (60% chance)
                $verified = wp_rand(1, 100) <= 60 ? 1 : 0;

                // Random helpful votes (0-25)
                $helpful_votes = wp_rand(0, 25);

                // Random date in last 90 days
                $days_ago = wp_rand(0, 90);
                $created_at = gmdate('Y-m-d H:i:s', strtotime("-{$days_ago} days"));

                // Insert review
                $result = $wpdb->insert(
                    $reviews_table,
                    [
                        'product_id' => $product->id,
                        'customer_id' => null,
                        'author_name' => $reviewer['name'],
                        'author_email' => $reviewer['email'],
                        'rating' => $rating,
                        'title' => $template['title'],
                        'content' => $template['content'],
                        'status' => 'approved',
                        'verified_purchase' => $verified,
                        'helpful_votes' => $helpful_votes,
                        'ip_address' => '127.0.0.1',
                        'created_at' => $created_at,
                        'updated_at' => $created_at
                    ]
                );

                if ($result) {
                    $review_id = $wpdb->insert_id;
                    $this->register_test_item('review', $review_id);
                    $created++;
                }
            }

            // Recalculate product rating
            if (class_exists('GGM_Commerce_Reviews')) {
                GGM_Commerce_Reviews::recalculate_product_rating($product->id);
            }
        }

        return $created;
    }

    /**
     * Select a random value based on weights
     *
     * @param array $weights Associative array of value => weight
     * @return mixed Selected value
     */
    private function weighted_random($weights) {
        $total = array_sum($weights);
        $rand = wp_rand(1, $total);
        $current = 0;

        foreach ($weights as $value => $weight) {
            $current += $weight;
            if ($rand <= $current) {
                return $value;
            }
        }

        return array_key_first($weights);
    }

    /**
     * Create variation attributes for test products
     *
     * @return int Number of attributes created
     */
    public function create_variation_attributes() {
        if (!class_exists('GGM_Commerce_Variations')) {
            return 0;
        }

        $variations_manager = GGM_Commerce_Variations::instance();
        $created = 0;

        $attributes = [
            [
                'name' => 'Color',
                'slug' => 'test-color',
                'attribute_type' => 'select',
                'options' => [
                    ['value' => 'Red'],
                    ['value' => 'Blue'],
                    ['value' => 'Green'],
                    ['value' => 'Black'],
                    ['value' => 'White'],
                    ['value' => 'Silver'],
                    ['value' => 'Gold'],
                    ['value' => 'Brown']
                ]
            ],
            [
                'name' => 'Size',
                'slug' => 'test-size',
                'attribute_type' => 'select',
                'options' => [
                    ['value' => 'XS'],
                    ['value' => 'S'],
                    ['value' => 'M'],
                    ['value' => 'L'],
                    ['value' => 'XL'],
                    ['value' => 'XXL'],
                    ['value' => 'S/M'],
                    ['value' => 'M/L']
                ]
            ],
            [
                'name' => 'Storage',
                'slug' => 'test-storage',
                'attribute_type' => 'select',
                'options' => [
                    ['value' => '64GB'],
                    ['value' => '128GB'],
                    ['value' => '256GB'],
                    ['value' => '512GB'],
                    ['value' => '1TB']
                ]
            ],
            [
                'name' => 'RAM',
                'slug' => 'test-ram',
                'attribute_type' => 'select',
                'options' => [
                    ['value' => '8GB'],
                    ['value' => '16GB'],
                    ['value' => '32GB'],
                    ['value' => '64GB']
                ]
            ],
            [
                'name' => 'Material',
                'slug' => 'test-material',
                'attribute_type' => 'select',
                'options' => [
                    ['value' => 'Cotton'],
                    ['value' => 'Polyester'],
                    ['value' => 'Leather'],
                    ['value' => 'Wool'],
                    ['value' => 'Silk']
                ]
            ]
        ];

        foreach ($attributes as $attr_data) {
            // Check if variation type already exists by slug
            $existing = $variations_manager->get_variation_type_by_slug($attr_data['slug']);
            if ($existing) {
                continue;
            }

            $attr_id = $variations_manager->create_variation_type($attr_data);
            if ($attr_id) {
                $this->register_test_item('variation_attribute', $attr_id);
                $created++;
            }
        }

        return $created;
    }

    /**
     * Apply variations to test products
     *
     * @param array $product_map Array of product_id => product_name
     * @return array Results of variation application
     */
    public function apply_product_variations($product_map) {
        if (!class_exists('GGM_Commerce_Variations')) {
            return ['skipped' => 'Variations class not available'];
        }

        $variations_manager = GGM_Commerce_Variations::instance();
        $results = ['combined' => 0, 'independent' => 0, 'variations_created' => 0];

        // Get test variation type IDs by slug
        $color_attr = $variations_manager->get_variation_type_by_slug('test-color');
        $size_attr = $variations_manager->get_variation_type_by_slug('test-size');
        $storage_attr = $variations_manager->get_variation_type_by_slug('test-storage');
        $ram_attr = $variations_manager->get_variation_type_by_slug('test-ram');

        if (!$color_attr || !$size_attr || !$storage_attr || !$ram_attr) {
            return ['skipped' => 'Test attributes not found - generate attributes first'];
        }

        // Map product names to variation configs
        $variation_configs = [
            'iPhone 15 Pro Max' => [
                'mode' => 'combined',
                'stock_mode' => 'variation',
                'attributes' => [$storage_attr['id'], $color_attr['id']],
                'generate_subset' => [
                    $storage_attr['id'] => ['64GB', '128GB', '256GB'],
                    $color_attr['id'] => ['Black', 'White', 'Silver']
                ]
            ],
            'MacBook Air M3' => [
                'mode' => 'combined',
                'stock_mode' => 'variation',
                'attributes' => [$ram_attr['id'], $storage_attr['id']],
                'generate_subset' => [
                    $ram_attr['id'] => ['8GB', '16GB', '32GB'],
                    $storage_attr['id'] => ['256GB', '512GB']
                ]
            ],
            'Cotton Blend T-Shirt' => [
                'mode' => 'independent',
                'stock_mode' => 'parent',
                'attributes' => [$size_attr['id'], $color_attr['id']],
                'modifiers' => [
                    $size_attr['id'] => ['XS' => 0, 'S' => 0, 'M' => 0, 'L' => 2, 'XL' => 4, 'XXL' => 6],
                    $color_attr['id'] => ['Red' => 0, 'Blue' => 0, 'Green' => 0, 'Black' => 0, 'White' => 0]
                ],
                'defaults' => [
                    $size_attr['id'] => 'M',
                    $color_attr['id'] => 'Black'
                ]
            ],
            'Designer Leather Jacket' => [
                'mode' => 'independent',
                'stock_mode' => 'parent',
                'attributes' => [$size_attr['id'], $color_attr['id']],
                'modifiers' => [
                    $size_attr['id'] => ['S' => 0, 'M' => 0, 'L' => 20, 'XL' => 40],
                    $color_attr['id'] => ['Black' => 0, 'Brown' => 15]
                ],
                'defaults' => [
                    $size_attr['id'] => 'M',
                    $color_attr['id'] => 'Black'
                ]
            ],
            'Running Sneakers' => [
                'mode' => 'combined',
                'stock_mode' => 'variation',
                'attributes' => [$size_attr['id'], $color_attr['id']],
                'generate_subset' => [
                    $size_attr['id'] => ['S', 'M', 'L', 'XL'],
                    $color_attr['id'] => ['Red', 'Black', 'White']
                ]
            ],
            'Smart Fitness Watch' => [
                'mode' => 'combined',
                'stock_mode' => 'variation',
                'attributes' => [$color_attr['id'], $size_attr['id']],
                'generate_subset' => [
                    $color_attr['id'] => ['Black', 'Silver', 'Gold'],
                    $size_attr['id'] => ['S/M', 'M/L']
                ]
            ]
        ];

        // Apply variations to each configured product
        foreach ($product_map as $product_id => $product_name) {
            if (!isset($variation_configs[$product_name])) {
                continue;
            }

            $config = $variation_configs[$product_name];

            // Set has_variations and stock mode
            $variations_manager->set_product_has_variations($product_id, true, $config['stock_mode']);
            $variations_manager->set_product_variation_mode($product_id, $config['mode']);

            // Assign attributes to product
            $variations_manager->set_product_variation_config($product_id, $config['attributes']);

            // Register for cleanup
            $this->register_test_item('product_variation_config', $product_id);

            if ($config['mode'] === 'combined') {
                // Generate variations with subset of options
                $var_ids = $this->generate_subset_variations(
                    $product_id,
                    $config['attributes'],
                    $config['generate_subset'],
                    $variations_manager
                );

                foreach ($var_ids as $var_id) {
                    $this->register_test_item('product_variation', $var_id);
                    $results['variations_created']++;
                }

                $results['combined']++;
            } else {
                // Independent mode: initialize options with modifiers
                foreach ($config['attributes'] as $attr_id) {
                    // Initialize all options from the modifiers array
                    if (isset($config['modifiers'][$attr_id])) {
                        foreach ($config['modifiers'][$attr_id] as $value => $modifier) {
                            $is_default = isset($config['defaults'][$attr_id]) && $config['defaults'][$attr_id] === $value;
                            $variations_manager->add_product_variation_option(
                                $product_id,
                                $attr_id,
                                $value,
                                $modifier,
                                $is_default
                            );
                        }
                    }
                }

                $results['independent']++;
            }
        }

        return $results;
    }

    /**
     * Generate variations with a subset of attribute options
     *
     * @param int   $product_id        Product ID
     * @param array $attribute_ids     Array of attribute IDs
     * @param array $subset            Subset of options per attribute
     * @param object $variations_manager Variations manager instance
     * @return array Array of created variation IDs
     */
    private function generate_subset_variations($product_id, $attribute_ids, $subset, $variations_manager) {
        global $wpdb;
        $created_ids = [];

        // Build combinations from subset
        $combinations = $this->build_combinations($attribute_ids, $subset);

        // Get base product for pricing
        $base_product = $wpdb->get_row($wpdb->prepare(
            "SELECT price, sku FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
            $product_id
        ));

        $base_price = $base_product ? floatval($base_product->price) : 0;
        $base_sku = $base_product ? $base_product->sku : 'TEST';

        $variation_index = 1;
        foreach ($combinations as $combo) {
            // Check if variation already exists
            $existing = $variations_manager->get_variation_by_attributes($product_id, $combo);
            if ($existing) {
                continue;
            }

            // Create variation
            $var_id = $variations_manager->create_variation($product_id, [
                'sku' => $base_sku . '-V' . $variation_index,
                'price' => $base_price,
                'stock' => wp_rand(5, 50),
                'stock_status' => 'instock',
                'manage_stock' => 1,
                'price_type' => 'absolute',
                'status' => 'active'
            ], $combo);

            if ($var_id && !is_wp_error($var_id)) {
                $created_ids[] = $var_id;
                $variation_index++;
            }
        }

        // Set first variation as default
        if (!empty($created_ids)) {
            $variations_manager->update_variation($created_ids[0], ['is_default' => 1]);
        }

        return $created_ids;
    }

    /**
     * Build all combinations from attribute subsets
     *
     * @param array $attribute_ids Attribute IDs in order
     * @param array $subset        Values per attribute
     * @return array Array of combinations
     */
    private function build_combinations($attribute_ids, $subset) {
        $result = [[]];

        foreach ($attribute_ids as $attr_id) {
            if (!isset($subset[$attr_id])) {
                continue;
            }

            $new_result = [];
            foreach ($result as $combo) {
                foreach ($subset[$attr_id] as $value) {
                    $new_combo = $combo;
                    $new_combo[$attr_id] = $value;
                    $new_result[] = $new_combo;
                }
            }
            $result = $new_result;
        }

        return $result;
    }

    /**
     * Create kit and build products
     *
     * @param array $product_map Array of product_id => product_name
     * @return array Results
     */
    public function create_kits_and_builds($product_map) {
        if (!class_exists('GGM_Commerce_Kits') || !GGM_Commerce_Kits::is_feature_activated()) {
            return ['skipped' => 'product-kits module not activated'];
        }

        $kits_manager = GGM_Commerce_Kits::get_instance();
        $results = ['kits' => 0, 'builds' => 0, 'errors' => []];

        // Find products by name
        $product_ids_by_name = array_flip($product_map);

        // Kit: Educational Building Blocks Set
        if (isset($product_ids_by_name['Educational Building Blocks Set'])) {
            $kit_product_id = $product_ids_by_name['Educational Building Blocks Set'];

            // Find some simple products to use as components
            $component_products = $this->get_simple_component_products($product_map, 3);

            if (!empty($component_products)) {
                $components = [];
                foreach ($component_products as $comp_id) {
                    $components[] = ['product_id' => $comp_id, 'quantity' => 1];
                }

                $kit_id = $kits_manager->create_kit($kit_product_id, 'kit', $components, true);

                if (is_wp_error($kit_id)) {
                    $results['errors'][] = 'Educational Building Blocks Set: ' . $kit_id->get_error_message();
                } elseif ($kit_id) {
                    $this->register_test_item('product_kit', $kit_id);
                    $results['kits']++;
                }
            } else {
                $results['errors'][] = 'Educational Building Blocks Set: No component products found';
            }
        }

        // Kit: Essential Oils Starter Set
        if (isset($product_ids_by_name['Essential Oils Starter Set'])) {
            $kit_product_id = $product_ids_by_name['Essential Oils Starter Set'];

            // Use different products as components
            $component_products = $this->get_simple_component_products($product_map, 4, ['Essential Oils Starter Set', 'Educational Building Blocks Set']);

            if (!empty($component_products)) {
                $components = [];
                foreach ($component_products as $comp_id) {
                    $components[] = ['product_id' => $comp_id, 'quantity' => 1];
                }

                $kit_id = $kits_manager->create_kit($kit_product_id, 'kit', $components, true);
                if (is_wp_error($kit_id)) {
                    $results['errors'][] = 'Essential Oils Starter Set: ' . $kit_id->get_error_message();
                } elseif ($kit_id) {
                    $this->register_test_item('product_kit', $kit_id);
                    $results['kits']++;
                }
            } else {
                $results['errors'][] = 'Essential Oils Starter Set: No component products found';
            }
        }

        // Build: Camping Sleeping Bag
        if (isset($product_ids_by_name['Camping Sleeping Bag'])) {
            $build_product_id = $product_ids_by_name['Camping Sleeping Bag'];

            // Use simple products as components
            $component_products = $this->get_simple_component_products($product_map, 3, ['Camping Sleeping Bag', 'Essential Oils Starter Set', 'Educational Building Blocks Set']);

            if (!empty($component_products)) {
                $components = [];
                foreach ($component_products as $comp_id) {
                    $components[] = ['product_id' => $comp_id, 'quantity' => 1];
                }

                $build_id = $kits_manager->create_kit($build_product_id, 'build', $components, false);
                if (is_wp_error($build_id)) {
                    $results['errors'][] = 'Camping Sleeping Bag: ' . $build_id->get_error_message();
                } elseif ($build_id) {
                    $this->register_test_item('product_kit', $build_id);
                    $results['builds']++;
                }
            } else {
                $results['errors'][] = 'Camping Sleeping Bag: No component products found';
            }
        }

        return $results;
    }

    /**
     * Get simple products to use as kit components
     *
     * @param array $product_map     Product map
     * @param int   $count           Number of components needed
     * @param array $exclude         Product names to exclude
     * @return array Array of product IDs
     */
    private function get_simple_component_products($product_map, $count, $exclude = []) {
        $simple_products = [];

        // Products that are good for kit components (simple items)
        $good_components = [
            'Wireless Charging Pad',
            'Stainless Steel Water Bottle',
            'Organic Green Tea',
            'Puzzle 1000 Pieces',
            'LED Desk Lamp',
            'Yoga Mat Premium',
            'Luxury Silk Scarf',
            'Organic Face Moisturizer'
        ];

        $product_ids_by_name = array_flip($product_map);

        foreach ($good_components as $name) {
            if (in_array($name, $exclude)) {
                continue;
            }
            if (isset($product_ids_by_name[$name])) {
                $simple_products[] = $product_ids_by_name[$name];
                if (count($simple_products) >= $count) {
                    break;
                }
            }
        }

        return $simple_products;
    }

    /**
     * Create download files for digital products
     *
     * @param array $product_map Array of product_id => product_name
     * @return array Results
     */
    public function create_product_downloads($product_map) {
        global $wpdb;

        // Check if downloads module is available
        $downloads_active = false;
        if (function_exists('ggm_commerce_license')) {
            $license = ggm_commerce_license();
            $downloads_active = $license->is_widget_activated('downloads');
        }

        if (!$downloads_active) {
            return ['skipped' => 'downloads module not activated'];
        }

        $results = ['downloads' => 0, 'licenses' => 0];
        $product_ids_by_name = array_flip($product_map);

        // The Complete Guide to Web Development - Digital PDF
        if (isset($product_ids_by_name['The Complete Guide to Web Development'])) {
            $product_id = $product_ids_by_name['The Complete Guide to Web Development'];

            // Update product type
            $wpdb->update(
                "{$wpdb->prefix}ggmc_products",
                [
                    'product_type' => 'digital',
                    'is_downloadable' => 1,
                    'requires_shipping' => 0,
                    'download_access_mode' => 'unlimited'
                ],
                ['id' => $product_id]
            );

            // Add download file record
            $download_result = $wpdb->insert(
                "{$wpdb->prefix}ggmc_product_downloads",
                [
                    'product_id' => $product_id,
                    'name' => 'Complete Web Development Guide (PDF)',
                    'file_url' => 'https://example.com/downloads/web-dev-guide.pdf',
                    'file_type' => 'pdf',
                    'file_size' => 15728640, // 15MB
                    'download_limit' => -1,
                    'access_expiry_days' => -1,
                    'display_order' => 1,
                    'status' => 'active',
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ]
            );

            if ($download_result) {
                $this->register_test_item('product_download', $wpdb->insert_id);
                $results['downloads']++;
            }
        }

        // Premium Software License - License-based download
        if (isset($product_ids_by_name['Premium Software License'])) {
            $product_id = $product_ids_by_name['Premium Software License'];

            // Update product type
            $wpdb->update(
                "{$wpdb->prefix}ggmc_products",
                [
                    'product_type' => 'digital',
                    'is_downloadable' => 1,
                    'requires_shipping' => 0,
                    'download_access_mode' => 'license'
                ],
                ['id' => $product_id]
            );

            // Add download file
            $download_result = $wpdb->insert(
                "{$wpdb->prefix}ggmc_product_downloads",
                [
                    'product_id' => $product_id,
                    'name' => 'Premium Software Installer',
                    'file_url' => 'https://example.com/downloads/premium-software.zip',
                    'file_type' => 'zip',
                    'file_size' => 104857600, // 100MB
                    'download_limit' => 5,
                    'access_expiry_days' => 365,
                    'display_order' => 1,
                    'status' => 'active',
                    'created_at' => current_time('mysql'),
                    'updated_at' => current_time('mysql')
                ]
            );

            if ($download_result) {
                $this->register_test_item('product_download', $wpdb->insert_id);
                $results['downloads']++;
            }

            // Generate sample license keys
            for ($i = 1; $i <= 5; $i++) {
                $license_key = strtoupper(wp_generate_password(5, false) . '-' .
                               wp_generate_password(5, false) . '-' .
                               wp_generate_password(5, false) . '-' .
                               wp_generate_password(5, false));

                $license_result = $wpdb->insert(
                    "{$wpdb->prefix}ggmc_product_licenses",
                    [
                        'product_id' => $product_id,
                        'license_key' => $license_key,
                        'status' => 'available',
                        'max_activations' => 3,
                        'activations_count' => 0,
                        'created_at' => current_time('mysql'),
                        'updated_at' => current_time('mysql')
                    ]
                );

                if ($license_result) {
                    $this->register_test_item('product_license', $wpdb->insert_id);
                    $results['licenses']++;
                }
            }
        }

        return $results;
    }

    /**
     * Create custom attribute groups and attributes
     *
     * @return array Results with groups and attributes created
     */
    public function create_custom_attributes() {
        // Check if custom-attributes module is active
        if (!class_exists('GGM_Commerce_License') || !GGM_Commerce_License::instance()->is_widget_activated('custom-attributes')) {
            return ['skipped' => 'custom-attributes module not activated'];
        }

        if (!class_exists('GGM_Commerce_Attributes')) {
            return ['skipped' => 'GGM_Commerce_Attributes class not found'];
        }

        $attributes_manager = GGM_Commerce_Attributes::get_instance();
        $results = ['groups' => 0, 'attributes' => 0];

        // Define attribute groups with their attributes (icons stored as JSON for Elementor)
        $groups_data = [
            [
                'name' => 'Electronics Specifications',
                'description' => 'Technical specifications for electronic products',
                'attributes' => [
                    ['name' => 'Brand', 'icon' => 'fas fa-tag', 'attribute_type' => 'select', 'options' => ['Apple', 'Samsung', 'Sony', 'LG', 'Dell', 'HP', 'Lenovo']],
                    ['name' => 'Warranty', 'icon' => 'fas fa-shield-alt', 'attribute_type' => 'select', 'options' => ['1 Year', '2 Years', '3 Years', 'Lifetime']],
                    ['name' => 'Power Source', 'icon' => 'fas fa-plug', 'attribute_type' => 'select', 'options' => ['Battery', 'AC Power', 'USB', 'Solar']],
                    ['name' => 'Connectivity', 'icon' => 'fas fa-wifi', 'attribute_type' => 'select', 'options' => ['Bluetooth', 'WiFi', 'USB-C', 'Lightning', 'NFC']],
                    ['name' => 'Battery Life', 'icon' => 'fas fa-battery-full', 'attribute_type' => 'text'],
                    ['name' => 'Screen Size', 'icon' => 'fas fa-desktop', 'attribute_type' => 'text'],
                ]
            ],
            [
                'name' => 'Clothing Details',
                'description' => 'Material and care information for clothing items',
                'attributes' => [
                    ['name' => 'Material', 'icon' => 'fas fa-tshirt', 'attribute_type' => 'select', 'options' => ['100% Cotton', '100% Polyester', 'Cotton Blend', 'Wool', 'Silk', 'Linen', 'Leather']],
                    ['name' => 'Care Instructions', 'icon' => 'fas fa-hand-sparkles', 'attribute_type' => 'select', 'options' => ['Machine Wash', 'Hand Wash Only', 'Dry Clean Only', 'Spot Clean']],
                    ['name' => 'Fit', 'icon' => 'fas fa-ruler', 'attribute_type' => 'select', 'options' => ['Slim Fit', 'Regular Fit', 'Relaxed Fit', 'Oversized']],
                    ['name' => 'Season', 'icon' => 'fas fa-sun', 'attribute_type' => 'select', 'options' => ['Spring/Summer', 'Fall/Winter', 'All Season']],
                    ['name' => 'Country of Origin', 'icon' => 'fas fa-globe', 'attribute_type' => 'text'],
                ]
            ],
            [
                'name' => 'Food & Beverages',
                'description' => 'Nutritional and dietary information',
                'attributes' => [
                    ['name' => 'Dietary', 'icon' => 'fas fa-leaf', 'attribute_type' => 'select', 'options' => ['Vegan', 'Vegetarian', 'Gluten-Free', 'Organic', 'Non-GMO', 'Kosher', 'Halal']],
                    ['name' => 'Allergens', 'icon' => 'fas fa-exclamation-triangle', 'attribute_type' => 'text'],
                    ['name' => 'Serving Size', 'icon' => 'fas fa-utensils', 'attribute_type' => 'text'],
                    ['name' => 'Shelf Life', 'icon' => 'fas fa-calendar-alt', 'attribute_type' => 'text'],
                ]
            ],
            [
                'name' => 'General Product Info',
                'description' => 'General product specifications',
                'attributes' => [
                    ['name' => 'Manufacturer', 'icon' => 'fas fa-industry', 'attribute_type' => 'text'],
                    ['name' => 'Model Number', 'icon' => 'fas fa-hashtag', 'attribute_type' => 'text'],
                    ['name' => 'UPC', 'icon' => 'fas fa-barcode', 'attribute_type' => 'text'],
                    ['name' => 'Age Range', 'icon' => 'fas fa-child', 'attribute_type' => 'select', 'options' => ['All Ages', '3+', '6+', '12+', '18+', 'Adults Only']],
                ]
            ]
        ];

        $attribute_ids = []; // Track created attribute IDs by name

        foreach ($groups_data as $group_data) {
            // Create the group
            $group_id = $attributes_manager->create_attribute_group([
                'name' => $group_data['name'],
                'description' => $group_data['description'],
                'status' => 'active'
            ]);

            if (is_wp_error($group_id)) {
                continue;
            }

            $this->register_test_item('custom_attribute_group', $group_id);
            $results['groups']++;

            // Create attributes for this group
            foreach ($group_data['attributes'] as $attr_data) {
                // Prepare icon in JSON format for Elementor (same format as preset imports)
                $icon_json = '';
                if (!empty($attr_data['icon'])) {
                    $icon_json = wp_json_encode([
                        'value'   => $attr_data['icon'],
                        'library' => 'fa-solid',
                    ]);
                }

                $attr_id = $attributes_manager->create_attribute([
                    'name' => $attr_data['name'],
                    'attribute_type' => $attr_data['attribute_type'],
                    'icon' => $icon_json,
                    'options' => isset($attr_data['options']) ? $attr_data['options'] : [],
                    'group_id' => $group_id,
                    'status' => 'active'
                ]);

                if (!is_wp_error($attr_id)) {
                    $this->register_test_item('custom_attribute', $attr_id);
                    $results['attributes']++;
                    $attribute_ids[$attr_data['name']] = $attr_id;
                }
            }
        }

        // Store attribute IDs for later use when assigning to products
        $this->custom_attribute_ids = $attribute_ids;

        return $results;
    }

    /**
     * Store for custom attribute IDs
     */
    private $custom_attribute_ids = [];

    /**
     * Get custom attribute IDs
     */
    public function get_custom_attribute_ids() {
        return $this->custom_attribute_ids;
    }

    /**
     * Assign custom attributes to products
     *
     * @param array $product_map Array of product_id => product_name
     * @return array Results
     */
    public function assign_custom_attributes_to_products($product_map) {
        global $wpdb;

        // Check if custom-attributes module is active
        if (!class_exists('GGM_Commerce_License') || !GGM_Commerce_License::instance()->is_widget_activated('custom-attributes')) {
            return ['skipped' => 'custom-attributes module not activated'];
        }

        if (!class_exists('GGM_Commerce_Attributes')) {
            return ['skipped' => 'GGM_Commerce_Attributes class not found'];
        }

        $attributes_manager = GGM_Commerce_Attributes::get_instance();
        $results = ['products_updated' => 0, 'values_assigned' => 0];

        // Get all custom attributes by name
        $all_attrs = $wpdb->get_results("SELECT id, name FROM {$wpdb->prefix}ggmc_attributes WHERE status = 'active'");
        $attr_by_name = [];
        foreach ($all_attrs as $attr) {
            $attr_by_name[$attr->name] = $attr->id;
        }

        // Define which products get which attributes
        $product_attributes = [
            // Electronics
            'iPhone 15 Pro Max' => [
                'Brand' => 'Apple',
                'Warranty' => '1 Year',
                'Connectivity' => 'Lightning',
                'Screen Size' => '6.7 inches',
                'Battery Life' => 'Up to 29 hours video playback'
            ],
            'Wireless Bluetooth Headphones' => [
                'Brand' => 'Sony',
                'Warranty' => '2 Years',
                'Power Source' => 'Battery',
                'Connectivity' => 'Bluetooth',
                'Battery Life' => '30 hours'
            ],
            'MacBook Air M3' => [
                'Brand' => 'Apple',
                'Warranty' => '1 Year',
                'Screen Size' => '13.6 inches',
                'Battery Life' => 'Up to 18 hours'
            ],
            'Smart Coffee Maker' => [
                'Brand' => 'Samsung',
                'Warranty' => '2 Years',
                'Power Source' => 'AC Power',
                'Connectivity' => 'WiFi'
            ],
            'Gaming Mechanical Keyboard' => [
                'Brand' => 'Lenovo',
                'Warranty' => '2 Years',
                'Connectivity' => 'USB-C'
            ],
            'Wireless Charging Pad' => [
                'Brand' => 'Samsung',
                'Warranty' => '1 Year',
                'Power Source' => 'USB',
                'Connectivity' => 'USB-C'
            ],
            'Smart Fitness Watch' => [
                'Brand' => 'Samsung',
                'Warranty' => '1 Year',
                'Power Source' => 'Battery',
                'Connectivity' => 'Bluetooth',
                'Battery Life' => '7 days'
            ],
            'LED Desk Lamp' => [
                'Brand' => 'LG',
                'Warranty' => '1 Year',
                'Power Source' => 'USB'
            ],
            'Bluetooth Speaker Portable' => [
                'Brand' => 'Sony',
                'Warranty' => '1 Year',
                'Power Source' => 'Battery',
                'Connectivity' => 'Bluetooth',
                'Battery Life' => '20 hours'
            ],
            // Clothing
            'Cotton Blend T-Shirt' => [
                'Material' => 'Cotton Blend',
                'Care Instructions' => 'Machine Wash',
                'Fit' => 'Regular Fit',
                'Season' => 'All Season',
                'Country of Origin' => 'Bangladesh'
            ],
            'Designer Leather Jacket' => [
                'Material' => 'Leather',
                'Care Instructions' => 'Dry Clean Only',
                'Fit' => 'Slim Fit',
                'Season' => 'Fall/Winter',
                'Country of Origin' => 'Italy'
            ],
            'Running Sneakers' => [
                'Material' => '100% Polyester',
                'Season' => 'All Season',
                'Country of Origin' => 'Vietnam'
            ],
            'Luxury Silk Scarf' => [
                'Material' => 'Silk',
                'Care Instructions' => 'Hand Wash Only',
                'Season' => 'Spring/Summer',
                'Country of Origin' => 'France'
            ],
            // Food & Beverages
            'Organic Green Tea' => [
                'Dietary' => 'Organic',
                'Serving Size' => '2g per cup',
                'Shelf Life' => '24 months'
            ],
            'Gourmet Coffee Beans' => [
                'Dietary' => 'Non-GMO',
                'Serving Size' => '15g per cup',
                'Shelf Life' => '12 months'
            ],
            // General products
            'Yoga Mat Premium' => [
                'Manufacturer' => 'YogaLife Inc.',
                'Age Range' => 'All Ages'
            ],
            'Puzzle 1000 Pieces' => [
                'Manufacturer' => 'Ravensburger',
                'Age Range' => '12+',
                'Model Number' => 'PZL-1000-NATURE'
            ],
            'Educational Building Blocks Set' => [
                'Manufacturer' => 'LEGO',
                'Age Range' => '6+',
                'Model Number' => 'EBB-500'
            ],
            'Stainless Steel Water Bottle' => [
                'Manufacturer' => 'HydroFlask',
                'Model Number' => 'WB-32OZ-SS'
            ],
            'Ergonomic Office Chair' => [
                'Manufacturer' => 'Herman Miller',
                'Warranty' => '3 Years',
                'Model Number' => 'EOC-PRO-2024'
            ],
            'Anti-Aging Face Serum' => [
                'Allergens' => 'Contains fragrance',
                'Shelf Life' => '18 months'
            ],
            'Organic Face Moisturizer' => [
                'Dietary' => 'Organic',
                'Allergens' => 'None',
                'Shelf Life' => '12 months'
            ]
        ];

        $product_ids_by_name = array_flip($product_map);

        foreach ($product_attributes as $product_name => $attrs) {
            if (!isset($product_ids_by_name[$product_name])) {
                continue;
            }

            $product_id = $product_ids_by_name[$product_name];
            $values = [];
            $order = 0;

            foreach ($attrs as $attr_name => $attr_value) {
                if (!isset($attr_by_name[$attr_name])) {
                    continue;
                }

                $values[] = [
                    'attribute_id' => $attr_by_name[$attr_name],
                    'value' => $attr_value,
                    'display_order' => $order++
                ];
            }

            if (!empty($values)) {
                $result = $attributes_manager->set_product_attribute_values($product_id, $values);
                if ($result) {
                    $results['products_updated']++;
                    $results['values_assigned'] += count($values);

                    // Register each product attribute value for cleanup
                    foreach ($values as $val) {
                        // Get the inserted ID
                        $pav_id = $wpdb->get_var($wpdb->prepare(
                            "SELECT id FROM {$wpdb->prefix}ggmc_product_attribute_values
                             WHERE product_id = %d AND attribute_id = %d",
                            $product_id,
                            $val['attribute_id']
                        ));
                        if ($pav_id) {
                            $this->register_test_item('product_attribute_value', $pav_id);
                        }
                    }
                }
            }
        }

        return $results;
    }

    /**
     * Create test customers with addresses
     *
     * @return int Number of customers created
     */
    private function create_customers() {
        global $wpdb;

        $customers_data = [
            ['first_name' => 'Emma', 'last_name' => 'Thompson', 'phone' => '+44 7700 900123', 'company' => 'Thompson Design Ltd', 'address' => ['address_1' => '14 Baker Street', 'city' => 'London', 'state' => 'Greater London', 'postcode' => 'NW1 6XE', 'country' => 'GB']],
            ['first_name' => 'James', 'last_name' => 'Wilson', 'phone' => '+44 7700 900456', 'company' => '', 'address' => ['address_1' => '7 Castle Road', 'city' => 'Edinburgh', 'state' => 'Midlothian', 'postcode' => 'EH1 2NG', 'country' => 'GB']],
            ['first_name' => 'Sarah', 'last_name' => 'Mitchell', 'phone' => '+1 555-0147', 'company' => 'Mitchell & Co', 'address' => ['address_1' => '250 Park Avenue', 'address_2' => 'Suite 400', 'city' => 'New York', 'state' => 'NY', 'postcode' => '10177', 'country' => 'US']],
            ['first_name' => 'Oliver', 'last_name' => 'Brown', 'phone' => '+44 7700 900789', 'company' => '', 'address' => ['address_1' => '23 Queens Drive', 'city' => 'Manchester', 'state' => 'Greater Manchester', 'postcode' => 'M20 4BX', 'country' => 'GB']],
            ['first_name' => 'Rachel', 'last_name' => 'Davis', 'phone' => '+1 555-0298', 'company' => 'Davis Consulting', 'address' => ['address_1' => '1830 Elm Street', 'city' => 'San Francisco', 'state' => 'CA', 'postcode' => '94107', 'country' => 'US']],
            ['first_name' => 'William', 'last_name' => 'Clarke', 'phone' => '+44 7700 901234', 'company' => 'Clarke Electronics', 'address' => ['address_1' => '9 Victoria Lane', 'city' => 'Birmingham', 'state' => 'West Midlands', 'postcode' => 'B1 1BB', 'country' => 'GB']],
            ['first_name' => 'Lucy', 'last_name' => 'Taylor', 'phone' => '+44 7700 901567', 'company' => '', 'address' => ['address_1' => '42 Harbour View', 'city' => 'Bristol', 'state' => 'Bristol', 'postcode' => 'BS1 4DJ', 'country' => 'GB']],
            ['first_name' => 'Michael', 'last_name' => 'Anderson', 'phone' => '+1 555-0371', 'company' => 'Anderson Tech', 'address' => ['address_1' => '500 Congress Ave', 'address_2' => 'Floor 12', 'city' => 'Austin', 'state' => 'TX', 'postcode' => '78701', 'country' => 'US']],
            ['first_name' => 'Charlotte', 'last_name' => 'Evans', 'phone' => '+44 7700 901890', 'company' => '', 'address' => ['address_1' => '18 Park Crescent', 'city' => 'Cardiff', 'state' => 'South Glamorgan', 'postcode' => 'CF10 3DQ', 'country' => 'GB']],
            ['first_name' => 'David', 'last_name' => 'Roberts', 'phone' => '+1 555-0482', 'company' => 'Roberts & Sons', 'address' => ['address_1' => '77 Maple Drive', 'city' => 'Chicago', 'state' => 'IL', 'postcode' => '60601', 'country' => 'US']],
            ['first_name' => 'Hannah', 'last_name' => 'White', 'phone' => '+44 7700 902123', 'company' => '', 'address' => ['address_1' => '5 Riverside Walk', 'city' => 'Oxford', 'state' => 'Oxfordshire', 'postcode' => 'OX1 1PT', 'country' => 'GB']],
            ['first_name' => 'Thomas', 'last_name' => 'Hughes', 'phone' => '+1 555-0593', 'company' => 'Hughes Imports', 'address' => ['address_1' => '2100 Ocean Boulevard', 'city' => 'Los Angeles', 'state' => 'CA', 'postcode' => '90401', 'country' => 'US']],
        ];

        // Customers with separate shipping addresses
        $shipping_addresses = [
            'Sarah'   => ['address_1' => '88 Warehouse District', 'city' => 'Brooklyn', 'state' => 'NY', 'postcode' => '11201', 'country' => 'US'],
            'William' => ['address_1' => '15 Industrial Park', 'address_2' => 'Unit 3', 'city' => 'Solihull', 'state' => 'West Midlands', 'postcode' => 'B91 3DA', 'country' => 'GB'],
            'Michael' => ['address_1' => '200 Commerce Street', 'city' => 'Dallas', 'state' => 'TX', 'postcode' => '75201', 'country' => 'US'],
            'Thomas'  => ['address_1' => '450 Distribution Way', 'city' => 'Long Beach', 'state' => 'CA', 'postcode' => '90802', 'country' => 'US'],
        ];

        $created = 0;

        foreach ($customers_data as $data) {
            $email = 'test-' . strtolower($data['first_name']) . '@example.com';

            // Check if already exists
            $existing = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}ggmc_customers WHERE email = %s",
                $email
            ));

            if ($existing) {
                $this->customers[] = $existing;
                continue;
            }

            // Create WordPress user (same as real registration flow)
            $username = 'test-' . strtolower($data['first_name']);
            $password = wp_generate_password(16, true, true);
            $user_id = wp_create_user($username, $password, $email);

            if (is_wp_error($user_id)) {
                continue;
            }

            // Set customer role and user meta
            $wp_user = new WP_User($user_id);
            $wp_user->set_role('ggmc_customer');
            update_user_meta($user_id, 'first_name', $data['first_name']);
            update_user_meta($user_id, 'last_name', $data['last_name']);
            $this->register_test_item('wp_user', $user_id);

            // Create customer record linked to WordPress user
            $result = $wpdb->insert(
                "{$wpdb->prefix}ggmc_customers",
                [
                    'user_id'      => $user_id,
                    'email'        => $email,
                    'first_name'   => $data['first_name'],
                    'last_name'    => $data['last_name'],
                    'phone'        => $data['phone'],
                    'company'      => $data['company'],
                    'account_type' => !empty($data['company']) ? 'business' : 'individual',
                    'created_at'   => current_time('mysql'),
                    'updated_at'   => current_time('mysql'),
                ]
            );

            if ($result) {
                $customer_id = $wpdb->insert_id;
                $this->customers[] = $customer_id;
                $this->register_test_item('customer', $customer_id);
                $created++;

                // Insert billing address
                $addr = $data['address'];
                $wpdb->insert(
                    "{$wpdb->prefix}ggmc_customer_addresses",
                    [
                        'customer_id'   => $customer_id,
                        'address_type'  => 'billing',
                        'is_default'    => 1,
                        'address_label' => 'Home',
                        'first_name'    => $data['first_name'],
                        'last_name'     => $data['last_name'],
                        'company'       => $data['company'],
                        'address_1'     => $addr['address_1'],
                        'address_2'     => isset($addr['address_2']) ? $addr['address_2'] : '',
                        'city'          => $addr['city'],
                        'state'         => $addr['state'],
                        'postcode'      => $addr['postcode'],
                        'country'       => $addr['country'],
                        'phone'         => $data['phone'],
                        'created_at'    => current_time('mysql'),
                    ]
                );
                if ($wpdb->insert_id) {
                    $this->register_test_item('customer_address', $wpdb->insert_id);
                }

                // Insert shipping address if this customer has one
                if (isset($shipping_addresses[$data['first_name']])) {
                    $ship = $shipping_addresses[$data['first_name']];
                    $wpdb->insert(
                        "{$wpdb->prefix}ggmc_customer_addresses",
                        [
                            'customer_id'   => $customer_id,
                            'address_type'  => 'shipping',
                            'is_default'    => 1,
                            'address_label' => 'Warehouse',
                            'first_name'    => $data['first_name'],
                            'last_name'     => $data['last_name'],
                            'company'       => $data['company'],
                            'address_1'     => $ship['address_1'],
                            'address_2'     => isset($ship['address_2']) ? $ship['address_2'] : '',
                            'city'          => $ship['city'],
                            'state'         => $ship['state'],
                            'postcode'      => $ship['postcode'],
                            'country'       => $ship['country'],
                            'phone'         => $data['phone'],
                            'created_at'    => current_time('mysql'),
                        ]
                    );
                    if ($wpdb->insert_id) {
                        $this->register_test_item('customer_address', $wpdb->insert_id);
                    }
                }
            }
        }

        return $created;
    }

    /**
     * Create test orders with order items
     *
     * @return int Number of orders created
     */
    private function create_orders() {
        global $wpdb;

        // Get test customers
        if (empty($this->customers)) {
            $this->customers = $this->get_test_items('customer');
        }

        if (empty($this->customers)) {
            return 0;
        }

        // Get test products
        $test_product_ids = $this->get_test_items('product');
        if (empty($test_product_ids)) {
            return 0;
        }

        // Fetch product details for order items
        $ids_placeholder = implode(',', array_map('intval', $test_product_ids));
        $products = $wpdb->get_results(
            "SELECT id, name, sku, price FROM {$wpdb->prefix}ggmc_products WHERE id IN ($ids_placeholder)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            ARRAY_A
        );

        if (empty($products)) {
            return 0;
        }

        // Fetch customer details
        $cust_placeholder = implode(',', array_map('intval', $this->customers));
        $customer_rows = $wpdb->get_results(
            "SELECT c.*, a.address_1 AS billing_address_1, a.address_2 AS billing_address_2,
                    a.city AS billing_city, a.state AS billing_state, a.country AS billing_country,
                    a.postcode AS billing_postcode
             FROM {$wpdb->prefix}ggmc_customers c
             LEFT JOIN {$wpdb->prefix}ggmc_customer_addresses a ON a.customer_id = c.id AND a.address_type = 'billing' AND a.is_default = 1
             WHERE c.id IN ($cust_placeholder)", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            ARRAY_A
        );

        if (empty($customer_rows)) {
            return 0;
        }

        // Also fetch shipping addresses
        $shipping_rows = $wpdb->get_results(
            "SELECT customer_id, address_1, address_2, city, state, country, postcode
             FROM {$wpdb->prefix}ggmc_customer_addresses
             WHERE customer_id IN ($cust_placeholder) AND address_type = 'shipping' AND is_default = 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            ARRAY_A
        );
        $shipping_map = [];
        foreach ($shipping_rows as $row) {
            $shipping_map[$row['customer_id']] = $row;
        }

        $status_weights = [
            'completed'  => 40,
            'processing' => 25,
            'pending'    => 15,
            'shipped'    => 10,
            'cancelled'  => 10,
        ];

        $payment_weights = [
            'stripe'        => 50,
            'paypal'        => 30,
            'bank_transfer' => 20,
        ];

        $created = 0;
        $order_count = 20;
        $customer_totals = []; // Track per-customer totals

        for ($i = 0; $i < $order_count; $i++) {
            // Generate unique order number
            do {
                $order_number = 'GGMC-' . gmdate('Y') . '-' . str_pad(wp_rand(1, 999999), 6, '0', STR_PAD_LEFT);
                $exists = $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}ggmc_orders WHERE order_number = %s",
                    $order_number
                ));
            } while ($exists > 0);

            // Pick random customer
            $customer = $customer_rows[array_rand($customer_rows)];
            $cust_id = (int) $customer['id'];

            // Pick shipping address (use billing if no separate shipping)
            $shipping = isset($shipping_map[$cust_id]) ? $shipping_map[$cust_id] : $customer;

            // Pick 1-5 random products
            $num_items = wp_rand(1, 5);
            $item_keys = array_rand($products, min($num_items, count($products)));
            if (!is_array($item_keys)) {
                $item_keys = [$item_keys];
            }

            // Calculate order totals
            $subtotal = 0;
            $order_items = [];
            foreach ($item_keys as $key) {
                $product = $products[$key];
                $quantity = wp_rand(1, 3);
                $price = (float) $product['price'];
                $line_total = $price * $quantity;
                $subtotal += $line_total;

                $order_items[] = [
                    'product_id'   => (int) $product['id'],
                    'product_name' => $product['name'],
                    'product_sku'  => $product['sku'],
                    'quantity'     => $quantity,
                    'price'        => $price,
                    'total'        => $line_total,
                ];
            }

            $tax_rate = 20.00;
            $tax_amount = round($subtotal * ($tax_rate / 100), 2);
            $shipping_amount = $subtotal > 50 ? 0.00 : round(wp_rand(299, 999) / 100, 2);
            $total_amount = $subtotal + $tax_amount + $shipping_amount;

            $status = $this->weighted_random($status_weights);
            $payment_method = $this->weighted_random($payment_weights);

            // Determine payment status from order status
            if (in_array($status, ['completed', 'shipped', 'processing'], true)) {
                $payment_status = 'paid';
            } elseif ($status === 'cancelled') {
                $payment_status = 'refunded';
            } else {
                $payment_status = 'pending';
            }

            // Spread dates over 90 days
            $days_ago = wp_rand(0, 90);
            $created_at = gmdate('Y-m-d H:i:s', strtotime("-{$days_ago} days"));

            $order_data = [
                'order_number'        => $order_number,
                'user_id'             => (int) $customer['user_id'],
                'customer_id'         => $cust_id,
                'customer_email'      => $customer['email'],
                'customer_first_name' => $customer['first_name'],
                'customer_last_name'  => $customer['last_name'],
                'customer_phone'      => $customer['phone'],
                'billing_address_1'   => $customer['billing_address_1'],
                'billing_address_2'   => isset($customer['billing_address_2']) ? $customer['billing_address_2'] : '',
                'billing_city'        => $customer['billing_city'],
                'billing_state'       => $customer['billing_state'],
                'billing_country'     => $customer['billing_country'],
                'billing_postcode'    => $customer['billing_postcode'],
                'shipping_address_1'  => isset($shipping['address_1']) ? $shipping['address_1'] : $customer['billing_address_1'],
                'shipping_address_2'  => isset($shipping['address_2']) ? $shipping['address_2'] : '',
                'shipping_city'       => isset($shipping['city']) ? $shipping['city'] : $customer['billing_city'],
                'shipping_state'      => isset($shipping['state']) ? $shipping['state'] : $customer['billing_state'],
                'shipping_country'    => isset($shipping['country']) ? $shipping['country'] : $customer['billing_country'],
                'shipping_postcode'   => isset($shipping['postcode']) ? $shipping['postcode'] : $customer['billing_postcode'],
                'subtotal'            => $subtotal,
                'tax_amount'          => $tax_amount,
                'tax_rate'            => $tax_rate,
                'tax_label'           => 'VAT',
                'prices_include_tax'  => 0,
                'shipping_amount'     => $shipping_amount,
                'total_amount'        => $total_amount,
                'status'              => $status,
                'payment_method'      => $payment_method,
                'payment_status'      => $payment_status,
                'payment_transaction_id' => $payment_status === 'paid' ? 'txn_test_' . wp_rand(100000, 999999) : '',
                'created_at'          => $created_at,
                'updated_at'          => $created_at,
            ];

            $inserted = $wpdb->insert("{$wpdb->prefix}ggmc_orders", $order_data);

            if ($inserted) {
                $order_id = $wpdb->insert_id;
                $this->register_test_item('order', $order_id);
                $created++;

                // Insert order items
                foreach ($order_items as $item) {
                    $item['order_id'] = $order_id;
                    $item['created_at'] = $created_at;
                    $wpdb->insert("{$wpdb->prefix}ggmc_order_items", $item);
                    if ($wpdb->insert_id) {
                        $this->register_test_item('order_item', $wpdb->insert_id);
                    }
                }

                // Track per-customer totals (only for non-cancelled orders)
                if ($status !== 'cancelled') {
                    if (!isset($customer_totals[$cust_id])) {
                        $customer_totals[$cust_id] = ['orders' => 0, 'spent' => 0, 'last_date' => ''];
                    }
                    $customer_totals[$cust_id]['orders']++;
                    $customer_totals[$cust_id]['spent'] += $total_amount;
                    if ($created_at > $customer_totals[$cust_id]['last_date']) {
                        $customer_totals[$cust_id]['last_date'] = $created_at;
                    }
                }
            }
        }

        // Update customer aggregate fields
        foreach ($customer_totals as $cust_id => $totals) {
            $wpdb->update(
                "{$wpdb->prefix}ggmc_customers",
                [
                    'total_orders'    => $totals['orders'],
                    'total_spent'     => round($totals['spent'], 2),
                    'last_order_date' => $totals['last_date'],
                    'updated_at'      => current_time('mysql'),
                ],
                ['id' => $cust_id]
            );
        }

        return $created;
    }
}

// Note: GGM_Commerce_Test_Data_Generator is initialized in the main plugin file