<?php

namespace Quicker\Core\Frontend;

use Quicker\Utils\Singleton;

/**
 * Base Class
 *
 * @since 1.0.0
 */
class Ajax_Action {

	use Singleton;

	/**
	 * Ajax action
	 */
	public function init() {
		$callback = array( 'quicker_update_mini_cart', 'quick_view', 'quicker_remove_cart_item', 'quicker_apply_coupon', 'quicker_remove_coupon' );
		if ( ! empty( $callback ) ) {
			foreach ( $callback as $key => $value ) {
				add_action( 'wp_ajax_' . $value, array( $this, $value ) );
				add_action( 'wp_ajax_nopriv_' . $value, array( $this, $value ) );
			}
		}
	}


	/**
	 * Variation product template
	 */
	public function variation_popup_template( $product_id ) {
		$settings = \Quicker\Utils\Helper::get_settings();

		wp( 'p=' . $product_id . '&post_type=product' );
		while ( have_posts() ) :
			the_post();
			if ( isset( $settings['quicker_view_desc'] ) && $settings['quicker_view_desc'] === 'no' ) {
				add_filter(
					'woocommerce_short_description',
					function ( $desc ) {
						return '';
					},
					99
				);
			} elseif ( isset( $settings['quicker_view_desc'] ) && $settings['quicker_view_desc'] === 'full' ) {
				add_filter(
					'woocommerce_short_description',
					function ( $desc ) {
						global $post;
						// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Using WordPress core filter
						return '<div class="woocommerce-product-details__full-description">' . apply_filters( 'the_content', $post->post_content ) . '</div>';
					},
					99
				);
			}
			?>
			<div class="modal-content">
				<button type="button" class="quicker-popup-close" aria-label="Close">
					<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
						<circle cx="10" cy="10" r="10" fill="#333" opacity="0.6" />
						<path d="M6 6 L14 14 M14 6 L6 14" stroke="#fff" stroke-width="2" stroke-linecap="round" />
					</svg>
				</button>
				<div id="product-<?php echo intval( $product_id ); ?>" <?php wc_product_class( 'product' ); ?>>
					<div class="product-images">
						<?php
						global $product;
						$columns           = apply_filters( 'woocommerce_product_thumbnails_columns', 4 );
						$post_thumbnail_id = $product->get_image_id();
						$wrapper_classes   = apply_filters(
							'woocommerce_single_product_image_gallery_classes',
							array(
								'woocommerce-product-gallery',
								'woocommerce-product-gallery--with-images',
								'woocommerce-product-gallery--columns-' . absint( $columns ),
								'images',
							)
						);
						?>
						<div class="<?php echo esc_attr( implode( ' ', array_map( 'sanitize_html_class', $wrapper_classes ) ) ); ?>">
							<figure class="woocommerce-product-gallery__wrapper">
								<?php
								if ( $post_thumbnail_id ) {
									$html = wc_get_gallery_image_html( $post_thumbnail_id, true );
								} else {
									$html  = '<div class="woocommerce-product-gallery__image--placeholder">';
									$html .= sprintf( '<img src="%s" alt="%s" class="wp-post-image" />', esc_url( wc_placeholder_img_src( 'woocommerce_single' ) ), esc_html__( 'Awaiting product image', 'quicker' ) );
									$html .= '</div>';
								}
								// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- WooCommerce filter returns safe HTML
								echo apply_filters( 'woocommerce_single_product_image_thumbnail_html', $html, $post_thumbnail_id );

								// Gallery thumbnails
								$attachment_ids = $product->get_gallery_image_ids();
								if ( $attachment_ids && $post_thumbnail_id ) {
									foreach ( $attachment_ids as $attachment_id ) {
										// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- WooCommerce filter returns safe HTML
										echo apply_filters( 'woocommerce_single_product_image_thumbnail_html', wc_get_gallery_image_html( $attachment_id ), $attachment_id );
									}
								}
								?>
							</figure>
						</div>
					</div>
					<div class="summary entry-summary">
						<?php do_action( 'woocommerce_single_product_summary' ); ?>
					</div>
				</div>
			</div>
			<?php
		endwhile;
	}

	public function quick_view() {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX action uses wp_ajax hook which handles security
		$product_id  = isset( $_POST['product_id'] ) ? sanitize_text_field( wp_unslash( $_POST['product_id'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX action uses wp_ajax hook which handles security
		$view_action = isset( $_POST['quick_view_action'] ) ? sanitize_text_field( wp_unslash( $_POST['quick_view_action'] ) ) : '';

		if ( ! empty( $product_id ) && ( 'variation_popup' == $view_action ) ) {

			// Get the output
			ob_start();
			$this->variation_popup_template( $product_id );
			$html = ob_get_clean();

			// Add initialization script
			$html .= "<script type='text/javascript'>
				jQuery(function($){
					$('.variations_form').each(function(){
						$(this).wc_variation_form();
						$(this).trigger('check_variations');
					});
				});
			</script>";

			wp_send_json_success(
				array(
					'success' => 1,
					'message' => 'success',
					'data'    => json_encode( $html ),
				)
			);
		} else {
			$msg = $product_id == '' ? esc_html__( 'Product Id missing', 'quicker' ) : esc_html__( 'Something is wrong', 'quicker' );
			wp_send_json_error(
				array(
					'success' => 0,
					'message' => $msg,
					'data'    => array(),
				)
			);
		}

		wp_die();
	}

	public function error_response( $message = '' ) {
		$mes = empty( $message ) ? __( 'Required data missing', 'quicker' ) : $message;
		return wp_send_json_success( array( 'message' => $mes ) );
	}

	public function send_success( $message ) {
		// Force session reload to ensure we have the latest cart data
		if ( WC()->session && WC()->cart ) {
			WC()->cart->get_cart_from_session();
		}

		// Capture any existing notices before cart operations
		$existing_notices = wc_get_notices();

		// Recalculate cart totals to ensure coupons and discounts are properly calculated
		if ( WC()->cart ) {
			do_action( 'woocommerce_cart_loaded_from_session', WC()->cart );

			// Manually trigger Discountify coupon application for AJAX context
			if ( class_exists( 'Discountify\Core\Frontend\Coupon' ) ) {
				$coupons_to_apply = array();
				foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
					$product_id = ! empty( $cart_item['variation_id'] ) ? $cart_item['variation_id'] : $cart_item['product_id'];
					$quantity   = $cart_item['quantity'];
					$price      = $cart_item['data']->get_price();

					$result = \Discountify\Core\Frontend\Coupon::instance()->get_coupon_discount( $product_id, $quantity, $price );
					if ( ! empty( $result ) && ! empty( $result['rules_type'] ) ) {
						$allowed_coupons = array( 'bogo', 'discount', 'total_spend' );
						// Add the coupon if it's an allowed type
						if ( in_array( $result['rules_type'], $allowed_coupons ) ) {
							// Check bogo_discount_type only if it exists
							if ( ! isset( $result['bogo_discount_type'] ) || $result['bogo_discount_type'] !== 'buy_x_get_y' ) {
								$coupons_to_apply[] = $result['rules_type'];
							}
						}
					}
				}

				// Apply unique coupons
				if ( ! empty( $coupons_to_apply ) ) {
					$coupons_to_apply = array_unique( $coupons_to_apply );
					foreach ( $coupons_to_apply as $coupon_code ) {
						if ( ! in_array( $coupon_code, WC()->cart->applied_coupons ) ) {
							WC()->cart->applied_coupons[] = $coupon_code;
						}
					}
					// Save the applied coupons to session
					if ( WC()->session ) {
						WC()->session->set( 'applied_coupons', WC()->cart->applied_coupons );
					}
				}
			}

			WC()->cart->calculate_totals();
		}

		// Generate fragments directly to ensure they work even during AJAX calls
		$settings              = \Quicker\Utils\Helper::get_settings();
		$bump_product_type     = $settings['bump_product_type'] ?? '';
		$upsell_heading        = $settings['upsell_heading'] ?? '';
		$side_cart_style       = $settings['side_cart_style'] ?? '1';
		$cart_order_bump_style = $settings['cart_order_bump_style'] ?? '1';
		$show_coupon_form      = $settings['show_coupon_form'] ?? 'no';
		$up_sell_products      = $settings['up_sell_products'] ?? array();
		$enable_cart_upsell    = $settings['enable_cart_upsell'] ?? '';

		$template_path = \Quicker::template_dir() . 'side-cart/template-' . $side_cart_style . '.php';
		$cart_count    = WC()->cart->get_cart_contents_count();
		$cart_total    = WC()->cart->get_cart_total();
		$bump_section  = ( class_exists( 'QuickerPro' ) && $enable_cart_upsell == 'yes' ) ? 'quicker-up-sells' : '';
		$all_bump_items = \Quicker\Core\Frontend\Frontend::instance()->get_all_bump_items( $bump_product_type, $up_sell_products );

		ob_start();
		?>
		<div class="quicker-container">
			<div class="added-message" data-added_message="<?php esc_attr_e( 'Product has been added', 'quicker' ); ?>"></div>
			<span class="side-cart-icon" onClick="cart_open()">
				<?php echo \Quicker\Utils\Helper::get_cart_icon_svg( $settings['sc_icon_type'] ?? 'cart-1' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<div class="quicker-cart-count"><?php echo intval( $cart_count ); ?></div>
			</span>
			<?php
			if ( file_exists( $template_path ) ) {
				include $template_path;
			}
			?>
		</div>
		<?php

		$fragments['div.quicker-container']   = ob_get_clean();
		$fragments['div.quicker-cart-count']  = '<div class="quicker-cart-count">' . intval( $cart_count ) . '</div>';
		$fragments['span.quicker-cart-total'] = $cart_total;

		// Build notice HTML from existing notices (if any)
		$notice_html = '';
		if ( ! empty( $existing_notices ) ) {
			foreach ( $existing_notices as $type => $messages ) {
				foreach ( $messages as $notice_message ) {
					$notice_html .= '<div class="woocommerce-message" role="alert">' . wp_kses_post( $notice_message['notice'] ) . '</div>';
				}
			}
		}

		if ( ! empty( $notice_html ) ) {
			$fragments['div.woocommerce-notices-wrapper'] = '<div class="woocommerce-notices-wrapper">' . $notice_html . '</div>';
		}

		return wp_send_json_success(
			array(
				'message'   => $message,
				'fragments' => $fragments,
			)
		);
	}

	protected function verify_nonce() {
		$nonce = filter_input( INPUT_POST, 'nonce', FILTER_UNSAFE_RAW );
		if ( is_null( $nonce ) || ! wp_verify_nonce( $nonce, 'quicker_pro' ) ) {
			wp_send_json(
				array(
					'message' => __( 'Security check failed', 'quicker' ),
					'code'    => 401,
				)
			);
		}
	}

	/**
	 * Update mini cart qty
	 */
	public function quicker_update_mini_cart() {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX action uses wp_ajax hook which handles security
		$cart_key = isset( $_POST['cart_key'] ) ? sanitize_text_field( wp_unslash( $_POST['cart_key'] ) ) : '';
		if ( empty( $cart_key ) ) {
			$this->error_response();
		}

		if ( is_null( WC()->cart ) ) {
			$this->error_response( __( 'Cart not defined', 'quicker' ) );
		}

		$cart_items = WC()->cart->get_cart();
		if ( ! isset( $cart_items[ $cart_key ] ) ) {
			$this->error_response( __( 'Cart item not found', 'quicker' ) );
		}

		$cart_item = $cart_items[ $cart_key ];
		$product   = $cart_item['data'];

		add_filter( 'wp_redirect', '__return_false', 100 );

		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX action uses wp_ajax hook which handles security
		$quantity = isset( $_POST['quantity'] ) ? sanitize_text_field( wp_unslash( $_POST['quantity'] ) ) : '';
		$quantity = empty( $quantity ) ? 0 : floatval( $quantity );

		/** If 0 qty set */
		if ( 0 == $quantity || $quantity < 0 ) {
			// Remove any BOGO free products linked to this main product.
			$product_id          = (int) $cart_item['product_id'];
			$variation_id        = isset( $cart_item['variation_id'] ) ? (int) $cart_item['variation_id'] : 0;
			$bogo_keys_to_remove = array();
			foreach ( WC()->cart->get_cart() as $bogo_key => $bogo_item ) {
				if (
					( ! empty( $bogo_item['bogo_x_x_free'] ) || ! empty( $bogo_item['bogo_x_y_free'] ) )
					&& (
						( isset( $bogo_item['main_product'] ) && (int) $bogo_item['main_product'] === $product_id )
						|| ( (int) $bogo_item['product_id'] === $product_id && ( ! $variation_id || (int) ( $bogo_item['variation_id'] ?? 0 ) === $variation_id ) )
					)
				) {
					$bogo_keys_to_remove[] = $bogo_key;
				}
			}
			foreach ( $bogo_keys_to_remove as $bogo_key ) {
				WC()->cart->remove_cart_item( $bogo_key );
			}

			WC()->cart->remove_cart_item( $cart_key );
			/* translators: %s: product name */
			$message = sprintf( __( '%s has been removed from your cart.', 'quicker' ), $product->get_name() );
			$this->send_success( $message );
		}

		if ( ! $product->has_enough_stock( $quantity ) ) {
			/* translators: %1$s: stock quantity, %2$s: product name */
			$message = sprintf( __( 'Sorry, you can not add more then %1$s of "%2$s". Please edit your cart and try again.', 'quicker' ), $product->get_stock_quantity(), $product->get_name() );
			$this->error_response( $message );
		}

		// Min/Max order quantity check (scope-aware).
		$mmq_settings = \Quicker\Utils\Helper::get_settings();
		if ( ( $mmq_settings['mix_max_order_qty'] ?? '' ) === 'yes' ) {
			$mmq_max       = isset( $mmq_settings['max_order_quantity'] ) && $mmq_settings['max_order_quantity'] !== '' ? (int) $mmq_settings['max_order_quantity'] : 0;
			$mmq_min       = isset( $mmq_settings['min_order_quantity'] ) && $mmq_settings['min_order_quantity'] !== '' ? (int) $mmq_settings['min_order_quantity'] : 0;
			$new_total_qty = \Quicker\Core\Frontend\Frontend::get_scoped_cart_qty( $mmq_settings, $cart_key, (int) $quantity );

			if ( $mmq_max > 0 && $new_total_qty > $mmq_max ) {
				/* translators: %d: maximum allowed quantity */
				$this->error_response( sprintf( __( 'You cannot have more than %d items in your cart.', 'quicker' ), $mmq_max ) );
			}
			if ( $mmq_min > 0 && $new_total_qty < $mmq_min && $new_total_qty > 0 ) {
				/* translators: %d: minimum required quantity */
				$this->error_response( sprintf( __( 'Your cart must have at least %d items.', 'quicker' ), $mmq_min ) );
			}
		}

		$status = WC()->cart->set_quantity( $cart_key, $quantity );
		if ( $status ) {
			/* translators: %s: product name */
			$message = sprintf( __( '"%s" has been updated.', 'quicker' ), $product->get_name() );
			$this->send_success( $message );
		}

		$product_qty_in_cart      = WC()->cart->get_cart_item_quantities();
		$current_session_order_id = ( isset( WC()->session->order_awaiting_payment ) ? absint( WC()->session->order_awaiting_payment ) : 0 );

		$held_stock     = wc_get_held_stock_quantity( $product, $current_session_order_id );
		$required_stock = $product_qty_in_cart[ $product->get_stock_managed_by_id() ];
		if ( $product->get_stock_quantity() < ( $held_stock + $required_stock ) ) {
			/* translators: %1$s: product name, %2$s: available stock quantity */
			$message = sprintf( __( 'Sorry, we do not have enough "%1$s" in stock to fulfill your order (%2$s available). We apologize for any inconvenience caused.', 'quicker' ), $product->get_name(), wc_format_stock_quantity_for_display( $product->get_stock_quantity() - $held_stock, $product ) );
			$this->error_response( $message );
		}

		/* translators: %s: product name */
		$message = sprintf( __( 'Some error occurred in updating the "%s"', 'quicker' ), $product->get_name() );

		$this->error_response( $message );
	}


	/**
	 * Remove minicart item
	 */
	public function quicker_remove_cart_item() {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX action uses wp_ajax hook which handles security
		$cart_item_key = isset( $_POST['cart_item_key'] ) ? sanitize_text_field( wp_unslash( $_POST['cart_item_key'] ) ) : '';

		// Before removing, find any BOGO free products linked to this main product.
		$cart_contents = WC()->cart->get_cart();
		$cart_item     = isset( $cart_contents[ $cart_item_key ] ) ? $cart_contents[ $cart_item_key ] : null;
		if ( $cart_item && empty( $cart_item['bogo_x_x_free'] ) && empty( $cart_item['bogo_x_y_free'] ) ) {
			$product_id   = (int) $cart_item['product_id'];
			$variation_id = isset( $cart_item['variation_id'] ) ? (int) $cart_item['variation_id'] : 0;
			$bogo_keys_to_remove = array();
			foreach ( $cart_contents as $key => $item ) {
				if (
					( ! empty( $item['bogo_x_x_free'] ) || ! empty( $item['bogo_x_y_free'] ) )
					&& (
						( isset( $item['main_product'] ) && (int) $item['main_product'] === $product_id )
						|| ( (int) $item['product_id'] === $product_id && ( ! $variation_id || (int) ( $item['variation_id'] ?? 0 ) === $variation_id ) )
					)
				) {
					$bogo_keys_to_remove[] = $key;
				}
			}
			foreach ( $bogo_keys_to_remove as $bogo_key ) {
				WC()->cart->remove_cart_item( $bogo_key );
			}
		}

		if ( WC()->cart->remove_cart_item( $cart_item_key ) ) {
			$message = __( 'Item has been removed from your cart.', 'quicker' );
			$this->send_success( $message );
		} else {
			wp_send_json_error( 'Failed to remove item' );
		}
	}

	/**
	 * Apply coupon via AJAX
	 */
	public function quicker_apply_coupon() {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX action uses wp_ajax hook which handles security
		$coupon_code = isset( $_POST['coupon_code'] ) ? wc_format_coupon_code( sanitize_text_field( wp_unslash( $_POST['coupon_code'] ) ) ) : '';

		if ( empty( $coupon_code ) ) {
			wc_add_notice( __( 'Please enter a coupon code.', 'quicker' ), 'error' );
		} else {
			// Apply the coupon
			$result = WC()->cart->add_discount( $coupon_code );
		}

		// Get the notice that was added
		$notices = wc_get_notices();

		// Clear notices so they don't show again
		wc_clear_notices();

		// Force cart recalculation
		WC()->cart->calculate_totals();

		// Get the notice message to send back
		$notice_html = '';
		if ( ! empty( $notices ) ) {
			foreach ( $notices as $type => $messages ) {
				foreach ( $messages as $message ) {
					$notice_html .= '<div class="woocommerce-message" role="alert">' . wp_kses_post( $message['notice'] ) . '</div>';
				}
			}
		}

		// Generate fragments
		$this->send_success_with_notice( __( 'Coupon applied.', 'quicker' ), $notice_html );
	}

	/**
	 * Remove coupon via AJAX
	 */
	public function quicker_remove_coupon() {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing -- AJAX action uses wp_ajax hook which handles security
		$coupon = isset( $_POST['coupon'] ) ? wc_format_coupon_code( sanitize_text_field( wp_unslash( $_POST['coupon'] ) ) ) : '';

		if ( empty( $coupon ) ) {
			wc_add_notice( __( 'Please enter a coupon code.', 'quicker' ), 'error' );
		} else {
			WC()->cart->remove_coupon( $coupon );
			wc_add_notice( __( 'Coupon has been removed.', 'quicker' ) );
		}

		// Get the notice that was added
		$notices = wc_get_notices();

		// Clear notices so they don't show again
		wc_clear_notices();

		// Force cart recalculation
		WC()->cart->calculate_totals();

		// Get the notice message to send back
		$notice_html = '';
		if ( ! empty( $notices ) ) {
			foreach ( $notices as $type => $messages ) {
				foreach ( $messages as $message ) {
					$notice_html .= '<div class="woocommerce-message" role="alert">' . wp_kses_post( $message['notice'] ) . '</div>';
				}
			}
		}

		// Generate fragments
		$this->send_success_with_notice( __( 'Coupon removed.', 'quicker' ), $notice_html );
	}

	/**
	 * Send success response with notice
	 */
	public function send_success_with_notice( $message, $notice_html = '' ) {
		// Force session reload to ensure we have the latest cart data
		if ( WC()->session && WC()->cart ) {
			WC()->cart->get_cart_from_session();
		}

		// Recalculate cart totals to ensure coupons and discounts are properly calculated
		if ( WC()->cart ) {
			do_action( 'woocommerce_cart_loaded_from_session', WC()->cart );

			// Manually trigger Discountify coupon application for AJAX context
			if ( class_exists( 'Discountify\Core\Frontend\Coupon' ) ) {
				$coupons_to_apply = array();
				foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
					$product_id = ! empty( $cart_item['variation_id'] ) ? $cart_item['variation_id'] : $cart_item['product_id'];
					$quantity   = $cart_item['quantity'];
					$price      = $cart_item['data']->get_price();

					$result = \Discountify\Core\Frontend\Coupon::instance()->get_coupon_discount( $product_id, $quantity, $price );
					if ( ! empty( $result ) && ! empty( $result['rules_type'] ) ) {
						$allowed_coupons = array( 'bogo', 'discount', 'total_spend' );
						// Add the coupon if it's an allowed type
						if ( in_array( $result['rules_type'], $allowed_coupons ) ) {
							// Check bogo_discount_type only if it exists
							if ( ! isset( $result['bogo_discount_type'] ) || $result['bogo_discount_type'] !== 'buy_x_get_y' ) {
								$coupons_to_apply[] = $result['rules_type'];
							}
						}
					}
				}

				// Apply unique coupons
				if ( ! empty( $coupons_to_apply ) ) {
					$coupons_to_apply = array_unique( $coupons_to_apply );
					foreach ( $coupons_to_apply as $coupon_code ) {
						if ( ! in_array( $coupon_code, WC()->cart->applied_coupons ) ) {
							WC()->cart->applied_coupons[] = $coupon_code;
						}
					}
					// Save the applied coupons to session
					if ( WC()->session ) {
						WC()->session->set( 'applied_coupons', WC()->cart->applied_coupons );
					}
				}
			}

			WC()->cart->calculate_totals();
		}

		// Generate fragments directly to ensure they work even during AJAX calls
		$settings              = \Quicker\Utils\Helper::get_settings();
		$bump_product_type     = $settings['bump_product_type'] ?? '';
		$upsell_heading        = $settings['upsell_heading'] ?? '';
		$side_cart_style       = $settings['side_cart_style'] ?? '1';
		$cart_order_bump_style = $settings['cart_order_bump_style'] ?? '1';
		$show_coupon_form      = $settings['show_coupon_form'] ?? 'no';
		$up_sell_products      = $settings['up_sell_products'] ?? array();
		$enable_cart_upsell    = $settings['enable_cart_upsell'] ?? '';

		$template_path = \Quicker::template_dir() . 'side-cart/template-' . $side_cart_style . '.php';
		$cart_count    = WC()->cart->get_cart_contents_count();
		$cart_total    = WC()->cart->get_cart_total();
		$bump_section  = ( class_exists( 'QuickerPro' ) && $enable_cart_upsell == 'yes' ) ? 'quicker-up-sells' : '';
		$all_bump_items = \Quicker\Core\Frontend\Frontend::instance()->get_all_bump_items( $bump_product_type, $up_sell_products );

		ob_start();
		?>
		<div class="quicker-container">
			<div class="added-message" data-added_message="<?php esc_attr_e( 'Product has been added', 'quicker' ); ?>"></div>
			<span class="side-cart-icon" onClick="cart_open()">
				<?php echo \Quicker\Utils\Helper::get_cart_icon_svg( $settings['sc_icon_type'] ?? 'cart-1' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<div class="quicker-cart-count"><?php echo intval( $cart_count ); ?></div>
			</span>
			<?php
			if ( file_exists( $template_path ) ) {
				include $template_path;
			}
			?>
		</div>
		<?php

		$fragments['div.quicker-container']   = ob_get_clean();
		$fragments['div.quicker-cart-count']  = '<div class="quicker-cart-count">' . intval( $cart_count ) . '</div>';
		$fragments['span.quicker-cart-total'] = $cart_total;

		// Add the notice HTML if provided
		if ( ! empty( $notice_html ) ) {
			$fragments['div.woocommerce-notices-wrapper'] = '<div class="woocommerce-notices-wrapper">' . $notice_html . '</div>';
		}

		return wp_send_json_success(
			array(
				'message'   => $message,
				'notice'    => $notice_html,
				'fragments' => $fragments,
			)
		);
	}
}
