get_settings(); $notify_on_atc = !isset($settings['notify_on_add_to_cart']) || $settings['notify_on_add_to_cart'] === 'yes'; if ($notify_on_atc) { if ( ! defined( 'AIEO_RUNTIME_OWNS_AJAX' ) ) { add_action('woocommerce_add_to_cart', array($this, 'notify_on_add_to_cart'), 20, 6); } add_action('woocommerce_after_add_to_cart_form', array($this, 'render_product_page_notice')); } } if ( ! defined( 'AIEO_RUNTIME_OWNS_AJAX' ) ) { add_action('woocommerce_cart_calculate_fees', array($this, 'apply_cod_fee_to_cart'), 11, 1); add_filter('woocommerce_available_payment_gateways', array($this, 'force_cod_visible_when_aieo_enabled'), 999); } add_action('woocommerce_admin_order_data_after_billing_address', array($this, 'apply_cod_fee_admin'), 10, 1); add_action('wp_footer', array($this, 'output_cod_refresh_js')); add_action('woocommerce_blocks_loaded', array($this, 'maybe_register_cod_for_blocks')); } public function render_subtab() { $paged = isset($_GET['paged']) ? max(1, absint($_GET['paged'])) : 1; $this->render_unified_rules_section(); rooster_admin_band_open(array('cols' => 2, 'min' => 35)); $this->render_template('free-shipping.php', array( 'settings' => $this->get_settings(), 'exclusions' => $this->fetch_exclusions(100, $paged), 'exclusion_count' => $this->count_exclusions(), 'per_page' => 100, 'current_page' => $paged, )); $this->render_cod_card(); do_action('aieo_dmm_free_shipping_after_cod_card'); rooster_admin_band_close(); } private function render_cod_card() { $settings = $this->get_settings(true); $hint = self::i18n_hints(); $aieo_fs_cur = function_exists('get_woocommerce_currency_symbol') ? html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES | ENT_HTML5, 'UTF-8') : '€'; $aieo_fs_form = 'aieo-card-free-shipping-cash-on-delivery-form'; $aieo_fs_id = static function ($name) { return 'aieo-fs-' . str_replace('_', '-', $name); }; $aieo_fs_row = static function ($name, $label, $control, $help = '') use ($aieo_fs_id) { $field = array('id' => $aieo_fs_id($name), 'label' => $label, 'control' => $control); if ('' !== $help) { $field['help'] = $help; } return \Rooster\Admin\Ui::field_row($field); }; $aieo_fs_switch = static function ($name, $on, $text) use ($aieo_fs_id) { return \Rooster\Admin\Ui::toggle($name, $on, array('id' => $aieo_fs_id($name), 'hidden' => false, 'label' => $text)); }; list($aieo_fs_open, $aieo_fs_close) = AIEO_DMM_UI::card(array( 'anchor' => 'free-shipping-cash-on-delivery', 'icon' => 'banknote', 'title' => __('Cash on Delivery', 'ai-eshop-optimizer'), 'description' => __('Adds a fee to the order total when the customer picks the Cash on Delivery payment method at checkout. The fee is recalculated whenever the cart total or payment method changes (mini-cart qty changes included).', 'ai-eshop-optimizer'), 'footer' => \Rooster\Admin\States::save_button($aieo_fs_form, array('label' => __('Save COD settings', 'ai-eshop-optimizer'))), 'col' => 2, )); echo $aieo_fs_open; $aieo_fs_fields = $aieo_fs_row('cod_enabled', __('Enable COD fee', 'ai-eshop-optimizer'), $aieo_fs_switch('cod_enabled', $settings['cod_enabled'] === 'yes', __('Add a fee when the customer pays with Cash on Delivery', 'ai-eshop-optimizer'))); $aieo_fs_fields .= $aieo_fs_row('cod_fee', __('Fee amount', 'ai-eshop-optimizer'), \Rooster\Admin\Ui::input('cod_fee', (string) $settings['cod_fee'], array('id' => $aieo_fs_id('cod_fee'), 'type' => 'number', 'step' => 'any', 'min' => '0', 'short' => true, 'unit' => $aieo_fs_cur)), __('In your shop currency. A typical cash-on-delivery fee is €1.50–€2.50.', 'ai-eshop-optimizer')); $aieo_fs_fields .= $aieo_fs_row('cod_label', __('Fee label', 'ai-eshop-optimizer'), \Rooster\Admin\Ui::input('cod_label', (string) $settings['cod_label'], array('id' => $aieo_fs_id('cod_label'), 'medium' => true, 'maxlength' => '100', 'placeholder' => $hint['cod_label'])), __('Shown to the customer on cart/checkout/order — also used to detect duplicate fees so we never add it twice.', 'ai-eshop-optimizer')); $aieo_fs_fields .= $aieo_fs_row('cod_taxable', __('Taxable', 'ai-eshop-optimizer'), $aieo_fs_switch('cod_taxable', $settings['cod_taxable'] === 'yes', __('Apply tax to the COD fee', 'ai-eshop-optimizer'))); $aieo_fs_fields .= $aieo_fs_row('cod_gateway_slug', __('Payment gateway slug', 'ai-eshop-optimizer'), \Rooster\Admin\Ui::input('cod_gateway_slug', (string) $settings['cod_gateway_slug'], array('id' => $aieo_fs_id('cod_gateway_slug'), 'short' => true, 'maxlength' => '50')), __('WooCommerce payment-method ID that triggers this fee. Default "cod" matches WooCommerce\'s built-in Cash on Delivery gateway.', 'ai-eshop-optimizer')); ob_start(); do_action('aieo_dmm_cod_card_after_fee_label', $settings); $aieo_fs_fields .= trim((string) ob_get_clean()); $aieo_fs_html = '
' . $aieo_fs_fields . '
'; echo AIEO_DMM_UI::card_form('aieo_dmm_free_shipping_save', 'free_shipping_cod', $aieo_fs_form, $aieo_fs_html); echo $aieo_fs_close; } public function render_display_settings_card($description = '') { $settings = $this->get_settings(true); $hint = self::i18n_hints(); $id_of = static function ($name) { return 'aieo-fs-' . str_replace('_', '-', $name); }; $row = static function ($name, $label, $control, $help = '') use ($id_of) { $field = array('id' => $id_of($name), 'label' => $label, 'control' => $control); if ('' !== $help) { $field['help'] = $help; } return \Rooster\Admin\Ui::field_row($field); }; $on = static function ($name, $default = 'no') use ($settings) { return (isset($settings[$name]) ? $settings[$name] : $default) === 'yes'; }; $text = static function ($name) use ($settings, $hint, $id_of) { return \Rooster\Admin\Ui::input($name, (string) $settings[$name], array('id' => $id_of($name), 'placeholder' => (string) $hint[$name])); }; $px = static function ($name, $min, $max) use ($settings, $id_of) { return \Rooster\Admin\Ui::input($name, (string) (int) $settings[$name], array('id' => $id_of($name), 'type' => 'number', 'xs' => true, 'unit' => 'px', 'min' => $min, 'max' => $max)); }; $colour = static function ($name, $fallback) use ($settings, $id_of) { return \Rooster\Admin\Fields::color($name, (string) $settings[$name], array('id' => $id_of($name), 'default' => $fallback)); }; $card = static function ($anchor, $icon, $title, $col, $fields, $extra = array()) { $form_id = 'aieo-card-' . $anchor . '-form'; list($open, $close) = AIEO_DMM_UI::card(array( 'anchor' => $anchor, 'icon' => $icon, 'title' => $title, 'col' => $col, 'footer' => class_exists('\Rooster\Admin\States') ? \Rooster\Admin\States::save_button($form_id) : '', ) + $extra); echo $open; echo AIEO_DMM_UI::card_form('aieo_dmm_free_shipping_save', 'free_shipping_display', $form_id, '
' . $fields . '
'); echo $close; }; rooster_admin_band_open(array('cols' => 2)); $surfaces = '
'; foreach (array( 'display_cart' => __('Cart', 'ai-eshop-optimizer'), 'display_checkout' => __('Checkout', 'ai-eshop-optimizer'), 'display_mini_cart' => __('Mini-cart', 'ai-eshop-optimizer'), 'display_product' => __('Product page', 'ai-eshop-optimizer'), 'display_floating' => __('Floating bar', 'ai-eshop-optimizer'), ) as $name => $label) { $surfaces .= ''; } $surfaces .= '
'; $fields = $row('msg_initial', __('Message (initial)', 'ai-eshop-optimizer'), $text('msg_initial')); $fields .= $row('msg_progress', __('Message (progress)', 'ai-eshop-optimizer'), $text('msg_progress')); $fields .= $row('msg_success', __('Message (success)', 'ai-eshop-optimizer'), $text('msg_success')); $fields .= $row('msg_rule_product', __('Message (product with free shipping)', 'ai-eshop-optimizer'), $text('msg_rule_product'), __('Shown on the product page when a free-shipping rule ships the order free with this product.', 'ai-eshop-optimizer')); $fields .= \Rooster\Admin\Ui::field_row(array('id' => $id_of('display_on'), 'label' => __('Display on', 'ai-eshop-optimizer'), 'group' => true, 'control' => $surfaces)); $card( 'free-shipping-display-settings', 'truck', __('Free-shipping progress bar', 'ai-eshop-optimizer'), 1, $fields, '' !== (string) $description ? array('description' => (string) $description) : array() ); $notice_type = isset($settings['notify_type']) && 'error' === $settings['notify_type'] ? 'error' : 'notice'; $fields = $row('notify_on_add_to_cart', __('Signal at add-to-cart', 'ai-eshop-optimizer'), \Rooster\Admin\Ui::toggle('notify_on_add_to_cart', $on('notify_on_add_to_cart', 'yes'), array('id' => $id_of('notify_on_add_to_cart'), 'hidden' => false, 'label' => __('Show a WooCommerce notice when an excluded product is added to cart, and show an inline banner on its single-product page.', 'ai-eshop-optimizer')))); $fields .= $row('notify_message', __('Notice text', 'ai-eshop-optimizer'), \Rooster\Admin\Ui::textarea('notify_message', isset($settings['notify_message']) ? (string) $settings['notify_message'] : '', array('id' => $id_of('notify_message'), 'rows' => 2, 'placeholder' => (string) $hint['notify_message'])), __('Shown both as a WooCommerce notice on add-to-cart AND as an inline banner under the add-to-cart button on each excluded product\'s single-product page. Leave blank to suppress.', 'ai-eshop-optimizer')); $fields .= \Rooster\Admin\Ui::field_row(array( 'id' => $id_of('notify_type'), 'label' => __('Notice type', 'ai-eshop-optimizer'), 'group' => true, 'control' => \Rooster\Admin\Fields::segmented('notify_type', array('notice' => __('Info (grey)', 'ai-eshop-optimizer'), 'error' => __('Warning (red)', 'ai-eshop-optimizer')), $notice_type, array('id' => $id_of('notify_type') . '-switch', 'labelledby' => $id_of('notify_type') . '-label')), )); $card( 'free-shipping-display-early-signal-notice', 'bell', __('Early-signal notice', 'ai-eshop-optimizer'), 1, $fields, array('description' => __('Tell customers immediately (not only at checkout) when a product they touch will disqualify their order from free shipping.', 'ai-eshop-optimizer')) ); $fields = $row('bar_height', __('Bar height', 'ai-eshop-optimizer'), $px('bar_height', 1, 60)); $fields .= $row('bar_border_radius', __('Bar border radius', 'ai-eshop-optimizer'), $px('bar_border_radius', 0, 40)); $fields .= $row('bar_bg_color', __('Bar background', 'ai-eshop-optimizer'), $colour('bar_bg_color', '#e0e0e0')); $fields .= $row('bar_progress_color', __('Bar progress color', 'ai-eshop-optimizer'), $colour('bar_progress_color', '#4caf50')); $fields .= $row('text_color', __('Text color', 'ai-eshop-optimizer'), $colour('text_color', '#333333')); $fields .= $row('success_color', __('Success color', 'ai-eshop-optimizer'), $colour('success_color', '#2e7d32')); $fields .= $row('amount_color', __('Amount color', 'ai-eshop-optimizer'), $colour('amount_color', '#bf4300')); $fields .= $row('font_size', __('Font size', 'ai-eshop-optimizer'), $px('font_size', 8, 40)); $card( 'free-shipping-display-appearance', 'palette', __('Appearance', 'ai-eshop-optimizer'), 2, $fields, array('description' => __('Styling for the progress bar and the threshold card. Applied via CSS variables so the same values drive cart / checkout / mini-cart / side-cart / product-page / floating surfaces.', 'ai-eshop-optimizer')) ); rooster_admin_band_close(); } public function render_unified_rules_section() { global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_offers'; if (!class_exists('AIEO_DMM_Schema_Gate', false)) { require_once dirname(__DIR__) . '/services/class-aieo-dmm-schema-gate.php'; } $rules = array(); if (aieo_dmm_table_exists($tbl) && AIEO_DMM_Schema_Gate::ready(AIEO_DMM_Schema_Gate::OFFERS, 'free_shipping_screen')) { $rules = $wpdb->get_results("SELECT * FROM {$tbl} WHERE type='free_shipping' ORDER BY enabled DESC, id DESC", ARRAY_A); if (AIEO_DMM_Schema_Gate::failed('free_shipping_screen') || !is_array($rules)) { $rules = array(); } } $rules = array_values(array_filter($rules, static function ($rule) { return 'archived' !== (string) ($rule['state'] ?? ''); })); require_once dirname(__DIR__) . '/services/class-aieo-dmm-offer-forms.php'; if ( class_exists( 'AIEO_DMM_Offer_Store' ) && method_exists( 'AIEO_DMM_Offer_Store', 'notice_html' ) ) { echo AIEO_DMM_Offer_Store::notice_html(); } if ( class_exists( 'AIEO_DMM_Offers' ) ) { echo AIEO_DMM_Offers::outcome_notice(); } require_once dirname(__DIR__) . '/services/class-aieo-dmm-free-shipping-thresholds.php'; echo AIEO_DMM_Free_Shipping_Thresholds::notice_html(); if (!AIEO_DMM_Free_Shipping_Rules::reads_offers_now()) { AIEO_DMM_Free_Shipping_Rules::rebuild(); } $aieo_fs_save = AIEO_Kit::button(__('Save free-shipping rule', 'ai-eshop-optimizer'), array('variant' => 'primary', 'type' => 'submit', 'class' => 'aieo-dmm-fs-save-btn', 'attrs' => array('data-action' => 'aieo_dmm_free_shipping_save_rule', 'form' => 'aieo-dmm-fs-rule-form'))) . ' ' . AIEO_DMM_Offer_Forms::preview_button('aieo-dmm-fs-rule-form', 'aieo_dmm_free_shipping_save_rule') . ' ' . AIEO_Kit::button(__('Cancel edit', 'ai-eshop-optimizer'), array('class' => 'aieo-dmm-fs-cancel-btn', 'attrs' => array('hidden' => true))); list($aieo_fs_open, $aieo_fs_close) = AIEO_DMM_UI::card(array( 'anchor' => 'free-shipping-rules-unified', 'icon' => 'list-checks', 'title' => __('Unified free-shipping rules', 'ai-eshop-optimizer'), 'description' => __('Create a rule that makes shipping free when a cart contains the brands, categories or products you target.', 'ai-eshop-optimizer'), 'footer' => $aieo_fs_save, )); echo $aieo_fs_open; ?> type=\'free_shipping\'', 'wp_aieo_dmm_offers', 'cost = 0' ); echo \Rooster\Admin\Guidance::text('', 'guidance', array('html' => $aieo_fs_intro, 'question' => __('When do these rules apply?', 'ai-eshop-optimizer'))); ?>
'aieo-fs-rule-label', 'medium' => true, 'placeholder' => $aieo_fs_label_ph)), '', array('id' => 'aieo-fs-rule-label') ); echo $aieo_fs_out; ?>
array( 'name' => 'brand_term_ids', 'label' => __( 'Brands', 'ai-eshop-optimizer' ), 'help' => __( 'Leave empty to apply to any brand.', 'ai-eshop-optimizer' ) ), 'category' => array( 'name' => 'category_term_ids', 'label' => __( 'Categories', 'ai-eshop-optimizer' ), 'help' => __( 'Leave empty to apply to any category.', 'ai-eshop-optimizer' ) ), 'need' => array( 'name' => 'need_term_ids', 'label' => __( 'Needs', 'ai-eshop-optimizer' ), 'help' => __( 'Leave empty to apply to any need.', 'ai-eshop-optimizer' ) ), ) as $aieo_fs_entity => $aieo_fs_field ) { $aieo_fs_field['form'] = 'aieo-dmm-fs-rule-form'; echo AIEO_DMM_Product_Picker::entity_field( $aieo_fs_entity, $aieo_fs_field ); } echo AIEO_DMM_Product_Picker::entity_field( 'product', array( 'name' => 'product_ids', 'form' => 'aieo-dmm-fs-rule-form', 'label' => __( 'Specific products (optional)', 'ai-eshop-optimizer' ), 'help' => __( 'When set, the rule applies ONLY when the cart contains at least one of these (a positive whitelist, in addition to the filters beside it). Variations roll up to their parent.', 'ai-eshop-optimizer' ), 'selected' => isset( $edit_product_ids ) ? $edit_product_ids : array(), ) ); ?>
'code_patterns', 'label' => __('Product codes (optional)', 'ai-eshop-optimizer'), 'selected' => isset($edit_code_patterns) ? $edit_code_patterns : array(), )); $aieo_fs_out = AIEO_Kit::row( __('Minimum qualifying subtotal', 'ai-eshop-optimizer'), AIEO_Kit::input('min_subtotal', '0', array('id' => 'aieo-fs-rule-min', 'type' => 'number', 'step' => 'any', 'min' => '0', 'short' => true, 'unit' => $aieo_fs_cur, 'help' => true)), __('0 = no minimum; the rule applies to every matching cart.', 'ai-eshop-optimizer'), array('id' => 'aieo-fs-rule-min') ); echo $aieo_fs_out; $aieo_fs_out = AIEO_Kit::row( __('Threshold scope', 'ai-eshop-optimizer'), AIEO_Kit::select('min_subtotal_scope', array( 'cart_total' => __('Whole cart total', 'ai-eshop-optimizer'), 'targeted' => __('Subtotal of matching items only', 'ai-eshop-optimizer'), ), 'cart_total', array('id' => 'aieo-fs-rule-scope', 'help' => true)), __('"Whole cart total" = sum of every line. "Subtotal of matching items" = only lines hit by the filters above.', 'ai-eshop-optimizer'), array('id' => 'aieo-fs-rule-scope') ); echo $aieo_fs_out; ?>
'AND', 'OR' => 'OR'), array('AND'), array( 'type' => 'radio', 'descriptions' => array( 'AND' => __('every set targeting filter must match (brand AND category AND need AND specific-products), with the cart totalling at least the minimum subtotal', 'ai-eshop-optimizer'), 'OR' => __('any non-empty targeting filter that hits qualifies the offer, OR the whole cart reaches the minimum subtotal', 'ai-eshop-optimizer'), ), )), '', array('id' => 'aieo-fs-rule-operator', 'group' => true) ); echo $aieo_fs_out; ?>
'aieo-fs-rule-dates', 'label' => __('Schedule', 'ai-eshop-optimizer'), 'joiner' => '→', 'parts' => array( array('label' => __('From', 'ai-eshop-optimizer'), 'id' => 'aieo-fs-rule-from', 'control' => AIEO_Kit::input('date_from', '', array('id' => 'aieo-fs-rule-from', 'type' => 'date'))), array('label' => __('To', 'ai-eshop-optimizer'), 'id' => 'aieo-fs-rule-to', 'control' => AIEO_Kit::input('date_to', '', array('id' => 'aieo-fs-rule-to', 'type' => 'date'))), ), ))); echo $aieo_fs_dates; $aieo_fs_out = AIEO_Kit::row( __('Badge text (optional)', 'ai-eshop-optimizer'), AIEO_Kit::input('badge_label', '', array('id' => 'aieo-fs-rule-badge', 'maxlength' => self::BADGE_LABEL_MAX, 'placeholder' => self::badge_family_label(), 'help' => true)), __('Shown on the products this rule covers. Empty: the Free shipping badge\'s own text, set on the Badges screen.', 'ai-eshop-optimizer'), array('id' => 'aieo-fs-rule-badge') ); echo $aieo_fs_out; echo AIEO_Kit::row(__('Status', 'ai-eshop-optimizer'), AIEO_Kit::check('enabled', __('Enabled', 'ai-eshop-optimizer'), true, array('id' => 'aieo-fs-rule-enabled')), '', array('id' => 'aieo-fs-rule-enabled', 'group' => true)); $aieo_fs_order = class_exists('AIEO_DMM_Offer_Forms') ? AIEO_DMM_Offer_Forms::campaign_row('aieo-fs-rule-campaign') : ''; $aieo_fs_order .= class_exists('AIEO_DMM_Offer_Forms') && AIEO_DMM_Offer_Forms::shows_priority('free_shipping') ? AIEO_DMM_Offer_Forms::priority_row('aieo-fs-rule-priority') : ''; ?>
' . $aieo_fs_order . ''); } ?> __('What do exclusions do?', 'ai-eshop-optimizer'))); ?>
array( 'name' => 'excluded_brand_ids', 'label' => __( 'Excluded brands', 'ai-eshop-optimizer' ) ), 'category' => array( 'name' => 'excluded_category_ids', 'label' => __( 'Excluded categories', 'ai-eshop-optimizer' ) ), 'need' => array( 'name' => 'excluded_need_ids', 'label' => __( 'Excluded needs', 'ai-eshop-optimizer' ) ), ) as $aieo_fs_entity => $aieo_fs_field ) { $aieo_fs_field['mode'] = 'exclude'; $aieo_fs_field['form'] = 'aieo-dmm-fs-rule-form'; echo AIEO_DMM_Product_Picker::entity_field( $aieo_fs_entity, $aieo_fs_field ); } echo AIEO_DMM_Product_Picker::entity_field( 'product', array( 'name' => 'excluded_product_ids', 'form' => 'aieo-dmm-fs-rule-form', 'mode' => 'exclude', 'label' => __( 'Excluded specific products', 'ai-eshop-optimizer' ), 'help' => __( 'When the cart contains ANY of these, the rule does NOT apply. Variations roll up to their parent.', 'ai-eshop-optimizer' ), 'selected' => isset( $edit_excluded_product_ids ) ? $edit_excluded_product_ids : array(), ) ); ?>
'excluded_code_patterns', 'label' => __('Excluded product codes', 'ai-eshop-optimizer'), 'help' => __('Same patterns. A product whose SKU or barcode matches any of these never qualifies the rule, whatever the targeting above says.', 'ai-eshop-optimizer'), 'selected' => isset($edit_excluded_code_patterns) ? $edit_excluded_code_patterns : array(), )); ?>
'free-shipping-action-when-matched', 'icon' => 'zap', 'title' => __('Action when matched', 'ai-eshop-optimizer'), 'description' => __('Choose whether a matching cart gets every shipping option free or only the cheapest one.', 'ai-eshop-optimizer'), 'level' => 3)); echo $aieo_fs_act_open; ?> __('Force every shipping rate to free', 'ai-eshop-optimizer'), 'force_free_first' => __('Force only the cheapest rate to free', 'ai-eshop-optimizer'), ), 'force_free', array('id' => 'aieo-fs-rule-action', 'attrs' => array('aria-label' => __('Action when matched', 'ai-eshop-optimizer')))); echo $aieo_fs_action; ?>
'free-shipping-existing-rules', 'icon' => 'list', 'title' => __('Existing rules', 'ai-eshop-optimizer'), 'description' => __('The free-shipping rules you have saved; edit one to change its targeting or switch it off.', 'ai-eshop-optimizer'), )); echo $aieo_fs_open; ?> __('No unified rules yet. Create one above.', 'ai-eshop-optimizer'))); ?> 'success', 'scheduled' => 'warning', 'ended' => 'mono', 'off' => 'mono'); $aieo_fs_scopes = array( 'cart_total' => __('Whole cart total', 'ai-eshop-optimizer'), 'targeted' => __('Subtotal of matching items only', 'ai-eshop-optimizer'), ); $aieo_fs_actions = array( 'force_free' => __('Force every shipping rate to free', 'ai-eshop-optimizer'), 'force_free_first' => __('Force only the cheapest rate to free', 'ai-eshop-optimizer'), ); $aieo_fs_rows = array(); $aieo_fs_ask = AIEO_DMM_Offer_Forms::edit_asked(); $aieo_fs_asked = null; foreach ($rules as $r) { $aieo_fs_edit = AIEO_DMM_Offer_Forms::edit_window($r) + $this->edit_payload($r) + array('campaign_id' => (int) ($r['campaign_id'] ?? 0), 'priority' => (int) ($r['priority'] ?? 100)); $aieo_fs_state = !empty($r['enabled']) ? AIEO_DMM_Schedule::state_for($aieo_fs_edit['date_from'], $aieo_fs_edit['date_to'], $r) : 'off'; if ($aieo_fs_ask > 0 && $aieo_fs_ask === (int) $r['id']) { $aieo_fs_asked = $aieo_fs_edit; } $aieo_fs_min = (float) $r['min_subtotal']; $aieo_fs_kept = AIEO_DMM_Offer_Forms::kept_here($r); $aieo_fs_none = AIEO_DMM_Offer_Forms::targeting_of($r, $r)['_said'] ? '' : AIEO_DMM_Offer_Forms::NOT_SAID; $aieo_fs_rows[] = array( '_id' => (int) $r['id'], '_name' => (string) $r['label'], 'label' => array('title' => (string) $r['label'], 'sub' => '#' . (int) $r['id'] . ($aieo_fs_kept ? ' · ' . AIEO_DMM_Offer_Forms::kept_here_label() : '')), 'brands' => '' !== $aieo_fs_none ? $aieo_fs_none : self::names_summary($aieo_fs_edit['brand_term_names'], $aieo_fs_any), 'categories' => '' !== $aieo_fs_none ? $aieo_fs_none : self::names_summary($aieo_fs_edit['category_term_names'], $aieo_fs_any), 'needs' => '' !== $aieo_fs_none ? $aieo_fs_none : self::names_summary($aieo_fs_edit['need_term_names'], $aieo_fs_any), 'products' => '' !== $aieo_fs_none ? $aieo_fs_none : self::names_summary(wp_list_pluck($aieo_fs_edit['product_products'], 'text'), $aieo_fs_any), 'op' => '' !== $aieo_fs_none ? $aieo_fs_none : $aieo_fs_edit['rule_operator'], 'threshold' => '' !== $aieo_fs_none ? array('title' => $aieo_fs_none, 'sub' => '') : array( 'title' => html_entity_decode(wp_strip_all_tags(wc_price($aieo_fs_min)), ENT_QUOTES, 'UTF-8'), 'sub' => $aieo_fs_min > 0 ? $aieo_fs_scopes[$aieo_fs_edit['min_subtotal_scope']] : '', ), 'action' => $aieo_fs_actions[$aieo_fs_edit['action_kind']], 'window' => AIEO_DMM_Schedule::window_label_for($aieo_fs_edit['date_from'], $aieo_fs_edit['date_to'], $r), 'state' => array( 'label' => 'off' === $aieo_fs_state ? __('Disabled', 'ai-eshop-optimizer') : AIEO_DMM_Schedule::state_label($aieo_fs_state), 'tone' => $aieo_fs_tones[$aieo_fs_state], ), 'enabled' => (int) $r['enabled'] ? 'yes' : 'no', 'actions' => array( array( 'label' => __('Edit', 'ai-eshop-optimizer'), 'attrs' => array( 'data-aieo-fs-edit' => '1', 'data-rule' => (string) wp_json_encode($aieo_fs_edit), ), ), array( 'label' => __('Delete', 'ai-eshop-optimizer'), 'destructive' => true, 'attrs' => array( 'data-aieo-delete-row' => '1', 'data-action' => 'aieo_dmm_free_shipping_delete_rule', 'data-row' => (int) $r['id'], ), ), ), ); } echo \Rooster\Admin\Ui::table( array( array('key' => 'label', 'label' => __('Label', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'brands', 'label' => __('Brands', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'categories', 'label' => __('Categories', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'needs', 'label' => __('Needs', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'products', 'label' => __('Products', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'op', 'label' => __('Op', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'threshold', 'label' => __('Threshold', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'action', 'label' => __('Action', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'window', 'label' => __('Schedule', 'ai-eshop-optimizer'), 'type' => 'text'), array('key' => 'state', 'label' => __('State', 'ai-eshop-optimizer'), 'type' => 'status'), array('key' => 'enabled', 'label' => __('Enabled', 'ai-eshop-optimizer'), 'type' => 'boolean'), array('key' => 'actions', 'label' => __('Actions', 'ai-eshop-optimizer'), 'type' => 'actions'), ), $aieo_fs_rows, array('id' => 'aieo-free-shipping-rules', 'caption' => esc_html__('Existing rules', 'ai-eshop-optimizer'), 'scroll' => true) ); ?> name, ENT_QUOTES | ENT_HTML5, 'UTF-8') : ('#' . (int) $tid); } return $out; }; $patterns = static function ($raw) { $list = is_string($raw) ? json_decode($raw, true) : $raw; return AIEO_DMM_Pattern_Match::parse(is_array($list) ? $list : array()); }; $json = static function ($raw) { $value = is_string($raw) ? json_decode($raw, true) : $raw; return is_array($value) ? $value : array(); }; $brands = self::id_list($row['brand_term_ids'] ?? ''); $cats = self::id_list($row['category_term_ids'] ?? ''); $needs = self::id_list($row['need_term_ids'] ?? ''); $ex_brands = self::id_list($row['excluded_brand_ids'] ?? ''); $ex_cats = self::id_list($row['excluded_category_ids'] ?? ''); $ex_needs = self::id_list($row['excluded_need_ids'] ?? ''); $payload = $json($row['payload'] ?? ''); $display = $json($row['display'] ?? ''); return array( 'id' => isset($row['id']) ? (int) $row['id'] : 0, 'label' => (string) ($row['label'] ?? ''), 'brand_term_ids' => $brands, 'brand_term_names' => $names($brands), 'category_term_ids' => $cats, 'category_term_names' => $names($cats), 'need_term_ids' => $needs, 'need_term_names' => $names($needs), 'excluded_brand_ids' => $ex_brands, 'excluded_brand_names' => $names($ex_brands), 'excluded_category_ids' => $ex_cats, 'excluded_category_names' => $names($ex_cats), 'excluded_need_ids' => $ex_needs, 'excluded_need_names' => $names($ex_needs), 'product_products' => AIEO_DMM_Product_Picker::hydrate_ids(self::id_list($row['product_ids'] ?? '')), 'excluded_products' => AIEO_DMM_Product_Picker::hydrate_ids(self::id_list($row['excluded_product_ids'] ?? '')), 'code_patterns' => $patterns($row['code_patterns'] ?? array()), 'excluded_code_patterns' => $patterns($row['excluded_code_patterns'] ?? array()), 'rule_operator' => (isset($row['rule_operator']) && 'OR' === strtoupper((string) $row['rule_operator'])) ? 'OR' : 'AND', 'date_from' => AIEO_DMM_Schedule::clean_date($row['start_date'] ?? ''), 'date_to' => AIEO_DMM_Schedule::clean_date($row['end_date'] ?? ''), 'enabled' => !empty($row['enabled']) ? 1 : 0, 'min_subtotal' => isset($row['min_subtotal']) ? (float) $row['min_subtotal'] : 0.0, 'min_subtotal_scope' => (isset($row['min_subtotal_scope']) && 'targeted' === $row['min_subtotal_scope']) ? 'targeted' : 'cart_total', 'action_kind' => (isset($payload['action']) && 'force_free_first' === $payload['action']) ? 'force_free_first' : 'force_free', 'badge_label' => AIEO_DMM_Offer_Texts::standing_label(array(), is_array($display) ? $display : array()), ); } private static function id_list($raw) { if (is_string($raw)) { $raw = json_decode($raw, true); } return is_array($raw) ? array_values(array_filter(array_map('intval', $raw))) : array(); } private static function names_summary(array $names, $none) { $names = array_values(array_filter(array_map('strval', $names), 'strlen')); if (empty($names)) { return (string) $none; } $shown = array_slice($names, 0, 3); $more = count($names) - count($shown); $text = implode(', ', $shown); return $more > 0 ? sprintf(__('%1$s +%2$d', 'ai-eshop-optimizer'), $text, $more) : $text; } public static function badge_family_label() { $family = class_exists('AIEO_DMM_Badges') ? AIEO_DMM_Badges::get_family('free_shipping') : null; $label = (is_array($family) && isset($family['label'])) ? trim((string) $family['label']) : ''; return '' !== $label ? $label : __('Free delivery', 'ai-eshop-optimizer'); } public function render_archive_badge() { global $product; if (!$product || !is_a($product, 'WC_Product')) { return; } if (class_exists('AIEO_DMM_Badge_Renderer') && AIEO_DMM_Badge_Renderer::picture_carries($product->get_id())) { return; } echo $this->archive_badge_html($product); } public function archive_badge_html($product) { if (class_exists('AIEO_DMM_Badge_Renderer') && AIEO_DMM_Badge_Renderer::is_enabled()) { return ''; } if (!$product || !is_a($product, 'WC_Product')) { return ''; } if (!class_exists('AIEO_DMM_Free_Shipping_Rules') || !AIEO_DMM_Free_Shipping_Rules::has_targeted()) { return ''; } $rule = AIEO_DMM_Free_Shipping_Rules::covering_rule($product); if (!is_array($rule)) { return ''; } $family = class_exists('AIEO_DMM_Badges') ? AIEO_DMM_Badges::get_family('free_shipping') : null; if (is_array($family) && (empty($family['enabled']) || (isset($family['surfaces']['archive']) && empty($family['surfaces']['archive'])))) { return ''; } $label = AIEO_DMM_Offer_Texts::standing_label($rule, (array) ($rule['display'] ?? array())); if ('' === $label) { $label = self::badge_family_label(); } self::archive_badge_style(); $set_attr = class_exists('AIEO_DMM_Offer_Sets') ? AIEO_DMM_Offer_Sets::card_attr((int) $product->get_id()) : ''; return '' . '' . '' . esc_html($label) . '' . ''; } public function enqueue_archive_badge_css() { if (is_admin() || !function_exists('is_woocommerce')) { return; } if (class_exists('AIEO_DMM_Badge_Renderer') && AIEO_DMM_Badge_Renderer::is_enabled()) { return; } if (!class_exists('AIEO_DMM_Free_Shipping_Rules') || !AIEO_DMM_Free_Shipping_Rules::has_targeted()) { return; } $post = get_post(); $wants = is_woocommerce() || ($post instanceof WP_Post && (has_block('woocommerce/product-collection', $post) || has_block('woocommerce/products', $post) || has_block('woocommerce/product-template', $post))); if ($wants) { self::archive_badge_style(); } } private static function archive_badge_style() { if (!wp_style_is('aieo-fs-badge', 'registered')) { wp_register_style('aieo-fs-badge', false, array(), defined('AIEO_VERSION') ? AIEO_VERSION : '1'); wp_add_inline_style('aieo-fs-badge', self::archive_badge_css()); } wp_enqueue_style('aieo-fs-badge'); } public static function archive_badge_css() { return '.aieo-fs-badge{display:inline-flex;align-items:center;gap:.3em;box-sizing:border-box;inline-size:max-content;max-inline-size:100%;padding:.25rem .6rem;' . 'border-radius:var(--wp--custom--rooster--shape--badge,var(--wp--custom--rooster--shape--chip,999px));' . 'background:var(--wp--custom--rooster--badge--background,var(--wp--preset--color--contrast,var(--wp--preset--color--fg,CanvasText)));' . 'color:var(--wp--custom--rooster--badge--color,var(--wp--preset--color--bg,var(--wp--preset--color--base,Canvas)));font-size:var(--wp--preset--font-size--xs,.75rem);font-weight:700;line-height:1.2;white-space:nowrap}' . '.aieo-fs-badge-icon{flex:none;inline-size:1em;block-size:1em;background:currentColor;-webkit-mask:' . AIEO_Icons::mask_url('truck') . ' center/contain no-repeat;mask:' . AIEO_Icons::mask_url('truck') . ' center/contain no-repeat}' . '.aieo-fs-badge-text{min-inline-size:0;color:inherit;overflow:hidden;text-overflow:ellipsis}' . '@media (forced-colors:active){.aieo-fs-badge-icon{forced-color-adjust:none;background:CanvasText}}'; } public static function add_eligibility_row($rows, $product_id, $audience_key) { if (!is_array($rows)) { $rows = array(); } if ((int) $product_id !== 0) { return $rows; } if (!class_exists('AIEO_Effective_Eligibility')) { return $rows; } if (class_exists('AIEO_DMM_Price_Filter') && AIEO_DMM_Price_Filter::resolves()) { return $rows; } $rows[AIEO_Effective_Eligibility::SURFACE_FREE_SHIPPING_BAR] = self::is_audience_eligible((string) $audience_key); return $rows; } public static function is_audience_eligible($audience_key = 'guest') { if (class_exists('AIEO_DMM_Settings')) { if (!AIEO_DMM_Settings::is_module_enabled('free_shipping')) { return array('eligible' => false); } } $instance = self::eligibility_instance(); $s = $instance->get_settings(); $enabled = isset($s['enabled']) ? ($s['enabled'] === 'yes') : false; $threshold = isset($s['free_shipping_threshold']) ? (float) $s['free_shipping_threshold'] : 0.0; if (!$enabled || $threshold <= 0) { return array('eligible' => false); } return array( 'eligible' => true, 'offer_id' => null, 'payload' => array( 'threshold' => $threshold, 'msg_initial' => isset($s['msg_initial']) ? (string) $s['msg_initial'] : '', 'msg_progress' => isset($s['msg_progress']) ? (string) $s['msg_progress'] : '', 'msg_success' => isset($s['msg_success']) ? (string) $s['msg_success'] : '', ), ); } private static function eligibility_instance() { static $inst = null; if ($inst === null) { if (class_exists('AIEO_DMM') && method_exists('AIEO_DMM', 'instance')) { $mod = AIEO_DMM::instance()->get_module('free_shipping'); $inst = ($mod instanceof self) ? $mod : new self(); } else { $inst = new self(); } } return $inst; } public static function cod_fee_on() { $stored = get_option(self::OPTION_KEY, array()); return is_array($stored) && isset($stored['cod_enabled']) && 'yes' === $stored['cod_enabled']; } public function get_settings($raw = false) { $stored = get_option(self::OPTION_KEY, array()); if (!is_array($stored)) { $stored = array(); } $legacy = get_option('om_fs_settings', array()); if (!is_array($legacy)) { $legacy = array(); } $merged = array_merge(array( 'enabled' => 'yes', 'free_shipping_threshold' => isset($legacy['free_shipping_threshold']) ? (float) $legacy['free_shipping_threshold'] : 0, 'include_tax' => isset($legacy['include_tax']) ? $legacy['include_tax'] : 'no', 'msg_initial' => isset($legacy['msg_initial']) ? (string) $legacy['msg_initial'] : '', 'msg_progress' => isset($legacy['msg_progress']) ? (string) $legacy['msg_progress'] : '', 'msg_success' => isset($legacy['msg_success']) ? (string) $legacy['msg_success'] : '', 'msg_rule_product' => '', 'display_cart' => isset($legacy['display_cart']) ? $legacy['display_cart'] : 'yes', 'display_checkout' => isset($legacy['display_checkout']) ? $legacy['display_checkout'] : 'yes', 'display_mini_cart' => isset($legacy['display_mini_cart']) ? $legacy['display_mini_cart'] : 'yes', 'display_product' => isset($legacy['display_product']) ? $legacy['display_product'] : 'no', 'display_floating' => isset($legacy['display_floating']) ? $legacy['display_floating'] : 'no', 'default_country' => isset($legacy['default_country']) ? $legacy['default_country'] : '', 'default_postcode' => isset($legacy['default_postcode']) ? $legacy['default_postcode'] : '', 'bar_height' => isset($legacy['bar_height']) ? (int) $legacy['bar_height'] : 8, 'bar_border_radius' => isset($legacy['bar_border_radius']) ? (int) $legacy['bar_border_radius'] : 4, 'bar_bg_color' => isset($legacy['bar_bg_color']) ? (string) $legacy['bar_bg_color'] : '#e0e0e0', 'bar_progress_color' => isset($legacy['bar_progress_color']) ? (string) $legacy['bar_progress_color'] : '#4caf50', 'text_color' => isset($legacy['text_color']) ? (string) $legacy['text_color'] : '#333333', 'success_color' => isset($legacy['success_color']) ? (string) $legacy['success_color'] : '#2e7d32', 'amount_color' => isset($legacy['amount_color']) ? (string) $legacy['amount_color'] : '#bf4300', 'font_size' => isset($legacy['font_size']) ? (int) $legacy['font_size'] : 14, 'card_bg_color' => isset($legacy['card_bg_color']) ? (string) $legacy['card_bg_color'] : '#ffffff', 'card_padding' => isset($legacy['card_padding']) ? (int) $legacy['card_padding'] : 16, 'card_border_radius' => isset($legacy['card_border_radius']) ? (int) $legacy['card_border_radius'] : 8, 'card_border_color' => isset($legacy['card_border_color']) ? (string) $legacy['card_border_color'] : '#e0e0e0', 'notify_on_add_to_cart' => 'yes', 'notify_message' => '', 'notify_type' => 'notice', 'cod_enabled' => 'no', 'cod_fee' => 1.50, 'cod_label' => '', 'cod_taxable' => 'no', 'cod_gateway_slug' => 'cod', 'weight_exclusion_enabled' => 'no', 'max_cart_weight' => 0, 'weight_notify_message' => '', ), $stored); return $raw ? $merged : self::fill_i18n_defaults($merged); } public static function i18n_hints() { return array( 'msg_initial' => __('Free delivery on orders over {amount}', 'ai-eshop-optimizer'), 'msg_progress' => __('Only {remaining} left for free delivery', 'ai-eshop-optimizer'), 'msg_success' => __('Your order has free delivery', 'ai-eshop-optimizer'), 'msg_rule_product' => __('Free delivery with this product', 'ai-eshop-optimizer'), 'notify_message' => __('Note: this product is not eligible for free delivery. Your order will be charged for delivery, whatever its total.', 'ai-eshop-optimizer'), 'weight_notify_message' => __('Heads up: your cart is heavier than our free-shipping limit, so shipping will be charged on this order.', 'ai-eshop-optimizer'), 'cod_label' => __('Cash on delivery cost', 'ai-eshop-optimizer'), ); } private static function fill_i18n_defaults(array $s) { if (!did_action('init')) { return $s; } $i18n = array( 'msg_initial' => __('Free delivery on orders over {amount}', 'ai-eshop-optimizer'), 'msg_progress' => __('Only {remaining} left for free delivery', 'ai-eshop-optimizer'), 'msg_success' => __('Your order has free delivery', 'ai-eshop-optimizer'), 'msg_rule_product' => __('Free delivery with this product', 'ai-eshop-optimizer'), 'notify_message' => __('Note: this product is not eligible for free delivery. Your order will be charged for delivery, whatever its total.', 'ai-eshop-optimizer'), 'weight_notify_message' => __('Heads up: your cart is heavier than our free-shipping limit, so shipping will be charged on this order.', 'ai-eshop-optimizer'), 'cod_label' => __('Cash on delivery cost', 'ai-eshop-optimizer'), ); foreach ($i18n as $k => $v) { if (!isset($s[$k]) || '' === trim((string) $s[$k])) { $s[$k] = $v; } } return $s; } public function notify_on_add_to_cart($cart_item_key, $product_id, $quantity = 0, $variation_id = 0, $variation = array(), $cart_item_data = array()) { if (!function_exists('wc_add_notice') || !class_exists('AIEO_DMM_Pricing_Engine')) { return; } $check_id = $variation_id > 0 ? (int) $variation_id : (int) $product_id; if ($check_id <= 0) { return; } if (AIEO_DMM_Pricing_Engine::instance()->is_excluded_from_free_shipping($check_id)) { $settings = $this->get_settings(); $msg = isset($settings['notify_message']) && $settings['notify_message'] !== '' ? (string) $settings['notify_message'] : __('Note: this product is not eligible for free delivery.', 'ai-eshop-optimizer'); $type = (isset($settings['notify_type']) && $settings['notify_type'] === 'error') ? 'error' : 'notice'; wc_add_notice($msg, $type); } } public function render_product_page_notice() { if (!function_exists('wc_get_product') || !class_exists('AIEO_DMM_Pricing_Engine')) { return; } global $product; if (!$product || !is_a($product, 'WC_Product')) { return; } $pid = (int) $product->get_id(); if (!AIEO_DMM_Pricing_Engine::instance()->is_excluded_from_free_shipping($pid)) { return; } $settings = $this->get_settings(); $msg = isset($settings['notify_message']) && $settings['notify_message'] !== '' ? (string) $settings['notify_message'] : __('Note: this product is not eligible for free delivery.', 'ai-eshop-optimizer'); echo self::product_notice_html($msg); } public static function product_notice_html($msg) { if ('' === trim((string) $msg) || !function_exists('wc_print_notice')) { return ''; } return '
' . wc_print_notice(esc_html((string) $msg), 'notice', array(), true) . '
'; } public function css_vars() { $s = $this->get_settings(); $vars = array(); $colour = static function ($name, $value, array $shipped) use (&$vars) { $v = strtolower(trim((string) $value)); if ('' !== $v && !in_array($v, $shipped, true) && preg_match('/^#[0-9a-f]{3,8}$/', $v)) { $vars[] = '--rooster-free-delivery-' . $name . ':' . $v; } }; $colour('track', $s['bar_bg_color'] ?? '', array('#e0e0e0')); $colour('fill', $s['bar_progress_color'] ?? '', array('#4caf50')); $colour('ink', $s['text_color'] ?? '', array('#333333', '#333')); $colour('done', $s['success_color'] ?? '', array('#2e7d32')); $colour('amount', $s['amount_color'] ?? '', array('#bf4300', '#e65100')); $size = static function ($name, $value, array $shipped) use (&$vars) { $n = (int) $value; if ($n > 0 && !in_array($n, $shipped, true)) { $vars[] = '--rooster-free-delivery-' . $name . ':' . $n . 'px'; } }; $size('bar', $s['bar_height'] ?? 0, array(8)); $size('radius', $s['bar_border_radius'] ?? 0, array(4)); $size('size', $s['font_size'] ?? 0, array(14)); return $vars ? ':root{' . implode(';', $vars) . '}' : ''; } public function enqueue_css_vars() { if (!$this->should_emit_css()) { return; } $vars = $this->css_vars(); if ('' === $vars) { return; } $handle = 'aieo-dmm-free-shipping-vars'; wp_register_style($handle, false, array(), AIEO_VERSION); wp_enqueue_style($handle); wp_add_inline_style($handle, $vars); } private function should_emit_css() { $s = $this->get_settings(); if (!empty($s['display_floating']) && $s['display_floating'] === 'yes') { return true; } if (function_exists('is_cart') && is_cart()) { return true; } if (function_exists('is_checkout') && is_checkout()) { return true; } if (function_exists('is_product') && is_product()) { return true; } return AIEO_DMM_Settings::is_module_enabled('side_cart') || AIEO_DMM_Settings::get('side_cart_enabled', false); } public function enqueue_admin_assets() { wp_enqueue_style('wp-color-picker'); wp_enqueue_script('wp-color-picker'); wp_add_inline_script('wp-color-picker', 'jQuery(function($){$(".aieo-dmm-fs-color").wpColorPicker();});' ); } public function ajax_save() { AIEO_DMM::verify_ajax_request(); $section = isset($_POST['form_section']) ? sanitize_key(wp_unslash($_POST['form_section'])) : ''; if (!in_array($section, array('eligibility', 'display', 'cod'), true)) { $section = ''; } $current = $this->get_settings(true); $patch = array(); if ($section === '' || $section === 'eligibility') { $patch['enabled'] = !empty($_POST['enabled']) ? 'yes' : 'no'; $patch['free_shipping_threshold'] = isset($_POST['free_shipping_threshold']) ? (float) $_POST['free_shipping_threshold'] : 0; $patch['include_tax'] = !empty($_POST['include_tax']) ? 'yes' : 'no'; $patch['default_country'] = isset($_POST['default_country']) ? sanitize_text_field(wp_unslash($_POST['default_country'])) : ''; $patch['default_postcode'] = isset($_POST['default_postcode']) ? sanitize_text_field(wp_unslash($_POST['default_postcode'])) : ''; $patch['weight_exclusion_enabled'] = !empty($_POST['weight_exclusion_enabled']) ? 'yes' : 'no'; $patch['max_cart_weight'] = isset($_POST['max_cart_weight']) ? max(0, (float) $_POST['max_cart_weight']) : 0; $patch['weight_notify_message'] = isset($_POST['weight_notify_message']) ? sanitize_textarea_field(wp_unslash($_POST['weight_notify_message'])) : ''; if (AIEO_DMM_Free_Shipping_Rules::reads_offers_now()) { unset($patch['free_shipping_threshold']); } } if ($section === '' || $section === 'cod') { $patch['cod_enabled'] = !empty($_POST['cod_enabled']) ? 'yes' : 'no'; $patch['cod_fee'] = isset($_POST['cod_fee']) ? max(0, (float) $_POST['cod_fee']) : 0; $patch['cod_label'] = isset($_POST['cod_label']) ? mb_substr(sanitize_text_field(wp_unslash($_POST['cod_label'])), 0, 100) : ''; $patch['cod_taxable'] = !empty($_POST['cod_taxable']) ? 'yes' : 'no'; $patch['cod_gateway_slug'] = isset($_POST['cod_gateway_slug']) ? sanitize_key(wp_unslash($_POST['cod_gateway_slug'])) : 'cod'; if ($patch['cod_gateway_slug'] === '') { $patch['cod_gateway_slug'] = 'cod'; } } if ($section === '' || $section === 'display') { $patch['msg_initial'] = isset($_POST['msg_initial']) ? sanitize_text_field(wp_unslash($_POST['msg_initial'])) : ''; $patch['msg_progress'] = isset($_POST['msg_progress']) ? sanitize_text_field(wp_unslash($_POST['msg_progress'])) : ''; $patch['msg_success'] = isset($_POST['msg_success']) ? sanitize_text_field(wp_unslash($_POST['msg_success'])) : ''; $patch['msg_rule_product'] = isset($_POST['msg_rule_product']) ? sanitize_text_field(wp_unslash($_POST['msg_rule_product'])) : ''; $patch['display_cart'] = !empty($_POST['display_cart']) ? 'yes' : 'no'; $patch['display_checkout'] = !empty($_POST['display_checkout']) ? 'yes' : 'no'; $patch['display_mini_cart'] = !empty($_POST['display_mini_cart']) ? 'yes' : 'no'; $patch['display_product'] = !empty($_POST['display_product']) ? 'yes' : 'no'; $patch['display_floating'] = !empty($_POST['display_floating']) ? 'yes' : 'no'; $patch['notify_on_add_to_cart'] = !empty($_POST['notify_on_add_to_cart']) ? 'yes' : 'no'; $patch['notify_message'] = isset($_POST['notify_message']) ? sanitize_textarea_field(wp_unslash($_POST['notify_message'])) : ''; $patch['notify_type'] = (isset($_POST['notify_type']) && sanitize_key(wp_unslash($_POST['notify_type'])) === 'error') ? 'error' : 'notice'; $num_clamps = array( 'bar_height' => array(1, 60), 'bar_border_radius' => array(0, 40), 'font_size' => array(8, 40), 'card_padding' => array(0, 80), 'card_border_radius' => array(0, 40), ); foreach ($num_clamps as $f => $clamp) { $v = isset($_POST[$f]) ? (int) $_POST[$f] : 0; $patch[$f] = max($clamp[0], min($clamp[1], $v)); } $color_fields = array('bar_bg_color', 'bar_progress_color', 'text_color', 'success_color', 'amount_color', 'card_bg_color', 'card_border_color'); foreach ($color_fields as $f) { $raw = isset($_POST[$f]) ? sanitize_text_field(wp_unslash($_POST[$f])) : ''; $patch[$f] = sanitize_hex_color($raw) ?: ''; } } $data = array_merge($current, $patch); update_option(self::OPTION_KEY, $data, false); update_option('om_fs_settings', $data, false); AIEO_DMM_Cache::bump_version('shipping'); wp_send_json_success(array('message' => __('Free shipping settings saved.', 'ai-eshop-optimizer'))); } public function ajax_add_exclusions() { AIEO_DMM::verify_ajax_request(); $mode = isset($_POST['mode']) && sanitize_key(wp_unslash($_POST['mode'])) === 'replace' ? 'replace' : 'append'; $ids_raw = isset($_POST['product_ids']) ? sanitize_text_field(wp_unslash($_POST['product_ids'])) : ''; $ids = preg_split('/[\s,;]+/', $ids_raw, -1, PREG_SPLIT_NO_EMPTY); $ids = array_map('absint', $ids); if (!empty($_FILES['csv_file']['tmp_name']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])) { $handle = fopen($_FILES['csv_file']['tmp_name'], 'r'); if ($handle) { while (($row = fgetcsv($handle, 0, ',', '"', '')) !== false) { foreach ($row as $cell) { $v = absint($cell); if ($v > 0) { $ids[] = $v; } } } fclose($handle); } } $ids = array_unique(array_filter($ids)); if (empty($ids)) { wp_send_json_error(array('message' => __('No product IDs received.', 'ai-eshop-optimizer'))); } global $wpdb; $tables = array( $wpdb->prefix . 'aieo_dmm_no_free_shipping', $wpdb->prefix . 'om_no_free_shipping', ); $products = array(); foreach ($ids as $pid) { $post = get_post($pid); if (!$post || !in_array($post->post_type, array('product', 'product_variation'), true)) { continue; } if ($post->post_type === 'product_variation') { $pid = (int) $post->post_parent; } if ($pid > 0) { $products[(int) $pid] = true; } } $products = array_keys($products); if ($mode === 'replace') { if (!$products) { wp_send_json_error(array('message' => __('None of these is a product: the list is left as it is.', 'ai-eshop-optimizer'))); } $held = $this->count_exclusions(); $confirmed = isset($_POST['confirmed']) && '1' === sanitize_key(wp_unslash($_POST['confirmed'])); if ($held > 0 && !$confirmed) { wp_send_json_error(array( 'code' => 'needs_confirmation', 'held' => $held, 'sent' => count($products), 'message' => sprintf( _n('The %d product on the list now is removed.', 'The %d products on the list now are removed.', $held, 'ai-eshop-optimizer'), $held ) . ' ' . sprintf( _n('%d product takes its place.', '%d products take their place.', count($products), 'ai-eshop-optimizer'), count($products) ), )); } foreach ($tables as $table) { if (aieo_dmm_table_exists($table)) { $wpdb->query("TRUNCATE TABLE {$table}"); } } } $added = 0; foreach ($products as $pid) { $sku = get_post_meta($pid, '_sku', true); foreach ($tables as $table) { if (!aieo_dmm_table_exists($table)) { continue; } $exists = $wpdb->get_var($wpdb->prepare( "SELECT 1 FROM {$table} WHERE product_id = %d LIMIT 1", $pid )); if (!$exists) { $wpdb->insert($table, array( 'product_id' => $pid, 'sku' => (string) $sku, ), array('%d', '%s')); $added++; } } } AIEO_DMM_Cache::bump_version('shipping'); wp_cache_delete('om_no_free_shipping_ids', 'om_shipping'); wp_send_json_success(array( 'added' => $added, 'message' => sprintf( _n('%d product excluded from free shipping.', '%d products excluded from free shipping.', $added, 'ai-eshop-optimizer'), $added ), )); } public function ajax_remove_exclusion() { AIEO_DMM::verify_ajax_request(); $pid = isset($_POST['product_id']) ? absint(wp_unslash($_POST['product_id'])) : 0; if ($pid <= 0) { wp_send_json_error(array('message' => __('Invalid id.', 'ai-eshop-optimizer'))); } global $wpdb; foreach (array($wpdb->prefix . 'aieo_dmm_no_free_shipping', $wpdb->prefix . 'om_no_free_shipping') as $table) { if (aieo_dmm_table_exists($table)) { $wpdb->delete($table, array('product_id' => $pid), array('%d')); } } AIEO_DMM_Cache::bump_version('shipping'); wp_cache_delete('om_no_free_shipping_ids', 'om_shipping'); wp_send_json_success(); } public function ajax_export_exclusions() { AIEO_DMM::verify_ajax_request(); global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_no_free_shipping'; if (!aieo_dmm_table_exists($table)) { wp_send_json_error(array('message' => __('Table missing.', 'ai-eshop-optimizer'))); } $rows = $wpdb->get_results("SELECT product_id, sku FROM {$table} ORDER BY product_id ASC", ARRAY_A); $dir = AIEO_DMM::get_upload_path('exports'); $filename = 'no-free-shipping-' . gmdate('Ymd-His') . '.csv'; $path = trailingslashit($dir['path']) . $filename; $url = trailingslashit($dir['url']) . $filename; $h = fopen($path, 'w'); AIEO_DMM_Sample::write_csv_bom($h); fputcsv($h, array('product_id', 'sku'), ',', '"', ''); foreach ((array) $rows as $row) { fputcsv($h, $row, ',', '"', ''); } fclose($h); wp_send_json_success(array('url' => $url, 'filename' => $filename, 'message' => __('The list is exported.', 'ai-eshop-optimizer'))); } private function fetch_exclusions($per_page, $page) { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_no_free_shipping'; if (!aieo_dmm_table_exists($table)) { return array(); } $offset = max(0, ((int) $page - 1) * (int) $per_page); $rows = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table} ORDER BY product_id ASC LIMIT %d OFFSET %d", (int) $per_page, $offset ), ARRAY_A); if (!is_array($rows)) { return array(); } foreach ($rows as &$row) { $post = get_post((int) $row['product_id']); $row['title'] = $post ? $post->post_title : ''; } return $rows; } private function count_exclusions() { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_no_free_shipping'; if (!aieo_dmm_table_exists($table)) { return 0; } return (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table}"); } public function filter_package_rates($rates, $package) { if (empty($rates) || empty($package['contents']) || !is_array($package['contents'])) { return $rates; } if (!class_exists('AIEO_DMM_Free_Shipping_Gate', false)) { require_once dirname(__DIR__) . '/services/class-aieo-dmm-free-shipping-gate.php'; } $s = $this->get_settings(); return AIEO_DMM_Free_Shipping_Gate::strip($rates, $package, (string) ($s['weight_notify_message'] ?? ''), $s); } public function get_free_shipping_rules() { return array_values(array_filter(AIEO_DMM_Free_Shipping_Rules::active(), array('AIEO_DMM_Free_Shipping_Rules', 'said_whole'))); } public static function cart_qualifies_for_free($package = null) { $contents = (is_array($package) && isset($package['contents']) && is_array($package['contents'])) ? $package['contents'] : null; return AIEO_DMM_Free_Shipping_Rules::cart_is_free($contents); } public function apply_unified_free_shipping_rules($rates, $package) { if (empty($rates) || empty($package['contents']) || !is_array($package['contents'])) { return $rates; } if (apply_filters('aieo_free_shipping_rules_paused', false)) { return $rates; } return AIEO_DMM_Free_Shipping_Rules::apply_to_rates($rates, $package['contents']); } public function mark_packages($packages) { return AIEO_DMM_Free_Shipping_Rules::mark_packages($packages); } public function ajax_save_rule() { AIEO_DMM::verify_ajax_request(); global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_offers'; if (!aieo_dmm_table_exists($tbl)) { wp_send_json_error(array('message' => __('Unified offers table missing — re-activate the plugin.', 'ai-eshop-optimizer'))); } $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0; $brand_ids = isset($_POST['brand_term_ids']) && is_array($_POST['brand_term_ids']) ? array_values(array_filter(array_map('absint', wp_unslash($_POST['brand_term_ids'])))) : array(); $cat_ids = isset($_POST['category_term_ids']) && is_array($_POST['category_term_ids']) ? array_values(array_filter(array_map('absint', wp_unslash($_POST['category_term_ids'])))) : array(); $need_ids = isset($_POST['need_term_ids']) && is_array($_POST['need_term_ids']) ? array_values(array_filter(array_map('absint', wp_unslash($_POST['need_term_ids'])))) : array(); $excl_brand = isset($_POST['excluded_brand_ids']) && is_array($_POST['excluded_brand_ids']) ? array_values(array_filter(array_map('absint', wp_unslash($_POST['excluded_brand_ids'])))) : array(); $excl_cat = isset($_POST['excluded_category_ids']) && is_array($_POST['excluded_category_ids']) ? array_values(array_filter(array_map('absint', wp_unslash($_POST['excluded_category_ids'])))) : array(); $excl_need = isset($_POST['excluded_need_ids']) && is_array($_POST['excluded_need_ids']) ? array_values(array_filter(array_map('absint', wp_unslash($_POST['excluded_need_ids'])))) : array(); $positive_product_ids = AIEO_DMM_Product_Picker::roll_up_to_parents( AIEO_DMM_Product_Picker::collect_ids('product_ids') ); $excluded_product_ids = AIEO_DMM_Product_Picker::roll_up_to_parents( AIEO_DMM_Product_Picker::collect_ids('excluded_product_ids') ); $code_patterns = AIEO_DMM_Pattern_Match::collect('code_patterns'); $excluded_code_patterns = AIEO_DMM_Pattern_Match::collect('excluded_code_patterns'); $rule_op = isset($_POST['rule_operator']) && strtoupper(sanitize_key(wp_unslash($_POST['rule_operator']))) === 'OR' ? 'OR' : 'AND'; $threshold = isset($_POST['min_subtotal']) ? (float) $_POST['min_subtotal'] : 0; $threshold_scope = isset($_POST['min_subtotal_scope']) && sanitize_key(wp_unslash($_POST['min_subtotal_scope'])) === 'targeted' ? 'targeted' : 'cart_total'; $action = isset($_POST['action_kind']) && sanitize_key(wp_unslash($_POST['action_kind'])) === 'force_free_first' ? 'force_free_first' : 'force_free'; if (empty($brand_ids) && empty($cat_ids) && empty($need_ids) && empty($positive_product_ids) && $threshold <= 0 && empty($code_patterns)) { wp_send_json_error(array('message' => __('Set a brand, category, need, product, product-code pattern, or minimum subtotal. Otherwise the rule applies unconditionally.', 'ai-eshop-optimizer'))); } $date_from_raw = isset($_POST['date_from']) ? sanitize_text_field(wp_unslash($_POST['date_from'])) : ''; $date_to_raw = isset($_POST['date_to']) ? sanitize_text_field(wp_unslash($_POST['date_to'])) : ''; $window_error = AIEO_DMM_Schedule::window_error($date_from_raw, $date_to_raw); if ('' !== $window_error) { wp_send_json_error(array('message' => $window_error)); } $date_from = AIEO_DMM_Schedule::clean_date($date_from_raw); $date_to = AIEO_DMM_Schedule::clean_date($date_to_raw); $display = array(); if ($id > 0) { $existing = $wpdb->get_row($wpdb->prepare("SELECT id, display FROM {$tbl} WHERE id = %d AND type = 'free_shipping'", $id), ARRAY_A); if (empty($existing)) { wp_send_json_error(array('message' => __('This rule no longer exists. Reload the page and try again.', 'ai-eshop-optimizer'))); } $stored_display = json_decode((string) ($existing['display'] ?? ''), true); if (is_array($stored_display)) { $display = $stored_display; } } $badge_label = isset($_POST['badge_label']) ? sanitize_text_field(wp_unslash($_POST['badge_label'])) : ''; if (function_exists('mb_substr')) { $badge_label = mb_substr($badge_label, 0, self::BADGE_LABEL_MAX); } $display = AIEO_DMM_Offer_Texts::with_label($display, $badge_label, null); $data = array( 'type' => 'free_shipping', 'enabled' => !empty($_POST['enabled']) ? 1 : 0, 'label' => isset($_POST['label']) ? sanitize_text_field(wp_unslash($_POST['label'])) : '', 'rule_operator' => $rule_op, 'brand_term_ids' => wp_json_encode($brand_ids), 'category_term_ids' => wp_json_encode($cat_ids), 'need_term_ids' => wp_json_encode($need_ids), 'product_ids' => wp_json_encode($positive_product_ids), 'excluded_brand_ids' => wp_json_encode($excl_brand), 'excluded_category_ids' => wp_json_encode($excl_cat), 'excluded_need_ids' => wp_json_encode($excl_need), 'excluded_product_ids' => wp_json_encode($excluded_product_ids), 'code_patterns' => AIEO_DMM_Pattern_Match::to_json($code_patterns), 'excluded_code_patterns' => AIEO_DMM_Pattern_Match::to_json($excluded_code_patterns), 'min_subtotal' => $threshold, 'min_subtotal_scope' => $threshold_scope, 'application_scope' => 'whole_cart', 'payload' => wp_json_encode(array('action' => $action)), 'display' => wp_json_encode((object) $display), 'start_date' => '' !== $date_from ? $date_from : null, 'end_date' => '' !== $date_to ? $date_to : null, ); require_once dirname(__DIR__) . '/services/class-aieo-dmm-offer-forms.php'; if (AIEO_DMM_Offer_Forms::previewing()) { AIEO_DMM_Offer_Forms::answer_preview('', array($data + ($id > 0 ? array('id' => $id) : array())), array(), AIEO_DMM_Offer_Store::ORIGIN_FREE_SHIPPING); } $saved = AIEO_DMM_Offer_Forms::save_offer($data + ($id > 0 ? array('id' => $id) : array()), 'the free-shipping rules form', AIEO_DMM_Offer_Store::ORIGIN_FREE_SHIPPING); if (is_wp_error($saved)) { AIEO_DMM_Offer_Forms::refuse($saved); } $id = (int) $saved['id']; AIEO_DMM_Free_Shipping_Rules::rebuild(); do_action('rooster/store_features/changed'); AIEO_DMM_Offer_Pages::purge('free_shipping_rule'); wp_send_json_success(array( 'id' => $id, 'message' => __('Free-shipping rule saved.', 'ai-eshop-optimizer'), )); } public function ajax_delete_rule() { AIEO_DMM::verify_ajax_request(); global $wpdb; $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0; if ($id <= 0) { wp_send_json_error(array('message' => __('Invalid id.', 'ai-eshop-optimizer'))); } $tbl = $wpdb->prefix . 'aieo_dmm_offers'; $is_rule = (int) $wpdb->get_var($wpdb->prepare("SELECT id FROM {$tbl} WHERE id = %d AND type = 'free_shipping' AND state <> 'archived'", $id)); if ($is_rule > 0) { require_once dirname(__DIR__) . '/services/class-aieo-dmm-offer-forms.php'; $archived = AIEO_DMM_Offer_Forms::archive_offer($id, 'deleted in the free-shipping rules form'); if (is_wp_error($archived)) { AIEO_DMM_Offer_Forms::refuse($archived); } AIEO_DMM_Free_Shipping_Rules::rebuild(); do_action('rooster/store_features/changed'); AIEO_DMM_Offer_Pages::purge('free_shipping_rule'); } wp_send_json_success(); } public function apply_cod_fee_to_cart($cart) { if (is_admin() && !defined('DOING_AJAX')) { return; } if (!function_exists('WC') || !WC() || !WC()->session) { return; } $s = $this->get_settings(); if ($s['cod_enabled'] !== 'yes') { return; } $chosen = (string) WC()->session->get('chosen_payment_method'); if ($chosen !== (string) $s['cod_gateway_slug']) { return; } $fee_amount = (float) $s['cod_fee']; if (class_exists('AIEO_DMM_COD_Country_Block') && method_exists('AIEO_DMM_COD_Country_Block', 'cod_fee_override_for_chosen')) { $override = AIEO_DMM_COD_Country_Block::cod_fee_override_for_chosen(); if ($override !== null) { $fee_amount = (float) $override; } } if ($fee_amount <= 0) { return; } $fee_label = (string) $s['cod_label']; if ($fee_label === '') { return; } $taxable = $s['cod_taxable'] === 'yes'; foreach ($cart->get_fees() as $existing) { $existing_name = isset($existing->name) ? (string) $existing->name : ''; if (mb_strtolower(trim($existing_name)) === mb_strtolower(trim($fee_label))) { $existing->amount = $fee_amount; $existing->total = $fee_amount; $existing->taxable = $taxable; return; } } $cart->add_fee($fee_label, $fee_amount, $taxable); } public function force_cod_visible_when_aieo_enabled($gateways) { if (is_admin() && !wp_doing_ajax()) { return $gateways; } if (!is_array($gateways)) { return $gateways; } $s = $this->get_settings(); if ($s['cod_enabled'] !== 'yes') { return $gateways; } $slug = (string) $s['cod_gateway_slug']; if ($slug === '' || isset($gateways[$slug])) { return $gateways; } if (!function_exists('WC') || !WC() || !WC()->payment_gateways) { return $gateways; } $all = WC()->payment_gateways->payment_gateways(); if (isset($all[$slug]) && $all[$slug]->enabled === 'yes') { $gateways[$slug] = $all[$slug]; } return $gateways; } public function apply_cod_fee_admin($order_id) { $s = $this->get_settings(); if ($s['cod_enabled'] !== 'yes') { return; } $order = wc_get_order($order_id); if (!$order) { return; } $new_method = isset($_POST['_payment_method']) ? wc_clean(wp_unslash($_POST['_payment_method'])) : ''; if ($new_method !== (string) $s['cod_gateway_slug']) { return; } $fee_amount = (float) $s['cod_fee']; if ($fee_amount <= 0) { return; } $fee_label = (string) $s['cod_label']; $taxable = $s['cod_taxable'] === 'yes'; foreach ($order->get_items('fee') as $fee_item_id => $fee_item) { if (mb_strtolower(trim((string) $fee_item->get_name())) === mb_strtolower(trim($fee_label))) { $order->remove_item($fee_item_id); } } $fee = new WC_Order_Item_Fee(); $fee->set_name($fee_label); $fee->set_total(wc_format_decimal($fee_amount)); $fee->set_props(array('tax_status' => $taxable ? 'taxable' : 'none')); $order->add_item($fee); $order->calculate_totals(); if (class_exists('WC_Data_Store')) { WC_Data_Store::load('order')->update($order); } } public function output_cod_refresh_js() { $s = $this->get_settings(); if ($s['cod_enabled'] !== 'yes') { return; } if (!function_exists('is_checkout') || !is_checkout()) { return; } if (function_exists('is_wc_endpoint_url') && is_wc_endpoint_url()) { return; } ?>