<?php
namespace BricksUltimate\WooCommerce;

if ( ! defined( 'ABSPATH' ) ) exit;

class WooOrderBumps {
	public static $instance = null;
	public $post_type = 'bu_order_bumps';

	public function __construct(){
		$this->bu_register_post_type();

		if( is_admin() ) {
			add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ), 30 );
			add_action( 'save_post', [ $this, 'save_order_bumps_post' ], PHP_INT_MAX - 10, 2 );
			add_action( 'admin_enqueue_scripts', array( $this, 'scripts' ) );
			add_filter( 'parent_file', [ $this, 'bu_parent_menu_active' ] );
			add_filter( "manage_{$this->post_type}_posts_columns", [ $this, 'bu_order_bumps_posts_columns' ] );
			add_action( "manage_{$this->post_type}_posts_custom_column", [ $this, 'bu_order_bumps_post_columns_data' ], 10, 2 );
			add_filter('get_sample_permalink_html', [$this, 'remove_sample_permalink_html'], 10, 5);
		}

		add_action( 'woocommerce_before_calculate_totals', [ $this, 'buob_calculate_totals' ], 100000 );
		add_filter( 'bricks/posts/query_vars', [ $this, 'filter_order_bumps_query' ], 100, 2 );
		add_filter( 'woocommerce_cart_item_product', [ $this, 'buob_cart_product_price' ], 10000, 2 );
		// removal logic
		add_action( 'wp_loaded', [ $this, 'buob_apply_removal_logic' ] );

		add_action( 'init', [$this, 'bu_register_element' ], 12 );
	}

	public function get_cart_item_subtotal( \WC_Product $product, int $quantity ) {
		$price = $product->get_price();

		if ( $product->is_taxable() ) {
			if ( WC()->cart->display_prices_including_tax() ) {
				$row_price = wc_get_price_including_tax( $product, array( 'qty' => $quantity ) );
			} else {
				$row_price = wc_get_price_excluding_tax( $product, array( 'qty' => $quantity ) );
			}
		} else {
			$row_price = (float) $price * (float) $quantity;
		}

		return $row_price;
	}

	function remove_sample_permalink_html($html, $post_id, $new_title, $new_slug, $post) {
		$screen  = get_current_screen();
		if ( ! empty( $screen->id ) && in_array( $screen->id, array( $this->post_type ), true ) ) {
			return;
		}

		return $html;
	}

	protected function productInCart( array $cart_item, int $product_id ) {
		if ( $cart_item['product_id'] === $product_id ) {
			return true;
		}

		if ( empty( $cart_item['variation_id'] ) ) {
			return false;
		}

		if ( $cart_item['variation_id'] === $product_id ) {
			return true;
		}

		return wp_get_post_parent_id( $cart_item['variation_id'] ) === $product_id;
	}

	public function bu_order_bumps_posts_columns( $columns ) {
		$date = array_pop( $columns );

		$columns['product_image'] 	= __('Image', 'bricksultimate');
		$columns['offer_product'] 	= __('Offer Product', 'bricksultimate');
		$columns['stock'] 			= __('Stock', 'bricksultimate');
		$columns['discount_amount'] = __('Discount', 'bricksultimate');
		$columns['offer_price'] 	= __('Price', 'bricksultimate');
		$columns['date'] 			= $date;

		return $columns;
	}

	public function bu_order_bumps_post_columns_data( $column, $post_id ) {
		$product_id = get_post_meta( $post_id, '_buob_offer_product', true );
		if( $product_id ) {
			$product = wc_get_product( $product_id );
		}

		if( $product === false )
			return;

		if ( 'product_image' === $column ) {
			echo '<a href="' . esc_url( get_edit_post_link( $product->get_id() ) ) . '">' . $product->get_image( 'thumbnail', [ 'style' => 'width: 40px; height: auto'] ) . '</a>';
		}

		if ( 'offer_product' === $column ) {
			printf( "<a href='%s'>%s<a/>", esc_url( get_edit_post_link( $product->get_id() ) ), $product->get_title() );
		}

		if( 'stock' == $column ) {
			if ( $product->is_on_backorder() ) {
				$stock_html = '<mark class="onbackorder">' . __( 'On backorder', 'woocommerce' ) . '</mark>';
			} elseif ( $product->is_in_stock() ) {
				$stock_html = '<mark class="instock">' . __( 'In stock', 'woocommerce' ) . '</mark>';
			} else {
				$stock_html = '<mark class="outofstock">' . __( 'Out of stock', 'woocommerce' ) . '</mark>';
			}

			if ( $product->managing_stock() ) {
				$stock_html .= ' (' . wc_stock_amount( $product->get_stock_quantity() ) . ')';
			}

			echo wp_kses_post( apply_filters( 'woocommerce_admin_stock_html', $stock_html, $product ) );
		}

		if( 'discount_amount' == $column ) {
			$discount_type = get_post_meta( $post_id, '_buob_discount_type', true ) ?? 'percent';
			$discount_amount = get_post_meta( $post_id, '_buob_offer_discount', true );

			if( $discount_amount && $discount_type == 'percent' ) {
				echo $discount_amount . '%';
			} elseif( $discount_amount && $discount_type == 'amount' ) {
				echo wc_price( $discount_amount );
			} else {
				echo 'N/A';
			}
		}

		if( 'offer_price' == $column ) {
			echo $this->get_offer_product_price( $product, $post_id );
		}
	}

	public function bu_register_post_type() {
		register_post_type(
			$this->post_type,
			array(
				'labels'             => array(
					'name'               => esc_html__( 'Order Bumps', 'bricksultimate' ),
					'singular_name'      => esc_html__( 'Order Bump', 'bricksultimate' ),
					'add_new'            => esc_html__( 'Add New', 'bricksultimate' ),
					'add_new_item'       => esc_html__( 'Add New Order Bump', 'bricksultimate' ),
					'edit_item'          => esc_html__( 'Edit Order Bump', 'bricksultimate' ),
					'new_item'           => esc_html__( 'New Order Bump', 'bricksultimate' ),
					'view_item'          => esc_html__( 'View Order Bump', 'bricksultimate' ),
					'search_items'       => esc_html__( 'Find Order Bump', 'bricksultimate' ),
					'not_found'          => esc_html__( 'No order bumps were found.', 'bricksultimate' ),
					'not_found_in_trash' => esc_html__( 'Not found in trash', 'bricksultimate' ),
					'menu_name'          => esc_html__( 'Order Bumps', 'bricksultimate' ),
					'featured_image'     => esc_html__( 'Product image', 'woocommerce' ),
				),
				'public'             => true,
				'publicly_queryable' => true,
				'show_ui'            => true,
				'show_in_menu'       => false,
				'show_in_rest'       => true,
				'query_var'          => false,
				'rewrite'            => false,
				'has_archive'        => false,
				'hierarchical'       => false,
				'supports'           => array( 'title', 'thumbnail' ),
				'capability_type' 	 => 'product',
				'exclude_from_search' => true,
			)
		);
	}

	public function bu_register_element() {
		$dir = str_replace( basename( __DIR__ ), '', __DIR__ );
		$file = $dir . 'Elements/WooAddOrderBumps.php';
				
		if( ! file_exists( $file ) )
			return;

		\Bricks\Elements::register_element( $file );
	}

	public function filter_order_bumps_query( $query_vars, $settings ) {
		if( ! empty( $query_vars['post_type'] ) && in_array( $this->post_type, $query_vars['post_type'] ) && ! bricks_is_builder() ) {
			//* Apply the conditions
			return $this->apply_conditions( $query_vars );
		}

		return $query_vars;
	}

	public function buob_apply_removal_logic() {
		if( is_null( WC()->cart ) )
			return;

		foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
			if ( empty( $cart_item['_buob_bump_id'] ) ) {
				continue;
			}

			$action 		= get_post_meta( $cart_item['_buob_bump_id'], '_buob_remove_logic', true ) ?? 'leaveincart';
			$display_for 	= get_post_meta( $cart_item['_buob_bump_id'], '_buob_display_condition', true );

			if ( $action == 'removefromcart' && $this->match_conditions( $cart_item['_buob_bump_id'], $display_for ) === false ) {
				\WC()->cart->remove_cart_item( $cart_item_key );
			}
		}

		\WC()->cart->set_session();
	}

	public function match_conditions( $bump_id, $switchCase ) {
		$match = false;

		switch( $switchCase ) {
			case "sprds" :
				$operator = get_post_meta( $bump_id, '_buob_spprdcat_operator', true ) ?? 'all';
				$specific_products = get_post_meta( $bump_id,'_buob_dc_specific_products', true );
				$cart_product_ids = array_map(
					function ( $cart_item ) use ( $specific_products ) {
						foreach ( $specific_products as $product_id ) {
							if ( $this->productInCart( $cart_item, $product_id ) ) {
								return $product_id;
							}
						}

						return false;
					},
					WC()->cart->get_cart_contents()
				);

				$specific_products = array_values( $specific_products );
				$cart_product_ids = array_values( $cart_product_ids );

				switch ( $operator ) {
					case 'all':
						if( count( array_diff( $specific_products, $cart_product_ids ) ) === 0 ) {
							$match = true;
						}
						break;
					case 'one':
						if( count( array_intersect( $specific_products, $cart_product_ids ) ) > 0 )
							$match = true;
						break;
					case 'none':
						if( count( array_intersect( $specific_products, $cart_product_ids ) ) === 0 )
							$match = true;
						break;
					default:
						break;
				}
				break;
			case "spcats" :
				$operator = get_post_meta( $bump_id, '_buob_spprdcat_operator', true ) ?? 'all';
				$category_slugs = get_post_meta( $bump_id,'_buob_dc_specific_cats', true );

				$cart_category_slugs = array();

				foreach ( WC()->cart->get_cart_contents() as $cart_item ) {

					$bump = $cart_item['_buob_bump_id'] ?? false;

					if ( $bump ) {
						continue;
					}

					$cart_item_terms = wp_get_post_terms( $cart_item['product_id'], 'product_cat' );

					$parent_ids = array_map(function($term) {
						return $term->parent;
					}, $cart_item_terms);
					
					$cart_item_terms = array_filter($cart_item_terms, function($term) use ($parent_ids) {
						return !in_array($term->term_id, $parent_ids);
					});

					foreach ( $cart_item_terms as $cart_item_term ) {
						$cart_category_slugs[] = $cart_item_term->slug;
					}
				}

				$cart_category_slugs = array_unique( $cart_category_slugs );

				switch ( $operator ) {
					case 'all':
						if( count( array_diff( $category_slugs, $cart_category_slugs ) ) === 0 ) {
							$match = true;
						}
						break;
					case 'one':
						if( count( array_intersect( $category_slugs, $cart_category_slugs ) ) > 0 )
							$match = true;
						break;
					case 'none':
						if( count( array_intersect( $category_slugs, $cart_category_slugs ) ) === 0 )
							$match = true;
						break;
					default:
						break;
				}

				break;
			case "cartqty":
				$compare = get_post_meta( $bump_id, '_buob_compare', true ) ?? 'equal';
				$user_value = get_post_meta( $bump_id,'_buob_user_value', true ) ?? 0;

				$cart_quantity = array_sum( WC()->cart->get_cart_item_quantities() );
				if( $this->compareValues($cart_quantity, $compare, $user_value) === true ) {
					$match = true;
				}
				break;
			case "csubttl":
				$subtotal = 0;
				$compare = get_post_meta( $bump_id, '_buob_compare', true ) ?? 'equal';
				$user_value = get_post_meta( $bump_id,'_buob_user_value', true ) ?? 0;

				foreach ( WC()->cart->get_cart() as $cart_item ) {
					$subtotal += $this->get_cart_item_subtotal( $cart_item['data'], $cart_item['quantity'] );
				}

				if( $this->compareValues($subtotal, $compare, $user_value) === true ) {
					$match = true;
				}
				break;
			case "all":
			default:
				$match = true;
			 	break;
		}

		return $match;
	}

	//* Returning the bumps ids
	public function apply_conditions( array $query_vars ) {
		global $wpdb;

		$query_vars['post__in'] = [ 0 ];
		
		/*if( is_singular( 'product' ) ) {
			$bump_ids = $wpdb->get_col( 
				"SELECT ID FROM `{$wpdb->prefix}posts` AS P 
				INNER JOIN `{$wpdb->prefix}postmeta` AS PM ON(P.ID = PM.post_ID) 
				WHERE 1=1 AND P.post_status='publish' AND P.post_type='{$this->post_type}' AND PM.meta_key='_buob_on_single_page' 
				LIMIT 0, 999" 
			);
		} else {*/
			$bump_ids = $wpdb->get_col( "SELECT ID FROM `{$wpdb->prefix}posts` WHERE 1=1 AND post_status='publish' AND post_type='{$this->post_type}' LIMIT 0, 999" );

			$in_cart = array();
			if ( ! is_null( WC()->cart ) && ! WC()->cart->is_empty() ) {
				foreach( WC()->cart->get_cart() as $values ) {
					if ( $values['quantity'] > 0 ) {
						$in_cart[] = $values['product_id'];

						// Add variations to the in cart array.
						if ( $values['data']->is_type( 'variation' ) ) {
							$in_cart[] = $values['variation_id'];
						}
					}
				}
			}

			if( isset( $query_vars['meta_query'] ) ) {
				$query_vars['meta_query'][] = [
					'key' 		=> '_buob_offer_product',
					'value' 	=> $in_cart,
					'compare' 	=> 'NOT IN'
				];
			} else {
				$query_vars['meta_query'] = [
					'relation' 	=> 'AND',
					[
						'key' 		=> '_buob_offer_product',
						'value' 	=> $in_cart,
						'compare' 	=> 'NOT IN'
					]
				];
			}
		//}

		foreach( $bump_ids as $bump_id ) {
			$display_for = get_post_meta( $bump_id, '_buob_display_condition', true );
			$product_id = get_post_meta( $bump_id, '_buob_offer_product', true );

			switch( $display_for ) {
				/*case 'single':
					$single_product_id = get_post_meta( $bump_id, '_buob_on_single_page', true );
					if( is_singular( 'product' ) && ! empty( $single_product_id ) && get_the_ID() == $single_product_id ) {
						unset( $query_vars['post__in'] );

						$query_vars['meta_query'][] = [
							'key' 		=> '_buob_on_single_page',
							'value' 	=> $single_product_id,
							'compare' 	=> '='
						];
					}
					break;*/

				case "sprds" :
					$operator = get_post_meta( $bump_id, '_buob_spprdcat_operator', true ) ?? 'all';
					$specific_products = get_post_meta( $bump_id,'_buob_dc_specific_products', true );
					$cart_product_ids = array_map(
						function ( $cart_item ) use ( $specific_products ) {
							foreach ( $specific_products as $product_id ) {
								if ( $this->productInCart( $cart_item, $product_id ) ) {
									return $product_id;
								}
							}

							return false;
						},
						WC()->cart->get_cart_contents()
					);

					$specific_products = array_values( $specific_products );
					$cart_product_ids = array_values( $cart_product_ids );

					switch ( $operator ) {
						case 'all':
							if( count( array_diff( $specific_products, $cart_product_ids ) ) === 0 ) {
								$query_vars['post__in'][] = $bump_id;
							}
							break;
						case 'one':
							if( count( array_intersect( $specific_products, $cart_product_ids ) ) > 0 )
								$query_vars['post__in'][] = $bump_id;
							break;
						case 'none':
							if( count( array_intersect( $specific_products, $cart_product_ids ) ) === 0 )
								$query_vars['post__in'][] = $bump_id;
							break;
						default:
							break;
					}
					break;
				case "spcats" :
					$operator = get_post_meta( $bump_id, '_buob_spprdcat_operator', true ) ?? 'all';
					$category_slugs = get_post_meta( $bump_id,'_buob_dc_specific_cats', true );

					$cart_category_slugs = array();

					foreach ( WC()->cart->get_cart_contents() as $cart_item ) {
						$cart_item_terms = wp_get_post_terms( $cart_item['product_id'], 'product_cat' );

						foreach ( $cart_item_terms as $cart_item_term ) {
							$cart_category_slugs[] = $cart_item_term->slug;
						}
					}

					$cart_category_slugs = array_unique( $cart_category_slugs );

					switch ( $operator ) {
						case 'all':
							if( count( array_diff( $category_slugs, $cart_category_slugs ) ) === 0 ) {
								$query_vars['post__in'][] = $bump_id;
							}
							break;
						case 'one':
							if( count( array_intersect( $category_slugs, $cart_category_slugs ) ) > 0 )
								$query_vars['post__in'][] = $bump_id;
							break;
						case 'none':
							if( count( array_intersect( $category_slugs, $cart_category_slugs ) ) === 0 )
								$query_vars['post__in'][] = $bump_id;
							break;
						default:
							break;
					}

					break;
				case "cartqty":
					$compare = get_post_meta( $bump_id, '_buob_compare', true ) ?? 'equal';
					$user_value = get_post_meta( $bump_id,'_buob_user_value', true ) ?? 0;

					$cart_quantity = array_sum( WC()->cart->get_cart_item_quantities() );
					if( $this->compareValues($cart_quantity, $compare, $user_value) === true ) {
						$query_vars['post__in'][] = $bump_id;
					}
					break;
				case "csubttl":
					$subtotal = 0;
					$compare = get_post_meta( $bump_id, '_buob_compare', true ) ?? 'equal';
					$user_value = get_post_meta( $bump_id,'_buob_user_value', true ) ?? 0;

					foreach ( WC()->cart->get_cart() as $cart_item ) {
						$subtotal += $this->get_cart_item_subtotal( $cart_item['data'], $cart_item['quantity'] );
					}

					if( $this->compareValues($subtotal, $compare, $user_value) === true ) {
						$query_vars['post__in'][] = $bump_id;
					}
					break;
				case 'ccoupon':
					$coupons = get_post_meta( $bump_id,'_buob_cart_coupons', true ) ?? '';
					if( ! is_null( WC()->cart ) && ! empty( $coupons ) ) {
						$applied_coupons = WC()->cart->get_applied_coupons();
						$applied_coupons = array_map( 'strtolower', $applied_coupons );

						$coupons = array_filter( array_map( 'trim', explode( ',', $coupons ) ) );
						$coupons = array_map( 'strtolower', $coupons );

						if ( ! empty( $coupons ) && (bool) array_intersect( $coupons, $applied_coupons ) ) {
							$query_vars['post__in'][] = $bump_id;
						}
					}
					break;
				case "all":
				default:
					$query_vars['post__in'][] = $bump_id;
				 	break;
			}
		}

		return $query_vars;
	}

	protected function compareValues( $value, $compare, $user_value ) {
		$value  = floatval( $value );
		$user_value = floatval( $user_value );

		switch ( $compare ) {
			case 'equal':
				return $value === $user_value;
			case 'notequal':
				return $value !== $user_value;
			case 'greater':
				return $value > $user_value;
			case 'lessthan':
				return $value < $user_value;
			case 'gequal':
				return $value >= $user_value;
			case 'lequal':
				return $value <= $user_value;
			case 'contains':
				return strpos( $value, $user_value ) !== false;
			case 'notcontains':
				return strpos( $value, $user_value ) === false;
			default:
				return false;
		}
	}

	public function save_order_bumps_post( $post_id, $post ) {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return $post_id;
		}

		// Check if the nonce is set
	    if ( ! isset( $_POST['bu_order_bumps_meta_nonce'] ) ) {
	        return $post_id; // No nonce, no save
	    }

	    // Verify the nonce
	    if ( ! wp_verify_nonce( $_POST['bu_order_bumps_meta_nonce'], 'bu_order_bumps_save_data' ) ) {
	        return $post_id; // Nonce verification failed
	    }

		// Revision
		if ( wp_is_post_revision( $post_id ) ) {
			return $post_id;
		}

		// Autosave
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return $post_id;
		}

		if ( $this->post_type !== $post->post_type ) {
			return $post_id;
		}

		$display_condition = $_POST['buob_display_condition'] ?? "all";
		$has_quantity_field = isset( $_POST['buob_has_quantity_field'] ) ? "yes" : "no";

		update_post_meta( $post_id, '_buob_offer_product', $_POST['buob_offer_product'] ?? 0 );
		update_post_meta( $post_id, '_buob_discount_type', $_POST['_buob_discount_type'] ?? 'percent' );
		update_post_meta( $post_id, '_buob_offer_product_quantity', $_POST['buob_offer_product_quantity'] ?? 1 );
		update_post_meta( $post_id, '_buob_has_quantity_field', $has_quantity_field );
		update_post_meta( $post_id, '_buob_offer_discount', $_POST['_buob_offer_discount'] ?? 0 );
		update_post_meta( $post_id, '_buob_display_condition', $display_condition );
		update_post_meta( $post_id, '_buob_enable_remove_button', $_POST['buob_enable_remove_button'] ?? "no" );

		//delete_post_meta( $post_id, '_buob_on_single_page' );
		delete_post_meta( $post_id, '_buob_dc_specific_products' );
		delete_post_meta( $post_id, '_buob_spprdcat_operator' );
		delete_post_meta( $post_id, '_buob_dc_specific_cats' );
		delete_post_meta( $post_id, '_buob_user_value' );
		delete_post_meta( $post_id, '_buob_compare' );
		delete_post_meta( $post_id, '_buob_cart_coupons' );

		/*if( $display_condition === 'single' && isset( $_POST['buob_single_page'] ) ) {
			update_post_meta( $post_id, '_buob_on_single_page', $_POST['buob_single_page'] );
		}*/

		if( $display_condition === 'sprds' ) {
			update_post_meta( $post_id, '_buob_dc_specific_products', $_POST['buob_specific_products'] ?? 0 );
			update_post_meta( $post_id, '_buob_spprdcat_operator', $_POST['buob_spprdcat_operator'] ?? 'all' );
		}

		if( $display_condition === 'spcats' ) {
			update_post_meta( $post_id, '_buob_dc_specific_cats', $_POST['buob_specific_categories'] ?? 0 );
			update_post_meta( $post_id, '_buob_spprdcat_operator', $_POST['buob_spprdcat_operator'] ?? 'all' );
		}

		if( $display_condition === 'cartqty' || $display_condition === 'csubttl' ) {
			update_post_meta( $post_id, '_buob_user_value', $_POST['buob_user_value'] ?? 0 );
			update_post_meta( $post_id, '_buob_compare', $_POST['buob_compare'] ?? 'equal' );
		}

		if( $display_condition === 'ccoupon' && isset( $_POST['buob_cart_coupons'] ) ) {
			update_post_meta( $post_id, '_buob_cart_coupons', $_POST['buob_cart_coupons'] ?? '' );
		}

		if( isset( $_POST['buob_remove_logic'] ) ) {
			update_post_meta( $post_id, '_buob_remove_logic', $_POST['buob_remove_logic'] );
		}

		if( isset( $_POST['_buob_offer_description'] ) ) {
			update_post_meta( $post_id, '_buob_offer_description', $_POST['_buob_offer_description'] );
		}

		return $post_id;
	}

	public function get_offer_product_price( $product, int $bump_id = 0 ) {
		if ( $product->is_type( 'variable' ) ) {
			// Get min and max prices of variable product variations
			$prices = $product->get_variation_prices( true );

			// Get first and last key
			$min_id = key( $prices['price'] );
			$max_id = key( array_slice( $prices['price'], - 1, 1, true ) );

			$min_price = $this->get_price( $product, $bump_id, $min_id );
			$max_price = $this->get_price( $product, $bump_id, $max_id );

			if ( $min_price !== $max_price ) {
				return wc_format_price_range( $min_price, $max_price );
			}
		}

		$price = wc_get_price_to_display( $product, array(
			'price'           => $product->get_regular_price(),
			'display_context' => 'cart'
		) );

		$sale_price = wc_get_price_to_display( $product, array(
			'price'           => $this->get_price( $product, $bump_id ),
			'display_context' => 'cart'
		) );

		$sale_price_formatted = wc_price( $sale_price );

		if ( 0.00 === $price ) {
			return '<span class="woocommerce-Price-amount amount">' . __( 'Free!', 'woocommerce' ) . '</span>';
		} elseif ( $price > $sale_price ) {
			return wc_format_sale_price( $price, $sale_price );
		}

		return $sale_price_formatted;
	}

	public function get_price( $product, int $bump_id = 0,  int $variation_id = 0 ): float {
		$discount_type = get_post_meta( $bump_id, '_buob_discount_type', true ) ?? 'percent';
		$discount      = get_post_meta( $bump_id, '_buob_offer_discount', true ) ?? 0;

		if ( $product->is_type( 'variable' ) && $variation_id > 0 ) {
			// Get product variation
			$product = wc_get_product( $variation_id );
		}

		if( ! $product->is_type( 'variable' ) && ! $product->is_type('grouped') ) {
			if( $product->is_on_sale() )
				$price = $product->get_sale_price();
			else
				$price = $product->get_regular_price();
		} else {
			$price = $product->get_price( 'view' );
		}

		if ( 'percent' === $discount_type && $discount > 0 ) {
			$discount_value = $price * ( $discount / 100 );
		} else {
			$discount_value = $discount;
		}

		return apply_filters( 'bu_order_bump_get_price', ( (float) $price - (float) $discount_value ), $bump_id );
	}

	/**
	 * Add Order Bumps Meta boxes.
	 */
	public function add_meta_boxes() {
		// Products.
		add_meta_box( 'bu-order-bumps-data', __( 'Order Bumps Data', 'bricksultimate' ), [ $this, 'output' ], $this->post_type, 'normal', 'high' );
	}

	/**
	 * Order Bumps meta boxes output.
	 */
	public function output( $post ) {
		global $thepostid;
		$thepostid = $post->ID;
		wp_nonce_field( 'bu_order_bumps_save_data', 'bu_order_bumps_meta_nonce' );

		include_once __DIR__ . '../../Admin/views/html-order-bumps-data.php';
	}

	public function scripts() {
		$screen  = get_current_screen();
		if ( in_array( $screen->id, array( $this->post_type ), true ) ) {
			wp_enqueue_style( 'woocommerce_admin_styles' );

			wp_enqueue_script( 'woocommerce_admin' );
			//wp_enqueue_script( 'wc-enhanced-select' );

			wp_register_script( 'wc-admin-product-meta-boxes', WC()->plugin_url() . '/assets/js/admin/meta-boxes-product.min.js', array( 'wc-admin-meta-boxes', 'media-models' ), '9.5.3' );
			wp_enqueue_script( 'wc-admin-product-meta-boxes' );

			wp_enqueue_script( 'bu-order-bumps', \BricksUltimate\Helpers::get_asset_url('js') . 'buorderbumps.min.js', [], filemtime(\BricksUltimate\Helpers::get_asset_path('js') . 'buorderbumps.min.js' ),true);

			$params = array(
				'urls' => array(
					'add_product'     => null,
					'import_products' => null,
					'export_products' => null,
				),
			);
			wp_localize_script( 'woocommerce_admin', 'woocommerce_admin', $params );

			wp_localize_script( 'wc-admin-meta-boxes', 'woocommerce_admin_meta_boxes', [] );
		}
	}

	public function buob_calculate_totals( $cart ) {
		foreach ( $cart->get_cart_contents() as $cart_item ) {
			$bump = $cart_item['_buob_bump_id'] ?? false;

			if ( ! $bump ) {
				continue;
			}

			$cart_product = $cart_item['data'] ?? false;

			if ( ! ( $cart_product instanceof \WC_Product ) ) {
				continue;
			}

			$action 		= get_post_meta( $bump, '_buob_remove_logic', true ) ?? 'leaveincart';
			$display_for 	= get_post_meta( $bump, '_buob_display_condition', true );

			if ( $action == 'leaveincart' && $this->match_conditions( $bump, $display_for ) === false ) {
				continue;
			}

			$offer_price = $this->get_price(
				$cart_product,
				$bump,
				$cart_item['variation_id'] ?? 0
			);

			$cart_product->set_price( $offer_price );
		}

		\WC()->cart->set_session();
	}

	public function buob_cart_product_price( $product, $cart_item ) {
		$bump = $cart_item['_buob_bump_id'] ?? false;

		if ( ! $bump ) {
			return $product;
		}

		// Get cart item variation id
		$variation_id = $cart_item['variation_id'] ?? 0;

		$action 		= get_post_meta( $bump, '_buob_remove_logic', true ) ?? 'leaveincart';
		$display_for 	= get_post_meta( $bump, '_buob_display_condition', true );

		if ( $action == 'leaveincart' && $this->match_conditions( $bump, $display_for ) === false ) {
			return $product;
		} else {
			$product->set_price(
				$this->get_price(
					$product,
					$bump,
					$variation_id
				)
			);
		}

		return $product;
	}

	/**
	 * Active the parent menu.
	 */
	public function bu_parent_menu_active( $parent_file ) {
		global $plugin_page, $post_type;

		if ( $this->post_type === $post_type ) {
			$plugin_page = 'bricks';
		}

		return $parent_file;
	}

	public static function get_instance() {
        if ( null == self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}