_array = explode("-", $price);
$price = $price_array[0];
}
$discounted_price_for_set += $price;
}
$discounted_price = ($original_price - ($discounted_price_for_set + $other_discounts));
}
if ($discounted_price <= 0) {
$discounted_price = 0;
}
$original_price_with_tax_call = $discounted_price_with_tax_call = 0;
if(!empty($original_price)){
$original_price_with_tax_call = $calculator->mayHaveTax($product_obj, $original_price);
}
if(!empty($discounted_price)){
$discounted_price_with_tax_call = $calculator->mayHaveTax($product_obj, $discounted_price);
}
if (!empty($discounted_price)) {
$calculate_product_price[] = $discounted_price * $last_applied;
}
$price_suffix = Woocommerce::getProductPriceSuffix($product_obj, $discounted_price);
$price_html .= '' . self::$woocommerce_helper->formatPrice($original_price_with_tax_call) . ' ' . self::$woocommerce_helper->formatPrice($discounted_price_with_tax_call) .$price_suffix. ' x ' . $last_applied . '
';
//remove calculated set
$min_applied_range_keys = array_keys($partially_qualified_sets, $min_applied_quantity);
foreach ($min_applied_range_keys as $key) {
unset($partially_qualified_sets[$key]);
}
}
}
$original_price_with_tax_call = $discounted_price_with_tax_call = 0;
//get original price quantity
if ($discount_operator === 'total_qty_in_cart') {
$total_quantity = $current_product_quantity;
}
$not_applied = (int)$total_quantity - (int)$total_applied;
//calculate original price quantities discount.
if (!empty($other_discounts)) {
$calculate_product_price_total = $original_price * $not_applied;
$discounted_price = $calculate_product_price_total - $other_discounts;
//$discounted_price = $calculator->mayHaveTax($product_obj, $discounted_price);
if ($discounted_price < 0) {
$discounted_price = 0;
}
$calculate_product_price[] = $discounted_price;
if(!empty($original_price)){
$original_price_with_tax_call = $calculator->mayHaveTax($product_obj, $original_price);
}
if(!empty($discounted_price)){
$discounted_price_with_tax_call = $calculator->mayHaveTax($product_obj, $discounted_price);
}
$price_suffix = Woocommerce::getProductPriceSuffix($product_obj, $discounted_price_with_tax_call);
$price_html .= '' . self::$woocommerce_helper->formatPrice($original_price_with_tax_call) . ' ' . self::$woocommerce_helper->formatPrice($discounted_price_with_tax_call) .$price_suffix. ' x ' . $not_applied . '';
} else {
if(!empty($original_price)){
$original_price_with_tax_call = $calculator->mayHaveTax($product_obj, $original_price);
}
$price_suffix = Woocommerce::getProductPriceSuffix($product_obj, $original_price_with_tax_call);
$calculate_product_price[] = $original_price * $not_applied;
$price_html .= '' . self::$woocommerce_helper->formatPrice($original_price_with_tax_call) .$price_suffix. ' x ' . $not_applied . '';
}
if ($return_html) {
return apply_filters('advanced_woo_discount_rules_strikeout_for_set_discount_price_html', $price_html, $original_price, $discounted_price, $total_discount, $other_discounts, $not_applied);
} else {
$total_product_price = array_sum($calculate_product_price);
$single_product_price = $total_product_price;
if($total_quantity != 0){
$single_product_price = $total_product_price / $total_quantity;
}
return $single_product_price;
}
}
return false;
}
/**
* Apply cart discount fees
* @param $cart
*/
function applyCartDiscount($cart)
{
$discount_apply_type = self::$config->getConfig('apply_cart_discount_as', 'coupon');
if($discount_apply_type == "fee"){
$combine_all_discounts = self::$config->getConfig('combine_all_cart_discounts', 0);
$total_combined_discounts = 0;
$apply_as_cart_fee_details = DiscountCalculator::$price_discount_apply_as_cart_discount;
$flat_in_subtotal = array();
$discount_coupons = array();
if(!empty($apply_as_cart_fee_details)){
foreach ($apply_as_cart_fee_details as $rule_id => $product_id){
$discount_value = 0;
foreach ($product_id as $detail) {
if($detail['discount_type'] == 'wdr_cart_discount' && $detail['apply_type'] == 'flat_in_subtotal'){
if(!isset($flat_in_subtotal[$rule_id])){
$flat_in_subtotal[$rule_id]['value'] = $detail['discounted_price'];
$flat_in_subtotal[$rule_id]['label'] = $detail['discount_label'];
if (!isset($discount_coupons[$rule_id])) {
$discount_coupons[$rule_id] = array('discount_label' => $detail['discount_label'], 'discount_value' => $detail['discounted_price']);
}
}
}else{
$discount_value += $detail['discounted_price'];
$label = (isset($detail['discount_label']) && !empty($detail['discount_label'])) ? $detail['discount_label'] : $detail['rule_name'];
if (!isset($discount_coupons[$rule_id])) {
$discount_coupons[$rule_id] = array('discount_label' => $label, 'discount_value' => $detail['discounted_price']);
} else {
$discount_coupons[$rule_id]['discount_value'] += $detail['discounted_price'];
}
}
}
if ($discount_value > 0) {
if (empty($combine_all_discounts)) {
$discount_value = -1 * $discount_value;
$fee_name = apply_filters('advanced_woo_discount_rules_additional_fee_label', $label, $cart);
$fee_amount = apply_filters('advanced_woo_discount_rules_additional_fee_amount', $discount_value, $cart);
self::setCartCouponDiscountDetails($fee_name, $label, -1 * $fee_amount, array($rule_id), $discount_coupons);
Woocommerce::addCartFee($cart, $fee_name, $fee_amount);
}else{
$total_combined_discounts += $discount_value;
}
self::$calculated_cart_discount['discount'][] = array('price' => $discount_value, 'label' => $label);
}
}
}
if (!empty($flat_in_subtotal)) {
foreach ($flat_in_subtotal as $rule_id => $discount){
if(empty($combine_all_discounts)){
$discount_value = -1 * $discount['value'];
$label = $discount['label'];
$fee_name = apply_filters('advanced_woo_discount_rules_additional_fee_label', $label, $cart);
$fee_amount = apply_filters('advanced_woo_discount_rules_additional_fee_amount', $discount_value, $cart);
self::setCartCouponDiscountDetails($fee_name, $label, -1 * $fee_amount, array($rule_id), $discount_coupons);
Woocommerce::addCartFee($cart, $fee_name, $fee_amount);
}else{
$total_combined_discounts += $discount['value'];
}
}
}
//Combine all discounts and add as single discounts
if (!empty($total_combined_discounts) && !empty($combine_all_discounts)) {
$label = self::$config->getConfig('discount_label_for_combined_discounts', __('Cart discount', 'woo-discount-rules'));
$label = Helper::getCleanHtml($label);
if ($discount_apply_type == 'fee') {
$total_combined_discounts = -1 * $total_combined_discounts;
$fee_name = apply_filters('advanced_woo_discount_rules_additional_fee_label', $label, $cart);
$fee_amount = apply_filters('advanced_woo_discount_rules_additional_fee_amount', $total_combined_discounts, $cart);
self::setCartCouponDiscountDetails($fee_name, $label, -1 * $fee_amount, array_keys($discount_coupons), $discount_coupons);
Woocommerce::addCartFee($cart, $fee_name, $fee_amount);
}
}
DiscountCalculator::$price_discount_apply_as_cart_discount = array();
}
}
/**
* change the coupon label
* @param $label
* @param $coupon
* @return mixed
*/
function overwriteCouponLabel($label, $coupon)
{
$coupon_code = self::$woocommerce_helper->getCouponCode($coupon);
if (!empty($coupon_code) && isset(self::$calculated_cart_discount['discount'][$coupon_code]['label'])) {
return self::$calculated_cart_discount['discount'][$coupon_code]['label'];
}
return $label;
}
/**
* Manage the virtual coupon provided for cart
* @param $response
* @param $coupon_code
* @return array
*/
function manageVirtualCoupon($response, $coupon_code)
{
if (isset(self::$calculated_cart_discount['discount'][$coupon_code])) {
return array(
'id' => 321123 . rand(2, 9),
'amount' => self::$calculated_cart_discount['discount'][$coupon_code]['price'],
'individual_use' => false,
'product_ids' => array(),
'exclude_product_ids' => array(),
'usage_limit' => '',
'usage_limit_per_user' => '',
'limit_usage_to_x_items' => '',
'usage_count' => '',
'date_created' => apply_filters('advanced_woo_discount_rules_custom_coupon_date_created', date('Y-m-d')),
'expiry_date' => '',
'apply_before_tax' => 'yes',
'free_shipping' => false,
'product_categories' => array(),
'exclude_product_categories' => array(),
'exclude_sale_items' => false,
'minimum_amount' => '',
'maximum_amount' => '',
'customer_email' => '',
'discount_type' => (self::$calculated_cart_discount['discount'][$coupon_code]['type'] == 'flat') ? 'fixed_cart' : 'percent'
);
}
return $response;
}
/**
* Apply the custom coupon for create coupon condition
* @param $response
* @param $coupon_code
* @return array
*/
function checkCouponToApply($response, $coupon_code)
{
if($coupon_code !== false && $coupon_code !== 0){
$rule_helper = new Rule();
$available_coupons = $rule_helper->getAllDynamicCoupons();
if (in_array($coupon_code, $available_coupons)) {
$amount = 0;
$coupon = array(
'id' => time() . rand(2, 9),
'amount' => $amount,
'individual_use' => false,
'product_ids' => array(),
'exclude_product_ids' => array(),
'usage_limit' => '',
'usage_limit_per_user' => '',
'limit_usage_to_x_items' => '',
'usage_count' => '',
'date_created' => apply_filters('advanced_woo_discount_rules_custom_coupon_date_created', date('Y-m-d')),
'expiry_date' => '',
'apply_before_tax' => 'yes',
'free_shipping' => false,
'product_categories' => array(),
'exclude_product_categories' => array(),
'exclude_sale_items' => false,
'minimum_amount' => '',
'maximum_amount' => '',
'customer_email' => '',
'discount_type' => 'percent'
);
return $coupon;
}
}
return $response;
}
/**
* To change the discount name/code in front end
* */
public function changeCouponLabelInFrontEnd($text, $coupon)
{
if(!empty(self::$apply_as_coupon_values)){
$coupon_code = Woocommerce::getCouponCode($coupon);
$coupon_codes = array_keys(self::$apply_as_coupon_values);
if(in_array($coupon_code, $coupon_codes)){
$text = self::$apply_as_coupon_values[$coupon_code]['display_text'];
}
}
return $text;
}
/**
* Set coupon values
* */
public static function setCartCouponValues($label, $discount_value, $cart_item_keys, $rule_ids, $discount_details){
$coupon_code = apply_filters('woocommerce_coupon_code', $label);
$discount_value = apply_filters('advanced_woo_discount_rules_coupon_value', $discount_value, $label, $cart_item_keys);
self::$apply_as_coupon_values[$coupon_code]['value'] = $discount_value;
self::$apply_as_coupon_values[$coupon_code]['cart_item_keys'] = $cart_item_keys;
self::$apply_as_coupon_values[$coupon_code]['display_text'] = $label;
self::setCartCouponDiscountDetails($coupon_code, $label, $discount_value, $rule_ids, $discount_details);
}
/**
* Set discount coupons details
*/
public static function setCartCouponDiscountDetails($name, $label, $value, $rule_ids, $discount_details)
{
$rules = [];
foreach ($rule_ids as $rule_id) {
if (isset(self::$available_rules[$rule_id])) {
$data = [
'id' => $rule_id,
'title' => self::$available_rules[$rule_id]->getTitle(),
];
if (isset($discount_details[$rule_id])) {
$data['discount'] = [
'discount_label' => $discount_details[$rule_id]['discount_label'],
'discount_value' => round($discount_details[$rule_id]['discount_value'], 4),
];
}
$rules[] = $data;
}
}
if (!empty($rules)) {
self::$applied_cart_coupon_discounts[] = ['name' => $name, 'value' => round($value, 4), 'rules' => $rules];
}
}
/**
* Remove duplicate values from multi dimension array
* */
protected static function removeDuplicateValues($apply_as_cart_fee_details){
if(!empty($apply_as_cart_fee_details)){
foreach ($apply_as_cart_fee_details as $key => $apply_as_cart_fee_detail){
$apply_as_cart_fee_details[$key] = array_map("unserialize", array_unique(array_map("serialize", $apply_as_cart_fee_detail)));
}
}
return $apply_as_cart_fee_details;
}
/**
* Apply dynamic coupon for cart rules
* */
function applyVirtualCouponForCartRules(){
$discount_apply_type = self::$config->getConfig('apply_cart_discount_as', 'coupon');
if($discount_apply_type == "coupon"){
remove_action('woocommerce_after_calculate_totals', array($this, 'applyVirtualCouponForCartRules'), 10);
$combine_all_discounts = self::$config->getConfig('combine_all_cart_discounts', 0);
$total_combined_discounts = 0;
$combined_discounts_cart_items = array();
if(function_exists('WC')){
if(apply_filters('advanced_woo_discount_rules_recalculate_discount_before_apply_coupon', true)){
$cart_items = Woocommerce::getCart();
$loop_limit = 1;
if(!empty($cart_items) && is_array($cart_items)){
$loop_limit = count($cart_items)+1;
}
if ( $loop_limit >= did_action( 'advanced_woo_discount_rules_before_recalculate_discount_on_apply_coupon' ) ) {
do_action('advanced_woo_discount_rules_before_recalculate_discount_on_apply_coupon');
$this->applyCartProductDiscount(WC()->cart, true);
}
}
}
$apply_as_cart_fee_details = DiscountCalculator::$price_discount_apply_as_cart_discount;
DiscountCalculator::$price_discount_apply_as_cart_discount = array();
self::$applied_cart_coupon_discounts = array();
$apply_as_cart_fee_details = self::removeDuplicateValues($apply_as_cart_fee_details);
$flat_in_subtotal = array();
$discount_coupons = array();
if(!empty($apply_as_cart_fee_details)){
foreach ($apply_as_cart_fee_details as $rule_id => $product_id){
$cart_item_keys = array();
$discount_value = 0;
foreach ($product_id as $detail) {
if($detail['discount_type'] == 'wdr_cart_discount' && $detail['apply_type'] == 'flat_in_subtotal'){
if(!isset($flat_in_subtotal[$rule_id])){
$flat_in_subtotal[$rule_id]['value'] = $detail['discounted_price'];
$flat_in_subtotal[$rule_id]['label'] = $detail['discount_label'];
$flat_in_subtotal[$rule_id]['cart_item_keys'][] = $detail['cart_item_key'];
if (!isset($discount_coupons[$rule_id])) {
$discount_coupons[$rule_id] = array('discount_label' => $detail['discount_label'], 'discount_value' => $detail['discounted_price']);
}
} else {
$flat_in_subtotal[$rule_id]['cart_item_keys'][] = $detail['cart_item_key'];
}
}else{
$discount_value += $detail['discounted_price'];
$label = (isset($detail['discount_label']) && !empty($detail['discount_label'])) ? $detail['discount_label'] : $detail['rule_name'];
$cart_item_keys[] = $detail['cart_item_key'];
if (!isset($discount_coupons[$rule_id])) {
$discount_coupons[$rule_id] = array('discount_label' => $label, 'discount_value' => $detail['discounted_price']);
} else {
$discount_coupons[$rule_id]['discount_value'] += $detail['discounted_price'];
}
}
}
if ($discount_value > 0) {
if (empty($combine_all_discounts)) {
$label = __($label, 'woo-discount-rules');
self::setCartCouponValues($label, $discount_value, $cart_item_keys, array($rule_id), $discount_coupons);
$this->applyFakeCouponsForCartRules($label);
}else{
$total_combined_discounts += $discount_value;
$combined_discounts_cart_items = array_merge($combined_discounts_cart_items, $cart_item_keys);
}
self::$calculated_cart_discount['discount'][] = array('price' => $discount_value, 'label' => $label, 'cart_item_keys' => $cart_item_keys);
}
}
}
if (!empty($flat_in_subtotal)) {
foreach ($flat_in_subtotal as $rule_id => $discount){
if(empty($combine_all_discounts)){
$discount_value = $discount['value'];
$label = $discount['label'];
$label = __($label, 'woo-discount-rules');
self::setCartCouponValues($label, $discount_value, $discount['cart_item_keys'], array($rule_id), $discount_coupons);
$this->applyFakeCouponsForCartRules($label);
}else{
$total_combined_discounts += $discount['value'];
$combined_discounts_cart_items = array_merge($combined_discounts_cart_items, $discount['cart_item_keys']);
}
}
}
//Combine all discounts and add as single discounts
if (!empty($total_combined_discounts) && !empty($combine_all_discounts)) {
$label = self::$config->getConfig('discount_label_for_combined_discounts', __('Cart discount', 'woo-discount-rules'));
$label = Helper::getCleanHtml($label);
if(empty($label)){
$label = __('Cart discount', 'woo-discount-rules');
}
$label = __($label, 'woo-discount-rules');
self::setCartCouponValues($label, $total_combined_discounts, $combined_discounts_cart_items, array_keys($discount_coupons), $discount_coupons);
$this->applyFakeCouponsForCartRules($label);
}
add_action('woocommerce_after_calculate_totals', array($this, 'applyVirtualCouponForCartRules'), 10);
}
}
/**
* Apply dynamic coupon for cart rules
* */
function applyFakeCouponsForCartRules($coupon_code){
global $woocommerce;
$coupon_code = apply_filters('woocommerce_coupon_code', $coupon_code);
// Validating the Coupon as Valid and discount status.
if(isset($woocommerce->cart)){
if(is_object($woocommerce->cart) && method_exists($woocommerce->cart, 'has_discount')){
if (!$woocommerce->cart->has_discount($coupon_code)) {
// Do not apply coupon with individual use coupon already applied
if ($woocommerce->cart->applied_coupons) {
foreach ($woocommerce->cart->applied_coupons as $code) {
$coupon = new \WC_Coupon($coupon_code);
if ($coupon->get_individual_use() == true) {
return false;
}
}
}
// Add coupon
$woocommerce->cart->applied_coupons[] = $coupon_code;
do_action('woocommerce_applied_coupon', $coupon_code);
return true;
}
}
}
}
/**
* Apply url coupon
*/
function applyUrlCoupon() {
global $woocommerce;
if (isset($_GET['wdr_coupon']) && !empty($_GET['wdr_coupon']) && isset($woocommerce->cart)) {
if ( is_object($woocommerce->cart) && method_exists( $woocommerce->cart, 'has_discount' ) && method_exists( $woocommerce->cart, 'add_discount' ) ) {
$rule_helper = new Rule();
$available_url_coupons = $rule_helper->getAllUrlCoupons();
$available_url_coupons = array_map('\Wdr\App\Helpers\Woocommerce::formatStringToLower', $available_url_coupons);
$coupons = explode(",", $_GET['wdr_coupon']);
if (isset($woocommerce->session) && is_object($woocommerce->session) && method_exists($woocommerce->session, 'has_session')) {
if ( ! $woocommerce->session->has_session() && method_exists($woocommerce->session, 'set_customer_session_cookie')) {
$woocommerce->session->set_customer_session_cookie( true );
}
}
foreach ( $coupons as $coupon ) {
$coupon_code = rawurldecode( $coupon );
$coupon_code = Woocommerce::formatStringToLower($coupon_code);
if ( in_array( $coupon_code, $available_url_coupons ) ) {
if ( ! $woocommerce->cart->has_discount( $coupon_code ) ) {
$woocommerce->cart->add_discount( $coupon_code );
}
} else {
Woocommerce::wc_add_notice( sprintf( __( 'Coupon "%s" is currently not available!', 'woo-discount-rules' ), $coupon_code ), 'error' );
}
}
}
}
}
/**
* Get product ids from cart key
* */
protected static function getProductIdsFromCartKey($cart_item_keys){
$product_ids = array();
$cart = Woocommerce::getCart();
foreach ($cart as $cart_item){
if(in_array($cart_item['key'], $cart_item_keys)){
$product_ids[] = $cart_item['product_id'];
}
}
if(!empty($product_ids)) $product_ids = array_unique($product_ids);
return $product_ids;
}
/**
* Get percentage amount from selected cart item
* */
protected static function getPercentageFromCartKey($product_ids, $discountPrice){
$total_price = 0;
$cart = Woocommerce::getCart();
foreach ($cart as $cart_item){
if(in_array($cart_item['product_id'], $product_ids)){
$total_price += $cart_item['quantity']*$cart_item['data']->get_price();
}
}
if($total_price > 0){
return ($discountPrice*100)/$total_price;
}
return $total_price;
}
/**
* Apply the custom coupon for create coupon condition
* @param $response
* @param $coupon_code
* @return array
*/
function validateVirtualCouponForCartRules($response, $coupon_data)
{
if($coupon_data !== false && $coupon_data !== 0){
$discount_apply_type = self::$config->getConfig('apply_cart_discount_as', 'coupon');
if($discount_apply_type == "coupon"){
if(empty(self::$apply_as_coupon_values)){
remove_filter('woocommerce_get_shop_coupon_data', array($this, 'validateVirtualCouponForCartRules'), 10);
$this->applyVirtualCouponForCartRules();
add_filter('woocommerce_get_shop_coupon_data', array($this, 'validateVirtualCouponForCartRules'), 10, 2);
}
$product_ids = array();
if(!empty(self::$apply_as_coupon_values)){
if(array_key_exists($coupon_data, self::$apply_as_coupon_values)){
$coupon_code = $coupon_data;
$amount = self::$apply_as_coupon_values[$coupon_code]['value'];
$cart_item_keys = self::$apply_as_coupon_values[$coupon_code]['cart_item_keys'];
if(apply_filters('advanced_woo_discount_rules_apply_coupon_for_products_based_on_filters', true, $coupon_code)){
$product_ids = self::getProductIdsFromCartKey($cart_item_keys);
$discount_in_percentage = self::getPercentageFromCartKey($product_ids, $amount);
}
} else {
return $response;
}
} else {
add_filter('woocommerce_coupon_error', '\Wdr\App\Helpers\Helper::removeErrorMessageForOurCoupons', 10, 3);
return $response;
}
// Getting Coupon Remove status from Session.
if(isset(WC()->session) && is_object(WC()->session) && method_exists(WC()->session, 'get')) {
$is_removed = WC()->session->get('woo_coupon_removed', '');
// If Both are same, then it won't added.
if(!empty($is_removed)){
if ($coupon_code == $is_removed) return $response;
}
}
if ($coupon_data == $coupon_code || wc_strtolower($coupon_data) == wc_strtolower($coupon_code)) {
//if ($this->postData->get('remove_coupon', false) == $coupon_code) return false;
if(empty($product_ids)){
$discount_type = 'fixed_cart';
} else {
$discount_type = apply_filters('advanced_woo_discount_rules_coupon_discount_type_percentage', 'percent');
$amount = $discount_in_percentage;
}
$coupon = array(
'id' => time().rand(2, 9),
'amount' => $amount,
'individual_use' => false,
'product_ids' => $product_ids,
'exclude_product_ids' => array(),
'usage_limit' => '',
'usage_limit_per_user' => '',
'limit_usage_to_x_items' => '',
'usage_count' => '',
'expiry_date' => '',
'apply_before_tax' => 'yes',
'free_shipping' => false,
'product_categories' => array(),
'exclude_product_categories' => array(),
'exclude_sale_items' => false,
'minimum_amount' => '',
'maximum_amount' => '',
'customer_email' => '',
);
$coupon['discount_type'] = $discount_type;
return $coupon;
}
}
}
return $response;
}
/**
* Has third party coupon
*
* @return boolean
* */
function isCartContainsAnyThirdPartyCoupon(){
$has_third_party_coupon = false;
$used_coupons = DiscountCalculator::getUsedCoupons();
$applied_coupons = Woocommerce::getAppliedCoupons();
if(!empty($applied_coupons) && is_array($applied_coupons) && !empty($used_coupons)){
$used_coupons = array_map('\Wdr\App\Helpers\Woocommerce::formatStringToLower', $used_coupons);
foreach ($applied_coupons as $applied_coupon){
if(!in_array($applied_coupon, $used_coupons)){
$has_third_party_coupon = true;
break;
}
}
}elseif(!empty($applied_coupons) && is_array($applied_coupons) && empty($used_coupons)){
$has_third_party_coupon = true;
}
return $has_third_party_coupon;
}
/**
* Remove third party coupon when rule applied
*
* @param $calculated_cart_item_discount array
* @param $processed_rule boolean
* */
function removeThirdPartyCouponIfRequired($calculated_cart_item_discount, $processed_rule){
if($processed_rule === true){
add_action('woocommerce_after_calculate_totals', array($this, 'removeThirdPartyCoupon'), 20);
}
}
/**
* Remove third party coupon if exists
* */
function removeThirdPartyCoupon(){
$disable_coupon_when_rule_applied = self::$config->getConfig('disable_coupon_when_rule_applied', 'run_both');//run_both, disable_coupon, disable_rules
if($disable_coupon_when_rule_applied == 'disable_coupon'){
$used_coupons = DiscountCalculator::getUsedCoupons();
$applied_coupons = Woocommerce::getAppliedCoupons();
if(!empty($applied_coupons) && is_array($applied_coupons)){
if(!empty($used_coupons)){
$used_coupons = array_map('\Wdr\App\Helpers\Woocommerce::formatStringToLower', $used_coupons);
}
foreach ($applied_coupons as $applied_coupon){
if(empty($used_coupons) || !in_array($applied_coupon, $used_coupons)){
$exclude_coupon = apply_filters('advanced_woo_discount_rules_exclude_coupon_while_remove_third_party_coupon', false, $applied_coupon);
if ($exclude_coupon === false) {
$this->removeAppliedCoupon($applied_coupon);
}
}
}
}
}
}
/**
* Remove applied message for the coupon we are going to remove
* */
function removeAppliedMessageOfThirdPartyCoupon($msg, $msg_code, $coupon){
if(!empty($coupon)){
$disable_coupon_when_rule_applied = self::$config->getConfig('disable_coupon_when_rule_applied', 'run_both');//run_both, disable_coupon, disable_rules
/**
* Added fix for coupon not applied in checkout page( when disable coupon discount rules will work)
* added check for condition isset(self::$calculated_cart_item_discount) && !empty(self::$calculated_cart_item_discount)
* @since 2.3.4
*/
if($disable_coupon_when_rule_applied == 'disable_coupon' && isset(self::$calculated_cart_item_discount) && !empty(self::$calculated_cart_item_discount)){
$used_coupons = DiscountCalculator::getUsedCoupons();
$applied_coupons = Woocommerce::getAppliedCoupons();
if(!empty($applied_coupons) && is_array($applied_coupons)){
if(!empty($used_coupons)){
$used_coupons = array_map('\Wdr\App\Helpers\Woocommerce::formatStringToLower', $used_coupons);
}
foreach ($applied_coupons as $applied_coupon){
if(empty($used_coupons) || !in_array($applied_coupon, $used_coupons)){
$msg = '';
}
}
}
}
}
return $msg;
}
/**
* Remove applied coupon
*
* @param $coupon_code string
* */
function removeAppliedCoupon($coupon_code){
$msg = sprintf(__('Sorry, it is not possible to apply coupon "%s" as you already have a discount applied in cart.', 'woo-discount-rules'), $coupon_code);
$msg = apply_filters('advanced_woo_discount_rules_notice_on_remove_coupon_while_having_a_discount', $msg, $coupon_code);
//Remove message: Coupon code applied successfully.
$this->removeCouponAppliedMessage();
Woocommerce::remove_coupon($coupon_code);
Woocommerce::wc_add_notice( $msg, 'notice' );
}
/**
* Remove message: Coupon code applied successfully.
* */
function removeCouponAppliedMessage(){
$msg = __( 'Coupon code applied successfully.', 'woocommerce' );
$msg = apply_filters('advanced_woo_discount_rules_remove_coupon_applied_message_text', $msg);
Woocommerce::removeSpecificNoticeFromSession($msg);
}
/**
* Do apply discounts
*
* @return boolean
* */
function doApplyDiscount($cart_object){
$run_rule = true;
$disable_coupon_when_rule_applied = self::$config->getConfig('disable_coupon_when_rule_applied', 'run_both');//run_both, disable_coupon, disable_rules
if($disable_coupon_when_rule_applied == 'disable_rules'){
$has_third_party_coupon = $this->isCartContainsAnyThirdPartyCoupon();
if($has_third_party_coupon === true){
do_action('advanced_woo_discount_rules_remove_applied_rules_on_coupon_applied');
$calc = self::$calculator;
$calc::$applied_rules = array();
$run_rule = false;
}
}
return apply_filters('advanced_woo_discount_rules_run_discount_rules', $run_rule, $cart_object);
}
/**
* Apply discount for the products in cart
* @param $cart_object
* @return boolean
*/
function applyCartProductDiscount($cart_object, $on_coupon_validate = false)
{
remove_action('woocommerce_cart_calculate_fees', array($this, 'applyCartDiscount'));
Helper::clearPromotionMessages();
$do_apply_discount = $this->doApplyDiscount($cart_object);
if($do_apply_discount){
$calc = self::$calculator;
$calc::$applied_rules = array();
$this->calculateCartPageDiscounts($on_coupon_validate);
$processed_rule = false;
if (!empty(self::$calculated_cart_item_discount)) {
if (isset($cart_object->cart_contents) && !empty($cart_object->cart_contents)) {
foreach ($cart_object->cart_contents as $key => $cart_item) {
if (array_key_exists($key, self::$calculated_cart_item_discount)) {
$processed_rule = true;
$product_id = isset($cart_item['product_id']) ? $cart_item['product_id'] : 0;
if (isset($cart_item['variation_id']) && !empty($cart_item['variation_id'])) {
$product_id = $cart_item['variation_id'];
}
if (empty($product_id)) {
return false;
}
$product_obj = isset($cart_item['data']) ? $cart_item['data'] : $cart_item;
$item_quantity = isset($cart_item['quantity']) ? $cart_item['quantity'] : 0;
//product price
$initial_price = self::$calculated_cart_item_discount[$key]['initial_price'];
$discounted_price = self::$calculated_cart_item_discount[$key]['discounted_price'];
$calculator = self::$calculator;
$total_discounts = $calculator::$total_discounts;
$price = $discounted_price;
$price = apply_filters('advanced_woo_discount_rules_discounted_price_of_cart_item', $price, $cart_item, $cart_object, self::$calculated_cart_item_discount[$key]);
$do_apply_price_rules = apply_filters('advanced_woo_discount_rules_do_apply_price_discount', true, $price, $cart_item, $cart_object, self::$calculated_cart_item_discount[$key]);
if($do_apply_price_rules){
self::$woocommerce_helper->setCartProductPrice($product_obj, $price);
$product_obj->awdr_product_original_price = $initial_price;
}
}
}
}
}
// Disable third party coupon when rule applied
$this->removeThirdPartyCouponIfRequired(self::$calculated_cart_item_discount, $processed_rule);
do_action('advanced_woo_discount_rules_after_apply_discount', $cart_object, self::$calculated_cart_item_discount);
}
add_action('woocommerce_cart_calculate_fees', array($this, 'applyCartDiscount'));
}
/**
* Calculate cart discounts
* @return bool
*/
function calculateCartPageDiscounts($on_coupon_validate = false)
{
$cart_items = self::$woocommerce_helper->getCart();
if (!empty($cart_items)) {
foreach ($cart_items as $cart_key => $cart_item) {
$product_id = self::$woocommerce_helper->getProductId(isset($cart_item['data']) ? $cart_item['data'] : $cart_item);
$product = self::$woocommerce_helper->getProductFromCartItem($cart_item, $product_id);
$quantity = $cart_item['quantity'];
$calculate_discount_for_item = apply_filters('advanced_woo_discount_rules_calculate_discount_for_cart_item', true, $cart_item);
if($calculate_discount_for_item){
$prices = self::calculateInitialAndDiscountedPrice($product, $quantity, true, false, $cart_item, $on_coupon_validate);
if ($prices) {
//add the cart quantity
//Here discounts are calculated for per item
$prices['cart_quantity'] = $quantity;
$prices['product_id'] = $product_id;
$apply_discount = $this->didAppliedDiscountAlready($cart_key, $prices);
if ($apply_discount) {
self::$calculated_cart_item_discount[$cart_key] = apply_filters('advanced_woo_discount_rules_cart_item_discount_prices', $prices, $cart_item, $product);
}
}
}
}
}
return true;
}
/**
* Did applied discount already
*
* @param $cart_key string
* @param $prices array
* @return boolean
* */
public function didAppliedDiscountAlready($cart_key, $prices)
{
$apply_discount = true;
if (isset(self::$calculated_cart_item_discount[$cart_key])) {
if (isset(self::$calculated_cart_item_discount[$cart_key]['discounted_price'])) {
if (self::$calculated_cart_item_discount[$cart_key]['discounted_price'] > $prices['discounted_price']) {
$apply_discount = false;
}
}
}
return apply_filters('advanced_woo_discount_rules_did_discount_applied_already', $apply_discount, self::$calculated_cart_item_discount, $cart_key, $prices);
}
/**
* laod the bulk table discount message manually
* @param $product
* @param false $get_variable_product_table
* @return false|string
*/
function showBulkTableInPositionManually($product, $get_variable_product_table = false)
{
if (!empty($product)) {
$bulk_discounts_ranges = wp_unslash(self::$calculator->getDefaultLayoutMessagesByRules($product, $get_variable_product_table));
if(empty($bulk_discounts_ranges)){
$bulk_discounts_ranges['layout']['type'] = 'default';
$bulk_discounts_ranges['layout']['bulk_variant_table'] = 'default_variant_empty';
}
$override_path = get_theme_file_path('advanced_woo_discount_rules/discount_table.php');
$bulk_table_template_path = WDR_PLUGIN_PATH . 'App/Views/Templates/discount_table.php';
if (file_exists($override_path)) {
$bulk_table_template_path = $override_path;
}
if($get_variable_product_table){
return self::$template_helper->setPath($bulk_table_template_path)->setData(array('ranges' => $bulk_discounts_ranges, 'woocommerce' => self::$woocommerce_helper, 'base' => $this))->render();
}
self::$template_helper->setPath($bulk_table_template_path)->setData(array('ranges' => $bulk_discounts_ranges, 'woocommerce' => self::$woocommerce_helper, 'base' => $this))->display();
}
}
/**
* Show the bulk table discount message
*/
function showBulkTableInPosition()
{
global $product;
if (!empty($product)) {
$this->showBulkTableInPositionManually($product);
}
}
/**
* load the advanced table discount message manually
*/
function showAdvancedTableInPositionManually($product)
{
if (!empty($product)) {
$bulk_discounts_ranges = wp_unslash(self::$calculator->getAdvancedLayoutMessagesByRules($product));
$override_path = get_theme_file_path('advanced_woo_discount_rules/discount_table.php');
$bulk_table_template_path = WDR_PLUGIN_PATH . 'App/Views/Templates/discount_table.php';
if (file_exists($override_path)) {
$bulk_table_template_path = $override_path;
}
self::$template_helper->setPath($bulk_table_template_path)->setData(array('ranges' => $bulk_discounts_ranges, 'woocommerce' => self::$woocommerce_helper))->display();
}
}
/**
* Show the advanced table discount message
*/
function showAdvancedTableInPosition()
{
global $product;
if (!empty($product)) {
$this->showAdvancedTableInPositionManually($product);
}
}
/**
* save discounts of order for future
*
* @param $order_id
* @param $items
* @return void
*/
function orderItemsSaved($order_id, $items)
{
$order = self::$woocommerce_helper->getOrder($order_id);
if (empty($order)) {
return;
}
$free_shipping = false;
if (self::$woocommerce_helper->orderHasShippingMethod($order, 'wdr_free_shipping')) {
$free_shipping = true;
}
$cart_discounts = [];
if (!empty(self::$applied_cart_coupon_discounts)) {
$cart_discounts = [
'applied_as' => self::$config->getConfig('apply_cart_discount_as', 'coupon'),
'combine_all_discounts' => (bool) self::$config->getConfig('combine_all_cart_discounts', 0),
'applied_coupons' => self::$applied_cart_coupon_discounts,
];
}
$product_discount_total = $product_discount_total_with_tax = $cart_discount_total = 0;
foreach (self::$woocommerce_helper->getOrderItems($order) as $item_id => $item) {
if ($details = self::$woocommerce_helper->getOrderItemMeta($item, '_wdr_discounts')) {
$item_data = self::$woocommerce_helper->getOrderItemData($item);
if (empty($item_data)) {
continue;
}
$quantity = $item_data['quantity'];
$product_id = $item_data['variation_id'] > 0 ? $item_data['variation_id'] : $item_data['product_id'];
$initial_price = isset($details['initial_price_based_on_tax_settings']) ? $details['initial_price_based_on_tax_settings'] : 0;
$discounted_price = isset($details['discounted_price_based_on_tax_settings']) ? $details['discounted_price_based_on_tax_settings'] : 0;
$product_discount_total += isset($details['saved_amount']) ? $details['saved_amount'] : 0;
$product_discount_total_with_tax += isset($details['saved_amount_based_on_tax_settings']) ? $details['saved_amount_based_on_tax_settings'] : 0;
if (isset($details['applied_rules']) && !empty($details['applied_rules'])) {
foreach ($details['applied_rules'] as $rule) {
$simple_discount = $bulk_discount = $set_discount = $other_discount = 0;
$discount = $rule['discount'];
if ($discount['applied_in'] == 'product_level') {
switch ($rule['type']) {
case 'simple_discount':
$simple_discount = $discount['discount_price'] * $quantity;
break;
case 'bulk_discount':
$bulk_discount = $discount['discount_price'] * $quantity;
break;
case 'set_discount':
$set_discount = $discount['discount_price'] * $discount['discount_quantity'];
break;
default:
$other_discount = $discount['discount_price'] * $quantity;
}
$discount_price = $simple_discount + $bulk_discount + $set_discount + $other_discount;
DBTable::saveOrderItemDiscounts($order_id, $item_id, $product_id, $initial_price, $discounted_price, $discount_price, $quantity, $rule['id'], $simple_discount, $bulk_discount, $set_discount, 0, $other_discount, null);
}
}
}
}
}
foreach (self::$applied_cart_coupon_discounts as $coupon) {
foreach ($coupon['rules'] as $rule) {
$cart_discount = $rule['discount']['discount_value'];
$cart_discount_label = $rule['discount']['discount_label'];
$cart_discount_total += $cart_discount;
DBTable::saveOrderItemDiscounts($order_id, 0, 0, 0, 0, 0, 0, $rule['id'], 0, 0, 0, $cart_discount, 0, $cart_discount_label);
}
}
$available_custom_coupons = (new Rule())->getAllDynamicCoupons();
$applied_coupons = self::$woocommerce_helper->getAppliedCoupons();
$applied_custom_coupons = array_intersect($applied_coupons, $available_custom_coupons);
if (!empty($applied_custom_coupons)) {
foreach ($applied_custom_coupons as $custom_coupon_label) {
DBTable::saveOrderItemDiscounts($order_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $custom_coupon_label);
}
}
$calc = self::$calculator;
if (!empty($calc::$applied_rules)) {
foreach ($calc::$applied_rules as $rule) {
$used_limits = intval($rule->getUsedLimits()) + 1;
DBTable::updateRuleUsedCount($rule->getId(), $used_limits);
if ($free_shipping && $rule->getRuleDiscountType() == 'wdr_free_shipping') {
DBTable::saveOrderItemDiscounts($order_id, 0, 0, 0, 0, 0, 0, $rule->getId(), 0, 0, 0, 0, 0, null, true);
}
}
}
$discount_details = [];
if (!empty(self::$calculated_cart_discount)) {
if (isset(self::$calculated_cart_discount["discount"]) && !empty(self::$calculated_cart_discount["discount"])) {
$discount_details = self::$calculated_cart_discount["discount"];
}
}
if (!empty($discount_details) || $free_shipping) {
$discount_details = json_encode($discount_details);
$has_free_shipping = $free_shipping ? 'yes' : 'no';
DBTable::saveOrderDiscounts($order_id, $has_free_shipping, $discount_details);
}
$order_discount_info = [
'free_shipping' => $free_shipping,
'cart_discounts' => $cart_discounts,
'saved_amount' => [
'product_level' => round($product_discount_total, 4),
'product_level_based_on_tax_settings' => round($product_discount_total_with_tax, 4),
'cart_level' => round($cart_discount_total, 4),
'total' => round($product_discount_total + $cart_discount_total, 4),
'total_based_on_tax_settings' => round($product_discount_total_with_tax + $cart_discount_total, 4),
]
];
if (!empty($order_discount_info['free_shipping']) || !empty($order_discount_info['saved_amount']['total'])) {
self::$woocommerce_helper->setOrderMeta($order, '_wdr_discounts', $order_discount_info);
}
}
/**
* Bxgx free product amount data
* @param $buy_x_get_x_free_discounts
* @param $order_id
* @param $items
*/
function orderItemsSavedForBXGXFree($buy_x_get_x_free_discounts, $order_id, $items){
if(!empty($buy_x_get_x_free_discounts)){
foreach ($buy_x_get_x_free_discounts as $buy_x_get_x_free_key => $buy_x_get_x_free_discount){
$simple_discount = $bulk_discount = $set_discount = $cart_discount = 0;
$rule_id = isset($buy_x_get_x_free_discount['rule_id']) ? $buy_x_get_x_free_discount['rule_id'] : 0;
$variant_item_id = isset($buy_x_get_x_free_discount['variation_id']) ? $buy_x_get_x_free_discount['variation_id'] : '';
$item_id = isset($buy_x_get_x_free_discount['product_id']) ? $buy_x_get_x_free_discount['product_id'] : 0;
if(!empty($variant_item_id)){
$item_id = $variant_item_id;
}
$free_product = isset($buy_x_get_x_free_discount['cart_item']['data']) ? $buy_x_get_x_free_discount['cart_item']['data'] : '';
$discount = Woocommerce::getProductPrice($free_product);
$discount_quantity = isset($buy_x_get_x_free_discount['discount_quantity']) ? $buy_x_get_x_free_discount['discount_quantity'] : 0;
$discount_price = $discount * $discount_quantity;
$cart_shipping = 'no';
$cart_discount_label = '';
if($discount_price != 0){
$applied_rules[] = $rule_id;
}
DBTable::saveOrderItemDiscounts($order_id, $item_id, 0, 0, $discount_price, $discount_quantity, $rule_id, $simple_discount, $bulk_discount, $set_discount, $cart_discount, $cart_discount_label, $cart_shipping);
}
}
}
/**
* Bxgy free product amount data
* @param $buy_x_get_y_free_discounts
* @param $order_id
* @param $items
*/
function orderItemsSavedForBXGYFree($buy_x_get_y_free_discounts, $order_id, $items){
if(!empty($buy_x_get_y_free_discounts)){
foreach ($buy_x_get_y_free_discounts as $buy_x_get_y_free_key => $buy_x_get_y_free_discount){
$simple_discount = $bulk_discount = $set_discount = $cart_discount = $discount_quantity = 0;
$rule_id = isset($buy_x_get_y_free_discount['rule_id']) ? $buy_x_get_y_free_discount['rule_id'] : 0;
$variant_item_id = isset($buy_x_get_y_free_discount['variation_id']) ? $buy_x_get_y_free_discount['variation_id'] : 0;
$item_id = isset($buy_x_get_y_free_discount['product_id']) ? $buy_x_get_y_free_discount['product_id'] : 0;
if(!empty($variant_item_id)){
$item_id = $variant_item_id;
}
if($item_id != 0){
$free_product = isset($buy_x_get_y_free_discount['cart_item']['data']) ? $buy_x_get_y_free_discount['cart_item']['data'] : '';
$discount = Woocommerce::getProductPrice($free_product);
$discount_quantity = isset($buy_x_get_y_free_discount['discount_quantity']) ? $buy_x_get_y_free_discount['discount_quantity'] : 0;
$discount_price = $discount * $discount_quantity;
}else{
$discount_price = 0;
$discount_products = isset($buy_x_get_y_free_discount['discount_products']) ? $buy_x_get_y_free_discount['discount_products'] : array();
if(!empty($discount_products)){
foreach ($discount_products as $product_id){
$free_product = Woocommerce::getProduct((int)$product_id);
$discount = Woocommerce::getProductPrice($free_product);
$discount_quantity = isset($buy_x_get_y_free_discount['discount_quantity']) ? $buy_x_get_y_free_discount['discount_quantity'] : 0;
$discount_price += $discount * $discount_quantity;
}
}
}
$cart_shipping = 'no';
$cart_discount_label = '';
if($discount_price != 0){
$applied_rules[] = $rule_id;
}
DBTable::saveOrderItemDiscounts($order_id, $item_id, 0, 0, $discount_price, $discount_quantity, $rule_id, $simple_discount, $bulk_discount, $set_discount, $cart_discount, $cart_discount_label, $cart_shipping);
}
}
}
/**
* Show the discount promotion message
*/
function showAppliedRulesMessages()
{
$message = self::$config->getConfig('applied_rule_message', __('Discount {{title}} has been applied to your cart.', 'woo-discount-rules'));
$message = Helper::getCleanHtml($message);
$message = __($message, 'woo-discount-rules');
$calc = self::$calculator;
$applied_rules = $calc::$applied_rules;
if (!empty($applied_rules)) {
foreach ($applied_rules as $rule) {
$title = $rule->getTitle();
$title = __($title, 'woo-discount-rules');
$message_to_display = str_replace('{{title}}', $title, $message);
$message_to_display = apply_filters('advanced_woo_discount_rules_message_to_display_when_rules_applied', $message_to_display, $rule);
self::$woocommerce_helper->printNotice($message_to_display, 'success');
}
}
}
/**
* Display promotional message in check out while processing order review
* */
public function displayPromotionMessagesInCheckout(){
echo "