Edit BOGO Coupon.\n"; return $p; } /** * @param string $msg Lowercased message. * @return bool */ private static function message_has_manage_keywords( $msg ) { $kws = array( 'trash', 'delete', 'toggle', 'restore', 'duplicate', 'activate', 'deactivate', 'disable', 'enable', 'list', 'show' ); foreach ( $kws as $k ) { if ( strpos( $msg, $k ) !== false ) return true; } return false; } /** * @param string $msg Lowercased message. * @return bool */ private static function message_has_create_keywords( $msg ) { $kws = array( 'create', 'make', 'add', 'new', 'set up', 'setup', 'build', 'generate' ); foreach ( $kws as $k ) { if ( strpos( $msg, $k ) !== false ) return true; } return false; } // ------------------------------------------------------------------------- // Action dispatcher // ------------------------------------------------------------------------- /** * Dispatches a BOGO chatbot action JSON block to the correct handler. * * Called by the chatbot API's execute_raw_action() when the _action key * matches one of the BOGO action names. * * @param string $action Sanitized action name (without "bogo" prefix stripped). * @param array $json Decoded JSON block from the AI response. * @return mixed Array result, bool, or WP_Error. */ public static function dispatch( $action, array $json ) { if ( ! self::is_active() ) { return new WP_Error( 'bogo_inactive', __( 'The BOGO plugin is not active. Please install and activate "WebToffee WooCommerce BOGO" to use BOGO actions.', 'ai-content-generator-for-woocommerce' ) ); } switch ( $action ) { case 'create_bogo': return self::execute_create( $json ); case 'list_bogos': return self::execute_list( $json ); case 'trash_bogo': return self::execute_trash( $json ); case 'toggle_bogo': return self::execute_toggle( $json ); case 'restore_bogo': return self::execute_restore( $json ); case 'delete_bogo_permanently': return self::execute_delete_permanently( $json ); case 'duplicate_bogo': return self::execute_duplicate( $json ); default: return null; // Not a BOGO action — caller handles it. } } /** * Returns true if the given action name is handled by this module. * * @param string $action * @return bool */ public static function handles( $action ) { return in_array( $action, array( 'create_bogo', 'list_bogos', 'trash_bogo', 'toggle_bogo', 'restore_bogo', 'delete_bogo_permanently', 'duplicate_bogo', ), true ); } // ------------------------------------------------------------------------- // Action implementations // ------------------------------------------------------------------------- /** * Creates a new BOGO coupon. * * @param array $input Decoded JSON params from the AI. * @return array|WP_Error */ private static function execute_create( array $input ) { try { $coupon_name = sanitize_text_field( $input['coupon_name'] ?? '' ); $campaign_type = sanitize_text_field( $input['campaign_type'] ?? 'default_1' ); $status = isset( $input['status'] ) && 'publish' === $input['status'] ? 'publish' : 'draft'; $description = isset( $input['description'] ) ? sanitize_textarea_field( $input['description'] ) : ''; $conversion = isset( $input['conversion'] ) ? sanitize_text_field( $input['conversion'] ) : 'auto'; $input['buy_product_ids'] = isset( $input['buy_product_ids'] ) ? array_filter( array_map( 'absint', (array) $input['buy_product_ids'] ) ) : array(); $input['get_product_ids'] = isset( $input['get_product_ids'] ) ? array_filter( array_map( 'absint', (array) $input['get_product_ids'] ) ) : array(); // If any product names are provided, resolve both buy and get product IDs before creating the BOGO coupon. if ( empty( $input['buy_product_ids'] ) && ! empty( $input['buy_product_names'] ) ) { $resolved = self::resolve_product_ids_from_names( $input['buy_product_names'], 'buy_product_names' ); if ( is_wp_error( $resolved ) ) { return $resolved; } $input['buy_product_ids'] = $resolved; } if ( empty( $input['get_product_ids'] ) && ! empty( $input['get_product_names'] ) ) { $resolved = self::resolve_product_ids_from_names( $input['get_product_names'], 'get_product_names' ); if ( is_wp_error( $resolved ) ) { return $resolved; } $input['get_product_ids'] = $resolved; } // Derive a URL-safe coupon code from the name. $slug = strtolower( preg_replace( '/[^a-z0-9\-]+/i', '-', $coupon_name ) ); $slug = trim( preg_replace( '/-+/', '-', $slug ), '-' ); $coupon_code = $slug ?: 'bogo-' . time(); $c_title = $coupon_code; $counter = 1; if ( ! function_exists( 'post_exists' ) ) { require_once ABSPATH . 'wp-admin/includes/post.php'; } while ( post_exists( $c_title ) ) { $c_title = $coupon_code . $counter; ++$counter; } $coupon_id = wp_insert_post( array( 'post_title' => $c_title, 'post_type' => 'shop_coupon', 'post_status' => $status, 'post_excerpt' => $description, ) ); if ( is_wp_error( $coupon_id ) ) { return new WP_Error( 'insert_failed', $coupon_id->get_error_message() ); } $bogo_type = self::bogo_type(); $coupon = new WC_Coupon( $coupon_id ); $coupon->set_code( $c_title ); $coupon->set_discount_type( $bogo_type ); if ( is_null( $coupon->get_date_created() ) ) { $coupon->set_date_created( current_time( 'mysql' ) ); } if ( ! empty( $input['expiry_date'] ) ) { $coupon->set_date_expires( sanitize_text_field( $input['expiry_date'] ) ); } $coupon->save(); update_post_meta( $coupon_id, 'discount_type', $bogo_type ); update_post_meta( $coupon_id, 'wbte_sc_bogo_coupon_name', $coupon_name ); if ( ! empty( $input['start_date'] ) ) { update_post_meta( $coupon_id, 'wc_sc_start_date', sanitize_text_field( $input['start_date'] ) ); } // Auto / manual conversion. if ( 'auto' === $conversion ) { if ( class_exists( 'Wt_Smart_Coupon_Auto_Coupon_Admin' ) && method_exists( 'Wt_Smart_Coupon_Auto_Coupon_Admin', 'process_auto_coupon_meta' ) ) { Wt_Smart_Coupon_Auto_Coupon_Admin::process_auto_coupon_meta( $coupon_id, array( '_wt_make_auto_coupon' => 'yes' ) ); } else { update_post_meta( $coupon_id, '_wt_make_auto_coupon', 'yes' ); } update_post_meta( $coupon_id, 'wbte_sc_bogo_code_condition', 'wbte_sc_bogo_code_auto' ); } else { update_post_meta( $coupon_id, 'wbte_sc_bogo_code_condition', 'wbte_sc_bogo_code_manual' ); } // Campaign type / template settings. if ( 'custom' === $campaign_type ) { self::apply_custom_campaign( $coupon_id, $input ); } else { self::apply_predefined_campaign( $coupon_id, $campaign_type ); } // ALWAYS save product IDs if the AI provided them, regardless of campaign type. if ( ! empty( $input['buy_product_ids'] ) ) { update_post_meta( $coupon_id, 'wbte_sc_bogo_product_ids', implode( ',', array_map( 'absint', $input['buy_product_ids'] ) ) ); } if ( ! empty( $input['get_product_ids'] ) ) { update_post_meta( $coupon_id, 'wbte_sc_bogo_free_product_ids', implode( ',', array_map( 'absint', $input['get_product_ids'] ) ) ); update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets', 'specific_product' ); } // Fill in any missing defaults from the BOGO plugin's meta schema. if ( property_exists( 'Wbte_Smart_Coupon_Bogo_Common', 'meta_arr' ) ) { $skip = array( 'wbte_sc_bogo_type', 'wbte_sc_bogo_coupon_name', 'wbte_sc_bogo_campaign_description' ); foreach ( Wbte_Smart_Coupon_Bogo_Common::$meta_arr as $meta_key => $meta_info ) { if ( in_array( $meta_key, $skip, true ) || metadata_exists( 'post', $coupon_id, $meta_key ) ) { continue; } update_post_meta( $coupon_id, $meta_key, $meta_info['default'] ?? '' ); } } do_action( 'wbte_sc_bogo_new_coupon_created', $coupon_id ); // phpcs:ignore self::clear_caches(); $plugin_page = defined( 'WT_SC_PLUGIN_NAME' ) ? WT_SC_PLUGIN_NAME : 'wt_smart_coupon'; return array( 'success' => true, 'coupon_id' => $coupon_id, 'coupon_code' => $coupon->get_code(), 'edit_url' => admin_url( 'admin.php?page=' . $plugin_page . '_bogo&wbte_bogo_id=' . $coupon_id ), 'message' => __( 'BOGO Coupon created successfully.', 'ai-content-generator-for-woocommerce' ), ); } catch ( \Throwable $e ) { return new WP_Error( 'bogo_create_crash', $e->getMessage() ); } } /** * Resolves product IDs from product name strings using the chatbot product search helper. * * @param string|array $names * @param string $field_name * @return array|WP_Error */ private static function resolve_product_ids_from_names( $names, $field_name ) { $names = is_array( $names ) ? $names : array( $names ); $ids = array(); foreach ( $names as $name ) { $name = trim( sanitize_text_field( $name ) ); if ( '' === $name ) { continue; } $results = AI_Content_Generator_For_WooCommerce_Helper::search_product_id( array( 'search_term' => $name, 'limit' => 5, ) ); if ( empty( $results ) ) { return new WP_Error( 'product_not_found', sprintf( /* translators: %s: Product name provided by the user. */ __( 'Could not resolve product name "%s" to a product ID. Use search_product with a more precise name.', 'ai-content-generator-for-woocommerce' ), $name ) ); } $normalized = strtolower( $name ); $best_id = $results[0]['id']; foreach ( $results as $product ) { if ( strtolower( $product['name'] ) === $normalized || strtolower( $product['sku'] ) === $normalized ) { $best_id = $product['id']; break; } } $ids[] = $best_id; } return $ids; } /** * Applies custom campaign meta to a newly created BOGO coupon post. * * @param int $coupon_id * @param array $input AI JSON params. */ private static function apply_custom_campaign( $coupon_id, array $input ) { update_post_meta( $coupon_id, 'wbte_sc_bogo_type', 'wbte_sc_bogo_bxgx' ); update_post_meta( $coupon_id, 'wbte_sc_bogo_triggers_when', 'wbte_sc_bogo_triggers_qty' ); update_post_meta( $coupon_id, 'wbte_sc_bogo_apply_offer', 'wbte_sc_bogo_apply_repeatedly' ); $buy_qty = isset( $input['buy_quantity'] ) ? absint( $input['buy_quantity'] ) : 1; update_post_meta( $coupon_id, '_wbte_sc_bogo_min_qty', $buy_qty ); if ( ! empty( $input['buy_product_ids'] ) ) { update_post_meta( $coupon_id, 'wbte_sc_bogo_product_ids', implode( ',', array_map( 'absint', $input['buy_product_ids'] ) ) ); } $get_qty = isset( $input['get_quantity'] ) ? absint( $input['get_quantity'] ) : 1; update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_qty', $get_qty ); if ( ! empty( $input['get_product_ids'] ) ) { update_post_meta( $coupon_id, 'wbte_sc_bogo_free_product_ids', implode( ',', array_map( 'absint', $input['get_product_ids'] ) ) ); update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets', 'specific_product' ); } $discount_type = isset( $input['discount_type'] ) ? $input['discount_type'] : 'free'; $discount_value = isset( $input['discount_value'] ) ? floatval( $input['discount_value'] ) : 0; if ( 'percent' === $discount_type ) { update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_with', 'wbte_sc_bogo_customer_gets_with_discount' ); update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_discount_type', 'wbte_sc_bogo_customer_gets_with_perc_discount' ); update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_discount_perc', $discount_value ); } elseif ( 'fixed' === $discount_type ) { update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_with', 'wbte_sc_bogo_customer_gets_with_discount' ); update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_discount_type', 'wbte_sc_bogo_customer_gets_with_price_discount' ); update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_discount_price', $discount_value ); } else { // Default: free. update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_with', 'wbte_sc_bogo_customer_gets_with_discount' ); update_post_meta( $coupon_id, 'wbte_sc_bogo_customer_gets_discount_type', 'wbte_sc_bogo_customer_gets_free' ); } } /** * Applies a predefined campaign template's meta to a BOGO coupon post. * * Templates: * default_1 — Buy 1, Get 1 at 50% off (applied repeatedly). * default_2 — Buy 2, Get 1 free. * default_3 — Spend $100, Get 1 free. * * @param int $coupon_id * @param string $campaign_type */ private static function apply_predefined_campaign( $coupon_id, $campaign_type ) { $templates = array( 'default_1' => array( 'wbte_sc_bogo_triggers_when' => 'wbte_sc_bogo_triggers_qty', '_wbte_sc_bogo_min_qty' => 1, 'wbte_sc_bogo_customer_gets_discount_type' => 'wbte_sc_bogo_customer_gets_with_perc_discount', 'wbte_sc_bogo_customer_gets_discount_perc' => 50, 'wbte_sc_bogo_apply_offer' => 'wbte_sc_bogo_apply_repeatedly', ), 'default_2' => array( 'wbte_sc_bogo_triggers_when' => 'wbte_sc_bogo_triggers_qty', '_wbte_sc_bogo_min_qty' => 2, ), 'default_3' => array( 'wbte_sc_bogo_triggers_when' => 'wbte_sc_bogo_triggers_subtotal', '_wbte_sc_bogo_min_amount' => 100, ), ); $settings = isset( $templates[ $campaign_type ] ) ? $templates[ $campaign_type ] : $templates['default_1']; foreach ( $settings as $key => $value ) { update_post_meta( $coupon_id, $key, $value ); } } /** * Lists BOGO coupons. * * @param array $input ['limit' => int] * @return array */ private static function execute_list( array $input ) { $limit = isset( $input['limit'] ) ? absint( $input['limit'] ) : 20; $limit = max( 1, min( 100, $limit ) ); $query = new WP_Query( array( 'post_type' => 'shop_coupon', 'post_status' => array( 'publish', 'draft' ), 'posts_per_page' => $limit, 'fields' => 'ids', 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query array( 'key' => 'discount_type', 'value' => self::bogo_type(), ), ), ) ); $result = array(); foreach ( $query->posts as $id ) { $status = get_post_status( $id ); $result[] = array( 'id' => $id, 'code' => get_the_title( $id ), 'name' => get_post_meta( $id, 'wbte_sc_bogo_coupon_name', true ), 'status' => $status, ); } return $result; } /** * Moves a BOGO coupon to the trash. * * @param array $input ['coupon_id' => int] * @return true|WP_Error */ private static function execute_trash( array $input ) { $coupon_id = absint( $input['coupon_id'] ?? 0 ); $check = self::validate_bogo_id( $coupon_id ); if ( is_wp_error( $check ) ) { return $check; } $result = wp_trash_post( $coupon_id ); if ( $result ) { self::clear_caches(); return array( 'success' => true, 'message' => __( 'BOGO coupon moved to trash.', 'ai-content-generator-for-woocommerce' ), ); } return new WP_Error( 'trash_failed', __( 'Failed to trash the BOGO coupon.', 'ai-content-generator-for-woocommerce' ) ); } /** * Toggles a BOGO coupon's active/draft status. * * @param array $input ['coupon_id' => int, 'is_active' => bool] * @return array|WP_Error */ private static function execute_toggle( array $input ) { $coupon_id = absint( $input['coupon_id'] ?? 0 ); $is_active = ! empty( $input['is_active'] ); $check = self::validate_bogo_id( $coupon_id ); if ( is_wp_error( $check ) ) { return $check; } $new_status = $is_active ? 'publish' : 'draft'; $result = wp_update_post( array( 'ID' => $coupon_id, 'post_status' => $new_status ) ); if ( is_wp_error( $result ) || 0 === $result ) { return new WP_Error( 'toggle_failed', __( 'Failed to update BOGO coupon status.', 'ai-content-generator-for-woocommerce' ) ); } $coupon = new WC_Coupon( $coupon_id ); $coupon->save(); self::clear_caches(); return array( 'success' => true, 'message' => $is_active ? __( 'BOGO coupon activated.', 'ai-content-generator-for-woocommerce' ) : __( 'BOGO coupon deactivated (set to draft).', 'ai-content-generator-for-woocommerce' ), ); } /** * Restores a trashed BOGO coupon to publish. * * @param array $input ['coupon_id' => int] * @return array|WP_Error */ private static function execute_restore( array $input ) { $coupon_id = absint( $input['coupon_id'] ?? 0 ); $check = self::validate_bogo_id( $coupon_id ); if ( is_wp_error( $check ) ) { return $check; } $result = wp_update_post( array( 'ID' => $coupon_id, 'post_status' => 'publish' ) ); if ( $result ) { self::clear_caches(); return array( 'success' => true, 'message' => __( 'BOGO coupon restored to active.', 'ai-content-generator-for-woocommerce' ), ); } return new WP_Error( 'restore_failed', __( 'Failed to restore BOGO coupon.', 'ai-content-generator-for-woocommerce' ) ); } /** * Permanently deletes a BOGO coupon. * * @param array $input ['coupon_id' => int] * @return array|WP_Error */ private static function execute_delete_permanently( array $input ) { $coupon_id = absint( $input['coupon_id'] ?? 0 ); $check = self::validate_bogo_id( $coupon_id ); if ( is_wp_error( $check ) ) { return $check; } $result = wp_delete_post( $coupon_id, true ); if ( $result ) { self::clear_caches(); return array( 'success' => true, 'message' => __( 'BOGO coupon permanently deleted.', 'ai-content-generator-for-woocommerce' ), ); } return new WP_Error( 'delete_failed', __( 'Failed to permanently delete BOGO coupon.', 'ai-content-generator-for-woocommerce' ) ); } /** * Duplicates a BOGO coupon via the Smart Coupon plugin's clone engine. * * @param array $input ['coupon_id' => int] * @return array|WP_Error */ private static function execute_duplicate( array $input ) { $old_id = absint( $input['coupon_id'] ?? 0 ); $check = self::validate_bogo_id( $old_id ); if ( is_wp_error( $check ) ) { return $check; } if ( ! class_exists( 'WT_Duplicate_Shop_Coupon' ) || ! method_exists( 'WT_Duplicate_Shop_Coupon', 'clone_coupon' ) ) { return new WP_Error( 'missing_dependency', __( 'Smart Coupon duplication module is missing or inactive.', 'ai-content-generator-for-woocommerce' ) ); } try { if ( ! function_exists( 'post_exists' ) ) { require_once ABSPATH . 'wp-admin/includes/post.php'; } $old_code = get_the_title( $old_id ); $c_title = $old_code; $counter = 1; while ( post_exists( $c_title ) ) { $c_title = $old_code . $counter; ++$counter; } $new_id = WT_Duplicate_Shop_Coupon::clone_coupon( $old_id, $c_title ); if ( ! $new_id ) { return new WP_Error( 'duplicate_failed', __( 'Duplication returned false.', 'ai-content-generator-for-woocommerce' ) ); } delete_post_meta( $new_id, 'usage_count' ); delete_post_meta( $new_id, '_used_by' ); wp_update_post( array( 'ID' => $new_id, 'post_status' => 'draft' ) ); do_action( 'wbte_sc_bogo_new_coupon_created', $new_id ); // phpcs:ignore self::clear_caches(); return array( 'success' => true, 'new_id' => $new_id, 'new_code' => $c_title, 'message' => __( 'BOGO coupon duplicated as draft.', 'ai-content-generator-for-woocommerce' ), ); } catch ( \Throwable $e ) { return new WP_Error( 'duplicate_crash', $e->getMessage() ); } } // ------------------------------------------------------------------------- // Helpers // ------------------------------------------------------------------------- /** * Validates that a given post ID is an existing BOGO shop_coupon. * * @param int $coupon_id * @return true|WP_Error */ private static function validate_bogo_id( $coupon_id ) { if ( ! $coupon_id || 'shop_coupon' !== get_post_type( $coupon_id ) ) { return new WP_Error( 'invalid_id', __( 'Invalid coupon ID provided.', 'ai-content-generator-for-woocommerce' ) ); } if ( get_post_meta( $coupon_id, 'discount_type', true ) !== self::bogo_type() ) { return new WP_Error( 'not_bogo', __( 'The provided ID is not a BOGO coupon.', 'ai-content-generator-for-woocommerce' ) ); } return true; } /** * Clears all BOGO-related transient caches. * Mirrors Wbte_Smart_Coupon_Bogo_Admin::delete_bogo_count_cache(). * * @return void */ private static function clear_caches() { delete_transient( 'wbte_sc_bogo_count_all' ); delete_transient( 'wbte_sc_bogo_count_trash' ); delete_transient( 'wbte_sc_bogo_count_active' ); delete_transient( 'wbte_sc_bogo_coupon_ids' ); } }