*/ private static $wc_header_map = array( // Core identity. 'id' => 'id', 'type' => 'type', 'sku' => 'sku', 'name' => 'name', 'slug' => 'slug', // Status / visibility. 'published' => 'status', 'status' => 'status', 'is featured?' => 'featured', 'visibility in catalog' => 'catalog_visibility', 'catalog visibility' => 'catalog_visibility', // Content. 'description' => 'description', 'short description' => 'short_description', 'purchase note' => 'purchase_note', // Pricing. 'regular price' => 'regular_price', 'sale price' => 'sale_price', 'date sale price starts' => 'date_on_sale_from', 'date sale price ends' => 'date_on_sale_to', // Tax. 'tax status' => 'tax_status', 'tax class' => 'tax_class', // Stock. 'in stock?' => 'stock_status', 'stock' => 'stock_quantity', 'low stock amount' => 'low_stock_amount', 'backorders allowed?' => 'backorders', 'sold individually?' => 'sold_individually', // Dimensions — unit suffix stripped by normalize_header() before lookup. 'weight' => 'weight', 'length' => 'length', 'width' => 'width', 'height' => 'height', // Relations. 'upsells' => 'upsell_ids', 'cross-sells' => 'cross_sell_ids', 'grouped products' => 'children', 'parent' => 'parent_id', // Taxonomy / media. 'categories' => 'category_ids', 'tags' => 'tag_ids', 'shipping class' => 'shipping_class_id', 'images' => 'images', // External / virtual. 'external url' => 'product_url', 'button text' => 'button_text', 'allow customer reviews?' => 'reviews_allowed', // Downloads. 'download limit' => 'download_limit', 'download expiry days' => 'download_expiry', // Misc. 'position' => 'menu_order', ); /** * Values that WooCommerce native export uses for the "Published" / status column. * Maps to strings the import-export plugin's wt_parse_published_field() accepts. * * @var array */ private static $wc_status_values = array( '1' => 'publish', '0' => 'draft', '-1' => 'private', ); /** * Values that WooCommerce native export uses for "In stock?" column. * * @var array */ private static $wc_stock_status_values = array( '1' => 'instock', '0' => 'outofstock', ); /** * Register the AJAX hook. * Called once from the main plugin loader or admin bubble constructor. * * @return void */ public static function register() { add_action( 'wp_ajax_' . self::AJAX_ACTION, array( __CLASS__, 'ajax_handler' ) ); } /** * Returns true when the import-export plugin's product filter is registered, * meaning the plugin is active and loaded. * * @return bool */ public static function is_dependency_active() { return has_filter( 'wt_iew_importer_do_import_basic' ); } // ------------------------------------------------------------------------- // AJAX Handler // ------------------------------------------------------------------------- /** * wp_ajax handler for wtofe_chatbot_import_csv. * * Validates permissions, parses the uploaded CSV, runs the import via the * import-export plugin, and returns a chatbot-ready HTML reply. * * @return void Exits via wp_send_json_*. */ public static function ajax_handler() { check_ajax_referer( 'wtofe_chatbot_import_nonce', 'nonce' ); if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-content-generator-for-woocommerce' ) ) ); } if ( ! self::is_dependency_active() ) { wp_send_json_error( array( 'message' => __( 'The "Product Import Export for WooCommerce" plugin must be active to use CSV import.', 'ai-content-generator-for-woocommerce' ), ) ); } // ── Validate uploaded file ──────────────────────────────────────────── $file_error = isset( $_FILES['csv_file']['error'] ) ? (int) $_FILES['csv_file']['error'] : UPLOAD_ERR_NO_FILE; if ( UPLOAD_ERR_OK !== $file_error ) { $error_messages = array( UPLOAD_ERR_INI_SIZE => __( 'File exceeds upload_max_filesize.', 'ai-content-generator-for-woocommerce' ), UPLOAD_ERR_FORM_SIZE => __( 'File exceeds MAX_FILE_SIZE form directive.', 'ai-content-generator-for-woocommerce' ), UPLOAD_ERR_PARTIAL => __( 'File was only partially uploaded.', 'ai-content-generator-for-woocommerce' ), UPLOAD_ERR_NO_FILE => __( 'No file was uploaded.', 'ai-content-generator-for-woocommerce' ), UPLOAD_ERR_NO_TMP_DIR => __( 'Missing temporary folder.', 'ai-content-generator-for-woocommerce' ), UPLOAD_ERR_CANT_WRITE => __( 'Failed to write file to disk.', 'ai-content-generator-for-woocommerce' ), ); $msg = isset( $error_messages[ $file_error ] ) ? $error_messages[ $file_error ] : __( 'Unknown upload error.', 'ai-content-generator-for-woocommerce' ); wp_send_json_error( array( 'message' => $msg ) ); } $tmp_path = isset( $_FILES['csv_file']['tmp_name'] ) ? $_FILES['csv_file']['tmp_name'] : ''; // phpcs:ignore $raw_name = isset( $_FILES['csv_file']['name'] ) ? $_FILES['csv_file']['name'] : 'import.csv'; // phpcs:ignore $file_name = sanitize_file_name( $raw_name ); if ( 'csv' !== strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) ) ) { wp_send_json_error( array( 'message' => __( 'Only .csv files are accepted.', 'ai-content-generator-for-woocommerce' ) ) ); } if ( ! is_uploaded_file( $tmp_path ) ) { wp_send_json_error( array( 'message' => __( 'Invalid file upload.', 'ai-content-generator-for-woocommerce' ) ) ); } // ── Load CSV reader from import-export plugin (confirms installation path) ─ $csv_reader_path = WP_PLUGIN_DIR . '/' . self::IEW_PLUGIN . '/admin/classes/class-csvreader.php'; if ( ! file_exists( $csv_reader_path ) ) { wp_send_json_error( array( 'message' => __( 'Import plugin CSV reader not found. Ensure "Product Import Export for WooCommerce" is installed correctly.', 'ai-content-generator-for-woocommerce' ), ) ); } if ( ! class_exists( 'Wt_Import_Export_For_Woo_Basic_Csvreader' ) ) { require_once $csv_reader_path; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable } // ── Parse CSV ───────────────────────────────────────────────────────── $parse_result = self::parse_csv( $tmp_path ); if ( is_wp_error( $parse_result ) ) { wp_send_json_error( array( 'message' => $parse_result->get_error_message() ) ); } // ── Run import ──────────────────────────────────────────────────────── $import_response = self::run_import( $parse_result ); // ── Build chatbot reply ─────────────────────────────────────────────── $result = self::collect_results( $import_response ); $bot_reply = self::build_bot_reply( $file_name, $result ); // Persist to chat history so next messages have context. $user_id = get_current_user_id(); if ( $user_id ) { AI_Content_Generator_Chatbot_DB::save_message( $user_id, sprintf( '[CSV Import: %s]', $file_name ), $bot_reply ); } // Build compact context string for the next message request. $compact_context = self::build_compact_context( $result['all_items'], $file_name ); wp_send_json_success( array( 'response' => $bot_reply, 'import_context' => $compact_context, ) ); } // ------------------------------------------------------------------------- // CSV Parsing // ------------------------------------------------------------------------- /** * Opens, reads, and normalizes a CSV file into the row format expected * by the import-export plugin's filter callback. * * Handles both WooCommerce native export headers ("Name", "Regular price") * and WebToffee export headers ("post_title", "regular_price") automatically. * * @param string $tmp_path Absolute path to the uploaded temp file. * @return array|WP_Error Normalized import_data rows on success, WP_Error on failure. */ private static function parse_csv( $tmp_path ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen $handle = @fopen( $tmp_path, 'r' ); if ( ! $handle ) { return new WP_Error( 'csv_open_failed', __( 'Could not open the uploaded CSV file.', 'ai-content-generator-for-woocommerce' ) ); } // Read header row — strip BOM and invisible chars (same as the import plugin). $raw_headers = fgetcsv( $handle ); if ( empty( $raw_headers ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose fclose( $handle ); return new WP_Error( 'csv_empty', __( 'CSV file is empty or has no header row.', 'ai-content-generator-for-woocommerce' ) ); } $headers = array_map( array( __CLASS__, 'normalize_header' ), $raw_headers ); $col_count = count( $headers ); $import_data = array(); while ( false !== ( $row = fgetcsv( $handle ) ) ) { // Skip blank rows. if ( 0 === count( array_filter( $row, function( $v ) { return '' !== trim( $v ); } ) ) ) { continue; } // Pad / truncate to match header count. $row_count = count( $row ); if ( $row_count < $col_count ) { $row = array_merge( $row, array_fill( $row_count, $col_count - $row_count, '' ) ); } elseif ( $row_count > $col_count ) { $row = array_slice( $row, 0, $col_count ); } // Build mapping_fields — column name => value with value normalization. $mapping = array(); foreach ( $headers as $i => $col ) { $value = isset( $row[ $i ] ) ? trim( $row[ $i ] ) : ''; // Normalize WC-native special column values. $value = self::normalize_value( $col, $value ); // Pass attribute:, meta:, tax: prefixed columns through as-is. $mapping[ $col ] = $value; } $import_data[] = array( 'mapping_fields' => $mapping, 'meta_mapping_fields' => array(), ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose fclose( $handle ); if ( empty( $import_data ) ) { return new WP_Error( 'csv_no_data', __( 'No data rows found in the CSV. Ensure rows below the header are not blank.', 'ai-content-generator-for-woocommerce' ) ); } return $import_data; } /** * Normalizes a single CSV header to the internal column name used * by the import-export plugin. * * Detection order: * 1. Exact match in $wc_header_map (after BOM strip, lowercase, trim). * 2. Strip unit suffix "(kg)", "(cm)", "(lbs)", "(in)" and retry. * 3. Keep the original value (handles WebToffee export format, attribute:/meta:/tax: prefixes). * * @param string $raw Raw header string from CSV. * @return string Normalized column key. */ private static function normalize_header( $raw ) { // Strip BOM characters and invisible Unicode control chars. $clean = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\xFF]/', '', $raw ); $clean = trim( $clean ); // Lowercase for map lookup. $lower = strtolower( $clean ); if ( isset( self::$wc_header_map[ $lower ] ) ) { return self::$wc_header_map[ $lower ]; } // Strip parenthetical unit suffixes: "Weight (kg)" → "weight". $stripped = trim( preg_replace( '/\s*\([^)]*\)\s*$/', '', $lower ) ); if ( $stripped !== $lower && isset( self::$wc_header_map[ $stripped ] ) ) { return self::$wc_header_map[ $stripped ]; } // Return as-is — the import-export plugin already understands its own // export format (post_title, _regular_price, tax:product_cat, attribute:Color, etc.) return $clean; } /** * Normalizes column values for columns where WooCommerce native export * uses different representations than the import-export plugin expects. * * @param string $column Normalized column key. * @param string $value Raw cell value. * @return string Normalized value. */ private static function normalize_value( $column, $value ) { if ( '' === $value ) { return $value; } switch ( $column ) { // WC exports "Published" as 1 / 0 / -1; importer wants "publish" / "draft" / "private". case 'status': case 'post_status': if ( isset( self::$wc_status_values[ $value ] ) ) { return self::$wc_status_values[ $value ]; } break; // WC exports "In stock?" as 1 / 0. case 'stock_status': case '_stock_status': if ( isset( self::$wc_stock_status_values[ $value ] ) ) { return self::$wc_stock_status_values[ $value ]; } break; // WC exports booleans (featured, sold_individually, etc.) as 1 / 0. case 'featured': case 'sold_individually': case 'sold_individually_': case 'reviews_allowed': case 'backorders': case 'manage_stock': case '_manage_stock': case 'virtual': case '_virtual': case 'downloadable': case '_downloadable': if ( '1' === $value ) { return 'yes'; } if ( '0' === $value ) { return 'no'; } break; } return $value; } // ------------------------------------------------------------------------- // Import execution // ------------------------------------------------------------------------- /** * Fires the import-export plugin's product import filter with the parsed data. * * Uses minimal form_data defaults that mirror a standard quick import so no * merge/conflict step-wizard state is required. * * @param array $import_data Rows in mapping_fields/meta_mapping_fields format. * @return mixed Raw filter response from the import-export plugin. */ private static function run_import( array $import_data ) { $form_data = array( 'advanced_form_data' => array( 'wt_iew_found_action' => 'update', // update existing, create new. 'wt_iew_merge_with' => 'id', 'wt_iew_id_conflict' => 'skip', 'wt_iew_merge_empty_cells' => 0, 'wt_iew_skip_new' => 0, 'wt_iew_use_sku_upsell_crosssell' => 0, 'wt_iew_prod_use_chidren_sku' => 0, 'wt_iew_pro_stop_thumbnail_regen' => 0, 'wt_iew_delete_existing' => 0, ), ); /** * Fires the import-export plugin's product importer. * Wt_Import_Export_For_Woo_Product_Basic_Product::importer_do_import() is the callback. * * @param array $import_data Rows to import. * @param string 'product' Module base — selects the product importer callback. * @param string 'import' Step name. * @param array $form_data Import settings. * @param array [] Selected template data (none needed for quick import). * @param string 'quick' Import method identifier. * @param int 0 Batch offset (first and only batch). * @param bool true Is last batch flag. */ return apply_filters( // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound 'wt_iew_importer_do_import_basic', $import_data, 'product', 'import', $form_data, array(), 'quick', 0, true ); } // ------------------------------------------------------------------------- // Result processing // ------------------------------------------------------------------------- /** * Parses the import-export plugin's response into structured result arrays. * * @param mixed $response Raw filter response. * @return array { * @type int $total_success * @type int $total_failed * @type array $created_items [ ['id'=>int,'name'=>string], ... ] * @type array $updated_items [ ['id'=>int,'name'=>string], ... ] * @type array $all_items Combined created + updated. * } */ private static function collect_results( $response ) { $log_data = isset( $response['log_data'] ) ? (array) $response['log_data'] : array(); $total_success = isset( $response['total_success'] ) ? (int) $response['total_success'] : 0; $total_failed = isset( $response['total_failed'] ) ? (int) $response['total_failed'] : 0; $created = array(); $updated = array(); foreach ( $log_data as $entry ) { if ( empty( $entry['status'] ) || empty( $entry['post_id'] ) ) { continue; } $pid = (int) $entry['post_id']; $product = wc_get_product( $pid ); $name = $product ? $product->get_name() : __( 'Unknown Product', 'ai-content-generator-for-woocommerce' ); $item = array( 'id' => $pid, 'name' => $name ); // "imported" appears in the message for new products; updates say "updated". if ( false !== strpos( (string) $entry['message'], 'imported' ) ) { $created[] = $item; } else { $updated[] = $item; } } return array( 'total_success' => $total_success, 'total_failed' => $total_failed, 'created_items' => $created, 'updated_items' => $updated, 'all_items' => array_merge( $created, $updated ), ); } // ------------------------------------------------------------------------- // Response builders // ------------------------------------------------------------------------- /** * Builds the HTML chatbot reply shown in the bubble after import. * Lists each product with its ID and name so the AI can reference them immediately. * * @param string $file_name Sanitized CSV filename. * @param array $result From collect_results(). * @return string HTML string. */ private static function build_bot_reply( $file_name, array $result ) { $total_success = $result['total_success']; $total_failed = $result['total_failed']; $created = $result['created_items']; $updated = $result['updated_items']; if ( $total_success > 0 ) { $reply = '

✓ Imported ' . esc_html( $file_name ) . ' — '; $reply .= $total_success . ' product' . ( $total_success !== 1 ? 's' : '' ) . ' processed'; if ( $total_failed > 0 ) { $reply .= ', ' . $total_failed . ' skipped'; } $reply .= '.

'; // Compact clickable product list — one line per product with a View button. $all_items = array_merge( $created, $updated ); if ( ! empty( $all_items ) ) { $reply .= '
'; foreach ( $all_items as $item ) { $pid = (int) $item['id']; $name = esc_html( $item['name'] ); $edit_url = get_edit_post_link( $pid, 'raw' ); $view_url = get_permalink( $pid ); $is_new = in_array( $item, $created, true ); $badge = $is_new ? 'New' : 'Updated'; $reply .= '
'; $reply .= $badge . '' . $name . ''; if ( $edit_url ) { $reply .= 'Edit'; } if ( $view_url ) { $reply .= 'View'; } $reply .= '
'; } $reply .= '
'; } } else { $reply = '

Import of ' . esc_html( $file_name ) . ' finished — no products were imported.'; if ( $total_failed > 0 ) { $reply .= ' (' . $total_failed . ' row(s) failed/skipped)'; } $reply .= '.

'; } return $reply; } /** * Builds a compact, token-efficient context string sent alongside the next * chat message so the AI knows which products were just imported. * * Format example: * [Imported from products.csv: ID:42 "Blue T-Shirt", ID:43 "Red Hoodie"] * * @param array $all_items Combined created + updated items. * @param string $file_name CSV filename for reference. * @return string */ public static function build_compact_context( array $all_items, $file_name = '' ) { if ( empty( $all_items ) ) { return ''; } $parts = array(); foreach ( $all_items as $item ) { $parts[] = 'ID:' . (int) $item['id'] . ' "' . esc_attr( $item['name'] ) . '"'; } $prefix = $file_name ? 'Imported from ' . $file_name . ': ' : 'Recently imported products: '; return '[' . $prefix . implode( ', ', $parts ) . ']'; } }