types = Array(
'percent_total_amount' => __('Percentage of cart total amount', 'aco-woo-dynamic-pricing'),
'percent_product_price' => __('Percentage of product price', 'aco-woo-dynamic-pricing'),
'fixed_product_price' => __('Fixed price of product price', 'aco-woo-dynamic-pricing'),
'fixed_cart_amount' => __('Fixed price of cart total amount', 'aco-woo-dynamic-pricing'),
'cart_quantity' => __('Quantity based discount', 'aco-woo-dynamic-pricing')
);
}
/**
*
* Ensures only one instance of AWDP is loaded or can be loaded.
*
* @since 1.0.0
* @static
* @see WordPress_Plugin_Template()
* @return Main AWDP instance
*/
public static function instance($file = '', $version = '1.0.0')
{
if (is_null(self::$_instance)) {
self::$_instance = new self($file, $version);
}
return self::$_instance;
}
/**
* @return bool
*/
public function isActive()
{
return $this->_active;
}
// Cart Price View
public function cart_discount_items($item_price, $cart_item)
{
$prod_ID = $cart_item['data']->get_data()['slug'];
if( $this->converted_rate == '' && $cart_item['data']->get_ID() != '' ) {
$this->converted_rate = $this->get_con_unit($cart_item['data'], wc_remove_number_precision($this->discounted_price[$prod_ID]));
}
if ($this->discount_rules != false && sizeof($this->discount_rules) >= 1 && $this->check_discount($prod_ID) && false == $this->awdp_cart_rules) {
$discounted_price = abs(wc_remove_number_precision($this->discounted_price[$prod_ID]));
$actual_price = isset ($this->actual_price) ? (array_key_exists($prod_ID, $this->actual_price) ? $this->actual_price[$prod_ID] : $cart_item['data']->get_data()['price']) : $cart_item['data']->get_data()['price'];
$quantity = $cart_item['quantity'];
if (($discounted_price > 0.0000000001 && ($discounted_price < $actual_price)) || $discounted_price == 0) {
$item_price = wc_format_sale_price($actual_price * $this->converted_rate, $discounted_price * $this->converted_rate);
} else if ($discounted_price > $actual_price) {
$item_price = wc_format_sale_price($actual_price * $this->converted_rate, $discounted_price * $this->converted_rate);
}
}
return $item_price;
}
// Price View HTML
public function get_product_price_html($item_price, $product)
{
$prod_ID = $product->get_data()['slug'];
if( $this->converted_rate == '' && $product->get_ID() != '' ) {
$this->converted_rate = $this->get_con_unit($product, wc_remove_number_precision($this->discounted_price[$prod_ID]));
}
// Variable Product
if ($product->is_type('variable')) {
$variations = $product->get_available_variations();
if ($variations) {
$variation_prices = [];
$regular_prices = [];
foreach ($variations as $variation) {
array_push($variation_prices, $variation['display_price']);
// array_push($regular_prices, $variation['display_regular_price']);
}
$min_price = min($variation_prices);
$max_price = max($variation_prices);
if ($min_price !== $max_price) {
$item_price = wc_format_price_range($min_price * $this->converted_rate, $max_price * $this->converted_rate);
} else {
$item_price = wc_price($min_price * $this->converted_rate);
}
}
return $item_price;
}
// End Check
if ($this->discount_rules != false && sizeof($this->discount_rules) >= 1 && $this->check_discount($prod_ID) && false == $this->awdp_cart_rules) {
$latest_price = isset ($this->discounted_price) ? (array_key_exists($prod_ID, $this->discounted_price) ? abs(wc_remove_number_precision($this->discounted_price[$prod_ID])) : 0) : 0;
$actual_price = isset ($this->actual_price) ? (array_key_exists($prod_ID, $this->actual_price) ? $this->actual_price[$prod_ID] : $product->get_data()['price']) : $product->get_data()['price'];
if (($latest_price > 0.0000000001 && ($latest_price < $actual_price)) || $latest_price == 0) {
$item_price = wc_format_sale_price($actual_price * $this->converted_rate, $latest_price * $this->converted_rate);
} else if ($latest_price > $actual_price) {
$item_price = wc_format_sale_price($actual_price * $this->converted_rate, $latest_price * $this->converted_rate);
}
}
return $item_price;
}
// Currency convertor
public function get_con_unit( $product, $price = false, $insideloop = false )
{
if ( $this->conversion_unit === false && $insideloop === false ) {
global $WOOCS; // checking WooCommerce Currency Switcher (WOOCS) is enabled
$from_currency = get_option('woocommerce_currency');
$to_currency = get_woocommerce_currency();
if ( $from_currency === $to_currency || $WOOCS !== null ) return 1;
$view_price = $product->get_price('view');
$edit_price = ( $price ) ? $price : $product->get_price('edit');
if ($view_price && $edit_price && $edit_price > 0 && $view_price >0 ) {
$this->conversion_unit = $view_price / $edit_price;
} else {
$this->conversion_unit = 1;
}
if ($this->conversion_unit == 1) {
$this->conversion_unit = apply_filters('wcml_raw_price_amount', 1);
}
if ($this->conversion_unit == 1) {
if(wc_get_price_decimals()==0){
$converted_amount = apply_filters('wc_aelia_cs_convert', 1, $from_currency, $to_currency,2);
}else{
$converted_amount = apply_filters('wc_aelia_cs_convert', 1, $from_currency, $to_currency);
}
$this->conversion_unit = $converted_amount;
}
if ($this->conversion_unit == 1 && function_exists('wcpbc_the_zone')) {
$wcpbc = wcpbc_the_zone();
$converted_amount = 1;
if (is_callable($wcpbc, 'get_exchange_rate_price')) {
$converted_amount = $wcpbc->get_exchange_rate_price(1);
}
$this->conversion_unit = $converted_amount;
}
// global $WOOCS;
// if ($this->conversion_unit == 1 && $WOOCS!==null) {
// if (method_exists($WOOCS, 'woocs_exchange_value')) {
// $res=$WOOCS->woocs_exchange_value(1);
// $this->conversion_unit = $res;
// }
// }
return $this->conversion_unit;
} else if ( $this->conversion_unit === false && $insideloop === true ) { // Pricing Table
$data = $product->get_data();
$unit_price= (float)$data['regular_price'];
$converted_price = (float)$product->regular_price;
$this->conversion_unit = $converted_price / $unit_price;
return $this->conversion_unit;
} else {
return $this->conversion_unit;
}
}
// Show Pricing Table
public function show_pricing_table()
{
$pricing_table = $this->pricing_table;
$id = get_the_ID();
if ($pricing_table[$id]) echo $pricing_table[$id];
}
// Unset Discounts Array
public function apply_cart_discounts($cart_object)
{
$rules = $this->awdp_cart_rule_ids;
if ($this->awdp_cart_rules && $this->validate_discount_rules($cart_object, $rules, ['cart_total_amount', 'cart_items', 'cart_products'])) {
foreach ($rules as $rule) {
unset($this->discounts[$rule['id']]);
}
}
// Saving Cart in Session
WC()->session->__unset( 'WDP_Cart' );
WC()->session->set( 'WDP_Cart', WC()->cart->get_cart() );
}
// Discount Check
public function check_discount($slug)
{
$_discounts = array();
foreach ($this->discounts as $discounts) {
if ($discounts['discount_type'] == 'percent_product_price' || $discounts['discount_type'] == 'fixed_product_price' || $discounts['discount_type'] == 'cart_quantity') {
if (array_key_exists('discounts', $discounts)) {
if (!array_key_exists('type', $discounts['discounts'])) {
foreach ($discounts['discounts'] as $key => $discount) {
if (!isset($_discounts[$key])) {
$_discounts[$key] = 0.0;
}
if ($discount != '')
$_discounts[$key] += $discount;
}
}
}
}
}
if (isset($_discounts[$slug]) && $_discounts[$slug] > 0)
return true;
else
return false;
}
// Validate Rules
public function validate_discount_rules($cart_obj, $rule, $rules_to_validate = array(), $item = false, $single = false)
{
$list_id = (array_key_exists('product_list', $rule) && $rule['product_list']) ? $rule['product_list'] : '';
$evel_str = '';
// $rules_to_validate = ['cart_total_amount', 'cart_items', 'cart_products'];
$result = true;// if no rules, the validation must be true
// Disabling Quantity Rules for Discount Type -> Cart Quantity
if (array_key_exists('type', $rule) && 'cart_quantity' == $rule['type'] && 'cart_quantity' == $rule['quantity_type']) {
$qn_flag = true;
} else {
$qn_flag = false;
}
if (isset($rule['rules']) && is_array($rule['rules']) && !empty($rule['rules'])) {
foreach ($rule['rules'] as $val) {
if (is_array($val['rules']) && count($val['rules']) && !empty($val['rules'])) {
// echo 'rule';
$evel_str .= '(';
foreach ($val['rules'] as $rul) {
$evel_str .= '(';
if (in_array($rul['rule']['item'], $rules_to_validate)) {
if ($this->eval_rule($rul['rule'], $cart_obj, $item, $rule, $list_id, $qn_flag, $single)) {
$evel_str .= ' true ';
} else {
$evel_str .= ' false ';
}
} else {
$evel_str .= ' true ';
}
$evel_str .= ') ' . (($rul['operator'] !== false) ? $rul['operator'] : '') . ' ';
}
if (count($val['rules']) > 0 && !empty($val['rules'])) {
preg_match_all('/\(.*\)/', $evel_str, $match);
$evel_str = $match[0][0] . ' ';
}
$evel_str .= ') ' . (($val['operator'] !== false) ? $val['operator'] : '') . ' ';
}
}
if (count($rule['rules']) > 0 && !empty($rule['rules']) && $evel_str != '') {
preg_match_all('/\(.*\)/', $evel_str, $match);
$evel_str = $match[0][0] . ' ';
}
$evel_str = str_replace(['and', 'or'], ['&&', '||'], $evel_str);
if ($evel_str !== '') {
$result = eval('return ' . $evel_str . ';');
}
}
return $result;
}
public function eval_rule($rule, $cart_obj, $item = false, $discount_rule, $list_id, $qn_flag, $single = false)
{
$product_lists = $this->product_lists;
$wdp_cart_totals = $wdp_cart_items = $wdp_cart_quantity = 0;
// Checking if Product List is Active
if ( $list_id && $product_lists[$list_id] && WC()->cart && WC()->cart->get_cart_contents_count() > 0 ) {
$applicable_products = $product_lists[$list_id];
$cart_items = WC()->cart->get_cart();
if ($cart_items) {
foreach ($cart_items as $cart_item) {
if (in_array($cart_item['product_id'], $applicable_products)) {
$product_data = $cart_item['data']->get_data();
$wdp_cart_totals = $wdp_cart_totals + $product_data['price'] * $cart_item['quantity'];
$wdp_cart_items = $wdp_cart_items + $cart_item['quantity'];
$wdp_cart_quantity = $wdp_cart_quantity + 1;
}
}
}
} else if ( isset ( WC()->cart ) && WC()->cart->get_cart_contents_count() > 0 ) {
// Old Code //
// $wdp_cart_totals = (float)WC()->cart->subtotal;
// $wdp_cart_items = (float)WC()->cart->get_cart_contents_count();
// $wdp_cart_quantity = (float)sizeof(WC()->cart->get_cart());
// Checkout page ajax loading fix
$cart_items = is_checkout() ? ( WC()->session->get('WDP_Cart') ? WC()->session->get('WDP_Cart') : WC()->cart->get_cart() ) : WC()->cart->get_cart();
if ($cart_items) {
foreach ($cart_items as $cart_item) {
$product_data = $cart_item['data']->get_data();
$wdp_cart_totals = $wdp_cart_totals + $product_data['price'] * $cart_item['quantity'];
$wdp_cart_items = $wdp_cart_items + $cart_item['quantity'];
$wdp_cart_quantity = $wdp_cart_quantity + 1;
}
}
}
if ('cart_total_amount' == $rule['item']) {
// cart based rule : true
$this->awdp_cart_rules = true;
$this->apply_wdp_coupon = true;
// $this->awdp_cart_rule_ids[] = $discount_rule;
// Check if cart is empty
if ( !isset (WC()->cart) || $wdp_cart_totals == 0 || !did_action('woocommerce_before_calculate_totals') )
return false;
$item_val = $wdp_cart_totals;
$rel_val = (float)$rule['value'];
} else if ('product_price' == $rule['item']) {
$this->apply_wdp_coupon = true;
if ($single)
$item_val = (float)$item['data']->get_data()['price'];
else
$item_val = (float)$item->get_data()['price'];
$rel_val = (float)$rule['value'];
} else if ('cart_items' == $rule['item'] && false == $qn_flag) {
// cart based rule : true
$this->awdp_cart_rules = true;
$this->apply_wdp_coupon = true;
$this->awdp_cart_rule_ids[] = $discount_rule;
// Check if cart is empty
if ( !isset ( WC()->cart ) || $wdp_cart_quantity == 0 || !did_action('woocommerce_before_calculate_totals') ) return false;
$item_val = $wdp_cart_items;
$rel_val = (float)$rule['value'];
} else if ('cart_products' == $rule['item'] && false == $qn_flag) {
// cart based rule : true
$this->awdp_cart_rules = true;
$this->apply_wdp_coupon = true;
$this->awdp_cart_rule_ids[] = $discount_rule;
// Check if cart is empty
if ( !isset ( WC()->cart ) || $wdp_cart_quantity == 0 || !did_action('woocommerce_before_calculate_totals') ) return false;
$item_val = $wdp_cart_quantity;
$rel_val = (float)$rule['value'];
} else {
return false;
}
// if ( $item_val == 0 ) return false; // Divisible by zero error
switch ($rule['condition']) {
case 'equal_to':
if (@abs(($item_val - $rel_val) / $item_val) < 0.00001) {
return true;
}
break;
case 'less_than':
if ($item_val < $rel_val) {
return true;
}
break;
case 'less_than_eq':
if ($item_val < $rel_val || abs(($item_val - $rel_val) / $item_val) < 0.0001) {
return true;
}
break;
case 'greater_than':
if ($item_val > $rel_val) {
return true;
}
break;
case 'greater_than_eq':
if ($item_val > $rel_val || abs(($item_val - $rel_val) / $item_val) < 0.0001) {
return true;
}
break;
}
return false;
}
// Price
public function get_product_price($price, $product)
{
if ($product) {
$id = $product->get_id();
if (isset($this->product_lists[$id])) {
return $this->product_lists[$id]['price'];
}
return $this->calculate_discount($price, $product);
}
}
// Discount Calculation
public function calculate_discount($price, $product)
{
// Resetting discounts before cart totals
if (did_action('woocommerce_after_cart_table') && !defined('AWDP_CART_LOADED')) {
define('AWDP_CART_LOADED', true);
$this->discounts = $this->discounted_price = [];
}
// Load discount rules
$this->load_rules();
// Check if discount is active
if ($this->discount_rules == null)
return $price; // return product price
$products_with_discount = [];
global $woocommerce;
$awdp_product_id = $product->get_id();
$awdp_product_slug = $product->get_data()['slug'];
$this->pricing_table[$awdp_product_id] = '';
$this->discounted_price[$awdp_product_slug] = -0.0000000001;
// $this->awdp_cart_rules = false;
$this->awdp_cart_rule_ids = [];
foreach ($this->discount_rules as $k => $rule) {
// Get Product List
if ( !$this->get_items_to_apply_discount($product, $rule) ) {
continue;
}
// Validate Rules
if( 'cart_quantity' != $rule['type'] ) { // Skipping cart_quantity rule //
if ( !$this->validate_discount_rules( $product, $rule, ['cart_total_amount', 'cart_items', 'cart_products'] ) ) {
continue;
}
}
// Discounts Default Values
if ( !isset( $this->discounts[$rule['id']] ) ) {
$this->discounts[$rule['id']] = ['label' => $rule['label'], 'discount_type' => $rule['type'], 'discount_remainder' => -1, 'taxable' => false];
}
// Actual Price of the Product
if ( !isset( $this->actual_price[$product->get_data()['slug']] ) ) {
$discounted_price = $this->get_individual_discounted_price_in_cents($product, $rule['inc_tax'], true); // sequential
$actual_price = $this->get_individual_discounted_price_in_cents($product, $rule['inc_tax'], false);
$product_price = ($rule['sequentially']) ? $discounted_price : $actual_price; // check if apply_ sequential
$this->actual_price[$product->get_data()['slug']] = wc_remove_number_precision($product_price);
}
// Calculating Discount / Apply rules
if ('percent_product_price' == $rule['type'])
$this->apply_discount_percent_product_price($rule, $product, $price);
else if ('fixed_product_price' == $rule['type'])
$this->apply_discount_fixed_product_price($rule, $product, $price);
else if ('percent_total_amount' == $rule['type'])
$this->apply_discount_percent_total_amount($rule, $product, $price);
else if ('fixed_cart_amount' == $rule['type'])
$this->apply_discount_fixed_price_total_amount($rule, $product, $price);
else if ('cart_quantity' == $rule['type'])
$this->apply_discount_cart_quantity($rule, $product, $price);
}
$_discounts = array();
if (false == $this->awdp_cart_rules) {
foreach ($this->discounts as $discounts) {
if ($discounts['discount_type'] == 'percent_product_price' || $discounts['discount_type'] == 'fixed_product_price') {
if (array_key_exists('discounts', $discounts)) {
if (!array_key_exists('type', $discounts['discounts'])) {
foreach ($discounts['discounts'] as $key => $discount) {
if (!isset($_discounts[$key])) {
$_discounts[$key] = 0.0;
}
if ($discount != '')
$_discounts[$key] += $discount;
}
}
}
}
}
}
if (true == $this->awdp_cart_rules || !isset($_discounts[$product->get_data()['slug']]))
$latest_price = $price;
else if ($price >= wc_remove_number_precision($_discounts[$product->get_data()['slug']]))
$latest_price = $price - wc_remove_number_precision($_discounts[$product->get_data()['slug']]);
else
$latest_price = 0;
return $latest_price;
}
// Rules
public function load_rules()
{
if ($this->discount_rules === false) {
// Get wordpress timezone settings
$gmt_offset = get_option('gmt_offset');
$timezone_string = get_option('timezone_string');
if ($timezone_string) {
$datenow = new DateTime(current_time('mysql'), new DateTimeZone($timezone_string));
} else {
$min = 60 * get_option('gmt_offset');
$sign = $min < 0 ? "-" : "+";
$absmin = abs($min);
$tz = sprintf("%s%02d%02d", $sign, $absmin / 60, $absmin % 60);
$datenow = new DateTime(current_time('mysql'), new DateTimeZone($tz));
}
// Converting to UTC+000 (moment isoString timezone)
$datenow->setTimezone(new DateTimeZone('+000'));
$datenow = $datenow->format('Y-m-d H:i:s');
$stop_date = date('Y-m-d H:i:s', strtotime($datenow . ' +1 day'));
$day = date("l");
$awdp_discount_args = array(
'post_type' => AWDP_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'discount_priority',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'discount_status',
'value' => 1,
'compare' => '=',
'type' => 'NUMERIC'
),
array(
'key' => 'discount_start_date',
'value' => $datenow,
'compare' => '<=',
'type' => 'DATETIME'
),
array(
'relation' => 'OR',
array(
'key' => 'discount_type',
'value' => 'cart_quantity',
'compare' => '='
),
array(
'key' => 'discount_value',
'value' => '',
'compare' => '!='
),
),
array(
'relation' => 'OR',
array(
'key' => 'discount_end_date',
'value' => $datenow,
'compare' => '>=',
'type' => 'DATETIME'
),
array(
'key' => 'discount_end_date',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'discount_end_date',
'value' => '',
'compare' => '=',
),
)
)
);
$awdp_discount_rules = get_posts($awdp_discount_args);
$discount_rules = $check_rules = array();
if ($awdp_discount_rules) {
foreach ($awdp_discount_rules as $rule) {
$schedules = unserialize(get_post_meta($rule->ID, 'discount_schedules', true));
foreach ($schedules as $schedule) {
$mn_start_time = date('H:i', strtotime($schedule['start_date']));
$mn_end_time = date('H:i', strtotime($schedule['end_date']));
$current_time = strtotime(gmdate('H:i'));
$awdp_start_date = $schedule['start_date'];
$awdp_end_start = $schedule['end_date'] ? $schedule['end_date'] : $stop_date;
if (($awdp_start_date <= $datenow) && ($awdp_end_start >= $datenow) && !in_array($rule->ID, $check_rules)) {
$rule_type = get_post_meta($rule->ID, 'discount_type', true);
$discount_config = get_post_meta($rule->ID, 'discount_config', true);
$check_rules[] = $rule->ID; // remove repeated entry - single rule
$discount_rules[] = array(
'id' => $rule->ID,
'priority' => get_post_meta($rule->ID, 'discount_priority', true),
'label' => ($discount_config['label'] != '') ? $discount_config['label'] : (get_option('awdp_fee_label') ? get_option('awdp_fee_label') : $rule->post_title),
'discount' => get_post_meta($rule->ID, 'discount_value', true),
'inc_tax' => $discount_config['inc_tax'],
'disable_on_sale' => $discount_config['disable_on_sale'],
'sequentially' => $discount_config['sequentially'],
'product_list' => get_post_meta($rule->ID, 'discount_product_list', true),
'rules' => unserialize(base64_decode($discount_config['rules'])),
'type' => $rule_type,
'quantity_rules' => unserialize(get_post_meta($rule->ID, 'discount_quantityranges', true)),
'quantity_type' => get_post_meta($rule->ID, 'discount_quantity_type', true),
'pricing_table' => get_post_meta($rule->ID, 'discount_pricing_table', true),
'table_layout' => get_post_meta($rule->ID, 'discount_table_layout', true)
);
}
}
}
}
// Moving Cart based rules to least priority
$cart_rules = [];
foreach ($discount_rules as $key => $val) {
if ('cart_quantity' == $val['type'] || 'fixed_cart_amount' == $val['type'] || 'percent_total_amount' == $val['type']) {
$cart_rules[] = $discount_rules[$key];
unset($discount_rules[$key]);
}
}
$discount_rules = array_merge($discount_rules, $cart_rules);
$discount_rules = array_values($discount_rules);
$this->discount_rules = $discount_rules;
}
}
public function get_items_to_apply_discount($product, $rule)
{
$items = array();
global $woocommerce;
//validate with $rule
if (!$this->check_in_product_list($product, $rule)) {
return false;
}
if (!$this->validate_discount_rules($product, $rule, ['product_price'], $product)) {
return false;
}
if (isset($rule['disable_on_sale']) && $rule['disable_on_sale'] && $product->is_on_sale('edit')) {
return false;
}
return true;
}
public function check_in_product_list($product, $rule)
{
if (0 == $rule['product_list']) {
return true;
} else {
$this->set_product_list();
$pro_id = $product->get_parent_id(); // in case of variation
if ($pro_id == 0) {
$pro_id = $product->get_id();
}
return isset($this->product_lists[$rule['product_list']]) &&
in_array($pro_id, $this->product_lists[$rule['product_list']]);
}
}
// Cart Total Discount ///////////////////////////////
public function set_product_list()
{
if (false == $this->product_lists) {
if (false === ($product_lists = get_transient(AWDP_PRODUCTS_TRANSIENT_KEY))) {
$post_type = AWDP_PRODUCT_LIST;
global $wpdb;
$product_lists = array();
$lists = $wpdb->get_col($wpdb->prepare("
SELECT pm.meta_value FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = '%s'
AND p.post_status = '%s'
AND p.post_type = '%s'
", 'discount_product_list', 'publish', AWDP_POST_TYPE));
$post_ids = get_posts(
array(
'fields' => 'ids',
'post_type' => AWDP_PRODUCT_LIST,
'post__in' => $lists,
'posts_per_page' => -1,
)
);
foreach ($post_ids as $id) {
$list_type = get_post_meta($id, 'list_type', true);
$other_config = get_post_meta($id, 'product_list_config', true);
$product_lists[$id] = array();
if ('products_selection' == $list_type) {
$product_lists[$id] = ($other_config['selectedProducts']);
} else {
$tax_rules = ($other_config['rules']);
$tax_rules = ($tax_rules && is_array($tax_rules) && !empty($tax_rules)) ? $tax_rules : false;
$excludedProducts = ($other_config['excludedProducts']);
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'post__not_in' => $excludedProducts
);
if (false !== $tax_rules) {
if (isset($tax_rules[0]['rules']) && is_array($tax_rules[0]['rules'])) {
$tax_query = array(
'relation' => ('or' == strtolower($other_config['taxRelation'])) ? 'OR' : 'AND'
);
foreach (array_filter($tax_rules[0]['rules']) as $tr) {
$tax_query[] = array(
'taxonomy' => $tr['rule']['item'],
'field' => 'term_id',
'terms' => $tr['rule']['value'],
);
}
$args['tax_query'] = $tax_query;
}
}
$query = new WP_Query($args);
$product_lists[$id] = wp_list_pluck($query->posts, 'ID');
}
}
set_transient(AWDP_PRODUCTS_TRANSIENT_KEY, $product_lists, 7 * 24 * HOUR_IN_SECONDS);
}
$this->product_lists = $product_lists;
}
}
public function get_individual_discounted_price_in_cents($item, $include_tax = true, $sequential = false)
{
$latest_price = '';
if ($include_tax) {
$price = wc_get_price_including_tax($item, array(
'price' => $item->get_data()['price'],
));
} else {
$price = wc_get_price_excluding_tax($item, array(
'price' => $item->get_data()['price'],
));
}
// if($sequential)
// return wc_add_number_precision(abs($price - $this->get_discount($item->get_id(), true)));
// else
return wc_add_number_precision($price);
}
// Quantity based discount /////////////////////////////////
public function apply_discount_percent_product_price($rule, $item, $price)
{
$total_discount = 0;
$cart_total = 0;
global $woocommerce;
$prod_ID = $item->get_data()['slug'];
if (($this->discounted_price[$prod_ID] != '' && $this->discounted_price[$prod_ID] > 0) || $this->discounted_price[$prod_ID] == 0) {
$product_original_price = $this->discounted_price[$prod_ID];
} else {
$product_original_price = wc_add_number_precision($this->actual_price[$prod_ID]);
}
$discount = floor($product_original_price * ($rule['discount'] / 100));
// $discount = min($discounted_price, $discount);
if ($product_original_price >= $discount)
$updated_product_price = $product_original_price - $discount;
else
$updated_product_price = 0;
$this->discounts[$rule['id']]['discounts'][$prod_ID] = $discount;
$this->discounts[$rule['id']]['taxable'] = $rule['inc_tax'];
$this->discounted_price[$prod_ID] = $updated_product_price;
}
// Product Based Discounts ////////////////////////////////
public function apply_discount_fixed_product_price($rule, $item, $price)
{
$prod_ID = $item->get_data()['slug'];
if (($this->discounted_price[$prod_ID] != '' && $this->discounted_price[$prod_ID] > 0) || $this->discounted_price[$prod_ID] == 0) {
$product_original_price = $this->discounted_price[$prod_ID];
} else {
$product_original_price = wc_add_number_precision($this->actual_price[$prod_ID]);
}
$discount_amount = wc_add_number_precision($rule['discount']);
if ($product_original_price >= $discount_amount) {
$updated_product_price = $product_original_price - $discount_amount;
$single_discount_amount = $discount_amount;
} else {
$updated_product_price = 0;
$single_discount_amount = $product_original_price;
}
$this->discounts[$rule['id']]['discounts'][$prod_ID] = $single_discount_amount;
$this->discounts[$rule['id']]['taxable'] = $rule['inc_tax'];
$this->discounted_price[$prod_ID] = $updated_product_price;
}
public function apply_discount_percent_total_amount($rule, $item, $price)
{
$total_discount = 0;
$cart_total = 0;
$prod_ID = $item->get_data()['slug'];
$this->apply_wdp_coupon = true;
if (($this->discounted_price[$prod_ID] != '' && $this->discounted_price[$prod_ID] > 0) || $this->discounted_price[$prod_ID] == 0) {
$price_to_discount = $this->discounted_price[$prod_ID];
} else {
$price_to_discount = wc_add_number_precision($this->actual_price[$prod_ID]);
}
$discount = $price_to_discount * ((int)$rule['discount'] / 100);
$discount = min($price_to_discount, $discount);
// Store code and discount amount per item.
$cart_total = $cart_total + $price_to_discount;
$total_discount = $total_discount + $discount;
// $prod_ID = $item->get_data()['slug'];
// if(!$this->discounts[$rule['id']]['discount_applied'][$prod_ID]) {
$this->discounts[$rule['id']]['discounts'][$prod_ID] = $discount;
$this->discounts[$rule['id']]['taxable'] = $rule['inc_tax'];
// $this->discounts[$rule['id']]['discount_applied'][$prod_ID] = true;
// }
}
/////////////////////////////
public function apply_discount_fixed_price_total_amount($rule, $item, $price)
{
$total_discount = 0;
$cart_total = 0;
$prod_ID = $item->get_data()['slug'];
$this->apply_wdp_coupon = true;
if (($this->discounted_price[$prod_ID] != '' && $this->discounted_price[$prod_ID] > 0) || $this->discounted_price[$prod_ID] == 0) {
$price_to_discount = $this->discounted_price[$prod_ID];
} else {
$price_to_discount = wc_add_number_precision($this->actual_price[$prod_ID]);
}
$discount = wc_add_number_precision($rule['discount']);
if ($this->discounts[$rule['id']]['discount_remainder'] >= 0) {
$discount = $this->discounts[$rule['id']]['discount_remainder'];
}
if (!isset($this->discounts[$rule['id']]['discounts'][$prod_ID])) {
if (intval($price_to_discount) >= $discount && $discount >= 0) {
$discounted_price = $price_to_discount - $discount;
$product_discount = $discount;
$this->discounts[$rule['id']]['discount_remainder'] = 0;
} else if (intval($price_to_discount) < $discount && $discount >= 0) {
$discounted_price = $price_to_discount;
$product_discount = $discounted_price;
$this->discounts[$rule['id']]['discount_remainder'] = $discount - $price_to_discount;
} else {
$product_discount = 0;
}
$this->discounts[$rule['id']]['discounts'][$prod_ID] = $product_discount;
$this->discounts[$rule['id']]['taxable'] = $rule['inc_tax'];
}
}
public function apply_discount_cart_quantity($rule, $item, $price)
{
$quantity_rules = $rule['quantity_rules'];
$quantity_type = $rule['quantity_type'];
$table_layout = $rule['table_layout'];
$prod_ID = $item->get_data()['slug'];
$discount = $table = $tr_qn = $tr_pr = '';
$cart_total = $updated_product_price = 0;
$wdp_cart_totals = 0;
$wdp_cart_items = 0;
$wdp_cart_quantity = 0;
$this->apply_wdp_coupon = true;
$product_lists = $this->product_lists;
$list_id = (array_key_exists('product_list', $rule) && $rule['product_list']) ? $rule['product_list'] : '';
// Checking if Product List is Active / Cart rules Validation
if ( $list_id && $product_lists[$list_id] && isset ( WC()->cart ) && WC()->cart->get_cart_contents_count() > 0 ) {
$applicable_products = $product_lists[$list_id];
$cart_items = WC()->cart->get_cart();
if ($cart_items) {
foreach ($cart_items as $cart_item) {
if (in_array($cart_item['product_id'], $applicable_products)) {
if ($this->validate_discount_rules($cart_item, $rule, ['cart_total_amount', 'product_price'], $cart_item, true)) {
$product_data = $cart_item['data']->get_data();
$wdp_cart_totals = $wdp_cart_totals + $product_data['price'] * $cart_item['quantity'];
$wdp_cart_items = $wdp_cart_items + $cart_item['quantity'];
$wdp_cart_quantity = $wdp_cart_quantity + 1;
}
}
}
}
} else if ( isset ( WC()->cart ) && WC()->cart->get_cart_contents_count() > 0 ) { // Cart rules Validation
$cart_items = WC()->cart->get_cart();
if ($cart_items) {
foreach ($cart_items as $cart_item) {
if ($this->validate_discount_rules($cart_item, $rule, ['cart_total_amount', 'product_price'], $cart_item, true)) {
$product_data = $cart_item['data']->get_data();
$wdp_cart_totals = $wdp_cart_totals + $product_data['price'] * $cart_item['quantity'];
$wdp_cart_items = $wdp_cart_items + $cart_item['quantity'];
$wdp_cart_quantity = $wdp_cart_quantity + 1;
}
}
}
}
// End Check
// Get product price
if (($this->discounted_price[$prod_ID] != '' && $this->discounted_price[$prod_ID] > 0) || $this->discounted_price[$prod_ID] == 0) {
$price_to_discount = $this->discounted_price[$prod_ID];
} else {
$price_to_discount = wc_add_number_precision($this->actual_price[$prod_ID]);
}
// Sort
array_multisort(array_column($quantity_rules, "start_range"), SORT_ASC, $quantity_rules);
$last_key = end($quantity_rules);
$max_range = $last_key["start_range"];
// Variable Product
if ($item->is_type('variable')) {
$variations = $item->get_available_variations();
$variation_prices = [];
foreach ($variations as $variation) {
array_push($variation_prices, wc_add_number_precision($variation['display_price']));
}
}
if ( $quantity_type == 'type_cart' && isset ( WC()->cart ) && WC()->cart->get_cart_contents_count() > 0 ) {
foreach ($quantity_rules as $quantity_rule) {
if ($wdp_cart_items >= (int)$quantity_rule['start_range'] && $wdp_cart_items <= (int)$quantity_rule['end_range']) {
$discount_val = $quantity_rule['dis_value'];
$discount_typ = $quantity_rule['dis_type'];
$discount_amt = 0;
if ($discount_typ == 'percentage') {
$discount_amt = $wdp_cart_totals * ($discount_val / 100);
$this->discounts[$rule['id']]['discounts']['type'] = 'percentage';
$this->discounts[$rule['id']]['discounts']['value'] = $discount_val;
} else if ($discount_typ == 'fixed') {
$discount_amt = $discount_val;
$this->discounts[$rule['id']]['discounts']['type'] = 'fixed';
$this->discounts[$rule['id']]['discounts']['value'] = $discount_val;
} else {
$discount_amt = 0;
$this->discounts[$rule['id']]['discounts']['type'] = '';
$this->discounts[$rule['id']]['discounts']['value'] = 0;
}
$this->discounts[$rule['id']]['taxable'] = $rule['inc_tax'];
$cart_total = $wdp_cart_totals - $discount_amt;
$cart_fee = $discount_amt;
} else if ($wdp_cart_items >= $max_range) {
$discount_val = $last_key['dis_value'];
$discount_typ = $last_key['dis_type'];
$discount_amt = 0;
if ($discount_typ == 'percentage') {
$discount_amt = $wdp_cart_totals * ($discount_val / 100);
$this->discounts[$rule['id']]['discounts']['type'] = 'percentage';
$this->discounts[$rule['id']]['discounts']['value'] = $discount_val;
} else if ($discount_typ == 'fixed') {
$discount_amt = $discount_val;
$this->discounts[$rule['id']]['discounts']['type'] = 'fixed';
$this->discounts[$rule['id']]['discounts']['value'] = $discount_val;
} else {
$discount_amt = 0;
$this->discounts[$rule['id']]['discounts']['type'] = '';
$this->discounts[$rule['id']]['discounts']['value'] = 0;
}
$this->discounts[$rule['id']]['taxable'] = $rule['inc_tax'];
$cart_total = $wdp_cart_totals - $discount_amt;
$cart_fee = $discount_amt;
}
}
if ($cart_total > 0) {
$this->wdpCartDicount = $discount_amt;
}
} else if ( $quantity_type == 'type_product' ) { // product quantity
if (WC()->cart) {
$cart_contents = WC()->cart->get_cart();
} else {
$cart_contents = [];
}
$prod_QNT = [];
$item_id = $item->get_ID();
if ($cart_contents) {
foreach ($cart_contents as $cart_content) {
$cart_id = $cart_content['data']->get_ID();
if ($item_id == $cart_id)
$prod_QNT[$cart_content['data']->get_data()['slug']] = $cart_content['quantity'];
}
}
$awdp_pc_title = get_option('awdp_pc_title') ? get_option('awdp_pc_title') : __("Quantity Discounts", "aco-woo-dynamic-pricing");
$awdp_pc_label = get_option('awdp_pc_label') ? get_option('awdp_pc_label') : __("Price", "aco-woo-dynamic-pricing");
$awdp_qn_label = get_option('awdp_qn_label') ? get_option('awdp_qn_label') : __("Quantity", "aco-woo-dynamic-pricing");
if ($table_layout == 'horizontal') {
$table = '
' . $awdp_pc_title . '
';
$tr_qn = '| ' . $awdp_qn_label . ' | ';
$tr_pr = '
| ' . $awdp_pc_label . ' | ';
} else {
$table = '' . $awdp_pc_title . '
| ' . $awdp_qn_label . ' | ' . $awdp_pc_label . ' |
';
}
foreach ($quantity_rules as $quantity_rule) {
$discount_val = $quantity_rule['dis_value'];
$discount_typ = $quantity_rule['dis_type'];
// $discount = '';
if (array_key_exists($prod_ID, $prod_QNT)) {
if ($prod_QNT[$prod_ID] >= $quantity_rule['start_range'] && $prod_QNT[$prod_ID] <= $quantity_rule['end_range']) {
if ($discount_typ == 'percentage') {
$discount = $price_to_discount * ((int)$discount_val / 100);
$discount = min($price_to_discount, $discount);
} else if ($discount_typ == 'fixed') {
$discount = wc_add_number_precision($discount_val);
}
} else if ($prod_QNT[$prod_ID] >= $max_range) {
$discount_val_max = $last_key['dis_value'];
$discount_typ_max = $last_key['dis_type'];
if ($discount_typ_max == 'percentage') {
$discount = $price_to_discount * ((int)$discount_val_max / 100);
$discount = min($price_to_discount, $discount);
} else if ($discount_typ_max == 'fixed') {
$discount = wc_add_number_precision($discount_val_max);
}
}
}
// Currency conversion rate
if( $this->converted_rate == '' && $item->get_ID() != '' ) {
$this->converted_rate = $this->get_con_unit($item, wc_remove_number_precision($this->discounted_price[$prod_ID]), true);
}
// Pricing Table Calculations
if ($item->is_type('variable')) {
// Variation Pricing Table
$price_to_discount_max = max($variation_prices);
$price_to_discount_min = min($variation_prices);
if ($discount_typ == 'percentage') {
$discount_max_value = max($variation_prices) * ((int)$discount_val / 100);
$discount_min_value = min($variation_prices) * ((int)$discount_val / 100);
// $discount_max_value = min($price_to_discount, $discount_pt);
} else if ($discount_typ == 'fixed') {
$discount_max_value = wc_add_number_precision($discount_val);
$discount_min_value = wc_add_number_precision($discount_val);
}
$discounted_new_max_price = (($price_to_discount_max - $discount_max_value) > 0) ? wc_price ( wc_remove_number_precision ( $price_to_discount_max - $discount_max_value ) * $this->converted_rate ) : 0;
$discounted_new_min_price = (($price_to_discount_min - $discount_min_value) > 0) ? wc_price ( wc_remove_number_precision ( $price_to_discount_min - $discount_min_value ) * $this->converted_rate ) : 0;
if ($table_layout == 'horizontal') {
if ($quantity_rule['start_range'] == $quantity_rule['end_range']) {
$tr_qn .= '' . $quantity_rule['start_range'] . ' | ';
} else if ($quantity_rule['end_range']) {
$tr_qn .= '' . $quantity_rule['start_range'] . ' - ' . $quantity_rule['end_range'] . ' | ';
} else {
$tr_qn .= '' . $quantity_rule['start_range'] . ' + | ';
}
if ($discounted_new_min_price == $discounted_new_max_price) {
$tr_pr .= '' . $discounted_new_min_price . ' | ';
} else {
$tr_pr .= '' . $discounted_new_min_price . ' - ' . $discounted_new_max_price . ' | ';
}
} else {
if ($quantity_rule['start_range'] == $quantity_rule['end_range']) {
$table .= '';
$table .= '| ' . $quantity_rule['start_range'] . ' | ';
if ($discounted_new_min_price == $discounted_new_max_price) {
$table .= '' . $discounted_new_min_price . ' | ';
} else {
$table .= '' . $discounted_new_min_price . ' - ' . $discounted_new_max_price . ' | ';
}
$table .= '
';
} else if ($quantity_rule['end_range']) {
$table .= '';
$table .= '| ' . $quantity_rule['start_range'] . ' - ' . $quantity_rule['end_range'] . ' | ';
if ($discounted_new_min_price == $discounted_new_max_price) {
$table .= '' . $discounted_new_min_price . ' | ';
} else {
$table .= '' . $discounted_new_min_price . ' - ' . $discounted_new_max_price . ' | ';
}
$table .= '
';
} else {
$table .= '';
$table .= '| ' . $quantity_rule['start_range'] . ' + | ';
if ($discounted_new_min_price == $discounted_new_max_price) {
$table .= '' . $discounted_new_min_price . ' | ';
} else {
$table .= '' . $discounted_new_min_price . ' - ' . $discounted_new_max_price . ' | ';
}
$table .= '
';
}
}
// End
} else {
if ($discount_typ == 'percentage') {
$discount_pt = $price_to_discount * ((int)$discount_val / 100);
$discount_pt = min($price_to_discount, $discount_pt);
} else if ($discount_typ == 'fixed') {
$discount_pt = wc_add_number_precision($discount_val);
}
$discounted_new_price = (($price_to_discount - $discount_pt) > 0) ? wc_price ( wc_remove_number_precision ( $price_to_discount - $discount_pt ) * $this->converted_rate ) : 0;
if ($table_layout == 'horizontal') {
if ($quantity_rule['start_range'] == $quantity_rule['end_range']) {
$tr_qn .= '' . $quantity_rule['start_range'] . ' | ';
} else if ($quantity_rule['end_range']) {
$tr_qn .= '' . $quantity_rule['start_range'] . ' - ' . $quantity_rule['end_range'] . ' | ';
} else {
$tr_qn .= '' . $quantity_rule['start_range'] . ' + | ';
}
$tr_pr .= '' . $discounted_new_price . ' | ';
} else {
if ($quantity_rule['start_range'] == $quantity_rule['end_range']) {
$table .= '| ' . $quantity_rule['start_range'] . ' | ' . $discounted_new_price . ' |
';
} else if ($quantity_rule['end_range']) {
$table .= '| ' . $quantity_rule['start_range'] . ' - ' . $quantity_rule['end_range'] . ' | ' . $discounted_new_price . ' |
';
} else {
$table .= '| ' . $quantity_rule['start_range'] . ' + | ' . $discounted_new_price . ' |
';
}
}
}
// End PT
}
if ($table_layout == 'horizontal') {
$tr_qn .= '';
$tr_pr .= '';
$table .= $tr_qn . $tr_pr . '
';
} else {
$table .= '
';
}
// Pricinig Table
if ($rule['pricing_table'] == 1) $this->pricing_table[$item->get_id()] = $table;
if (array_key_exists($prod_ID, $prod_QNT) && $this->validate_discount_rules($item, $rule, ['cart_total_amount', 'product_price'], $item, true)) {
$this->discounts[$rule['id']]['discounts'][$prod_ID] = $discount;
$this->discounts[$rule['id']]['taxable'] = $rule['inc_tax'];
if ($price_to_discount >= $discount && $discount != '') {
$updated_product_price = $price_to_discount - $discount;
} else {
$updated_product_price = $price_to_discount;
}
// $this->discounted_price[$prod_ID] = $updated_product_price; // changed cart discount to discount coupon
}
}
}
public function get_discount($key, $in_cents = false)
{
$item_discount_totals = $this->get_discounts_by_item($in_cents);
return isset($item_discount_totals[$key]) ? $item_discount_totals[$key] : 0;
}
public function get_discounts_by_item($in_cents = false)
{
$discounts = $this->discounts;
$item_discount_totals = array();
foreach ($discounts as $item_discounts) {
if ($item_discounts['discounts']) {
foreach ($item_discounts['discounts'] as $item_key => $item_discount) {
if (!isset($item_discount_totals[$item_key])) {
$item_discount_totals[$item_key] = 0.0;
}
$item_discount_totals[$item_key] += $item_discount;
}
}
}
return $in_cents ? $item_discount_totals : $item_discount_totals;
}
public function addVirtualCoupon($response, $curr_coupon_code)
{
if ( $this->discounts && WC()->cart ) {
global $woocommerce;
$cart_contents = $woocommerce->cart->get_cart();
$prod_QNT = [];
$total = 0;
$ct_total = $this->wdpCartDicount;
$label = get_option('awdp_fee_label') ? get_option('awdp_fee_label') : 'Discount';
$this->couponLabel = $label;
// $cart_contents = $cart_obj->get_cart();
foreach ($cart_contents as $cart_content) {
$prod_QNT[$cart_content['data']->get_data()['slug']] = $cart_content['quantity'];
// $ct_total = $ct_total + ($cart_content['data']->get_price() * $cart_content['quantity']);
}
foreach ($this->discounts as $ruleid => $discounts) {
$discount_type = $discounts['discount_type'];
// $label = $discounts['label'];
// $this->couponLabel = $discounts['label'];
// if ( $discounts['label'] == $curr_coupon_code || strtolower ( $discounts['label'] ) == strtolower ( $curr_coupon_code ) ) {
if ($label == $curr_coupon_code || strtolower($label) == strtolower($curr_coupon_code)) {
if ($discount_type == 'percent_total_amount' || $discount_type == 'fixed_cart_amount' || (true == $this->awdp_cart_rules && $discount_type != 'cart_quantity')) {
if (array_key_exists('discounts', $discounts)) {
foreach ($discounts['discounts'] as $key => $discount) {
if ($discount != '') {
if ($discount_type == 'fixed_cart_amount') {
$total = $total + (wc_remove_number_precision($discount));
} else {
$total = $total + (wc_remove_number_precision($discount) * $prod_QNT[$key]);
}
}
}
}
} else if ($discounts['discount_type'] == 'cart_quantity') {
if (isset($discounts['discounts']) && array_key_exists('type', $discounts['discounts'])) {
// if ( $discounts['discounts']['type'] == 'percentage') {
// // Apply cart discount
// $total = $total + ( $ct_total * ( $discounts['discounts']['value'] / 100 ) );
// } else if( $discounts['discounts']['type'] == 'fixed') {
// $total = $total + $discounts['discounts']['value'];
// }
$total = $total + $ct_total;
} else if (isset($discounts) && array_key_exists('discounts', $discounts)) {
foreach ($discounts['discounts'] as $key => $discount) {
if ($discount != '') {
if ($discounts['discount_type'] == 'fixed_cart_amount') {
$total = $total + (wc_remove_number_precision($discount));
} else {
$total = $total + (wc_remove_number_precision($discount) * $prod_QNT[$key]);
}
}
}
}
}
}
}
if ($total > 0) {
if (!$discount_type) return false;
$coupon_array = array(
'code' => strtolower($label),
'id' => 99999999 + rand(1000, 9999),
'amount' => $total,
'individual_use' => false,
'product_ids' => array(),
'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' => '',
'discount_type' => $discount_type,
);
if (!defined('AWDP_CART_NOTICE') && get_option('awdp_message_status') == 1
&& !isset($_POST['update_cart']) && !is_checkout()) {
wc_clear_notices(); // Clear Woocommerce notices
define('AWDP_CART_NOTICE', true);
$notice = (get_option('awdp_message_status') == 1) ? (get_option('awdp_discount_message') ? str_replace('[label]', $label, get_option('awdp_discount_message')) : (('discount' == strtolower($label)) ? __($label . " has been applied!", "woocommerce") : __("Discount '" . $label . "' has been applied!", "woocommerce"))) : (('discount' == strtolower($label)) ? __($label . " has been applied!", "woocommerce") : __("Discount '" . $label . "' has been applied!", "woocommerce"));
if (false === wc_has_notice($notice, "notice")) {
wc_add_notice($notice, "notice");
}
}
return $coupon_array;
}
}
return $response;
}
// Fee Changed to Coupon
// public function show_discounts($cart_obj)
// {
// if (is_admin() && !defined('DOING_AJAX'))
// return;
// $cart_contents = $cart_obj->get_cart();
// $prod_QNT = [];
// foreach($cart_contents as $cart_content){
// $prod_QNT[$cart_content['data']->get_data()['slug']] = $cart_content['quantity'];
// }
// global $woocommerce;
// $_discounts = array();
// foreach ($this->discounts as $discounts) {
// $label = $discounts['label'];
// if ( $discounts['discount_type'] == 'percent_total_amount' || $discounts['discount_type'] == 'fixed_cart_amount' || ( true == $this->awdp_cart_rules && $discounts['discount_type'] != 'cart_quantity' ) ) {
// $total = 0;
// if(array_key_exists('discounts', $discounts)) {
// foreach ($discounts['discounts'] as $key => $discount) {
// if ( $discount != '' ) {
// if($discounts['discount_type'] == 'fixed_cart_amount') {
// $total = $total + ( wc_remove_number_precision($discount) );
// } else {
// $total = $total + ( wc_remove_number_precision($discount) * $prod_QNT[$key] );
// }
// }
// }
// if ( $total > 0 ) {
// // $total
// // tax_calculation -> price - ( price / ( ( tax_rate_% / 100 ) + 1 ) )
// // $_tax = new WC_Tax();
// // $exclusive_tax = ( get_option( 'woocommerce_prices_include_tax' ) == 'no' ) ? true : false;
// // if( true == $discounts['taxable'] && $exclusive_tax){
// // // $tax_percentage = round( reset( WC_Tax::get_rates() )['rate'] )
// // } else {
// // }
// // $fee = array(
// // 'id' => '_shipping_rebate',
// // 'name' => __( $discounts['label'] ),
// // 'amount' => (float) - 1 * $total,
// // 'taxable' => false,
// // 'tax_class' => '',
// // );
// // wc()->cart->fees_api()->add_fee( $fee );
// $woocommerce->cart->add_fee($label, $total * -1, false, 'Zero Rate');
// // $woocommerce->cart->add_discount('discount');
// // Discount Notice
// // wc_clear_notices(); // Clear
// // wc_add_notice( __("Discount '".$discounts['label']."' has been Applied!", "woocommerce"), "notice");
// }
// }
// } else if ( $discounts['discount_type'] == 'cart_quantity' ) {
// $total = 0;
// if( isset($discounts['discounts']) && array_key_exists('type', $discounts['discounts']) ) {
// if ( $discounts['discounts']['type'] == 'percentage') {
// $cart_discount = $cart_obj->cart_contents_total * ( $discounts['discounts']['value'] / 100 );
// } else if( $discounts['discounts']['type'] == 'fixed') {
// $cart_discount = $discounts['discounts']['value'];
// } else {
// $cart_discount = 0;
// }
// if ( $cart_discount > 0 ) {
// $woocommerce->cart->add_fee($label, $cart_discount * -1, false, 'Zero Rate');
// // Discount Notice
// // wc_add_notice( __("Discount '".$discounts['label']."' has been Applied!", "woocommerce"), "notice");
// }
// } else if ( isset($discounts) && array_key_exists('discounts', $discounts) ) {
// foreach ( $discounts['discounts'] as $key => $discount ) {
// if ( $discount != '' ) {
// if ( $discounts['discount_type'] == 'fixed_cart_amount') {
// $total = $total + ( wc_remove_number_precision($discount) );
// } else {
// $total = $total + ( wc_remove_number_precision($discount) * $prod_QNT[$key] );
// }
// }
// }
// if ( $total > 0 ) {
// $woocommerce->cart->add_fee($label, $total * -1, false, 'Zero Rate');
// // Discount Notice
// // wc_add_notice( __("Discount '".$discounts['label']."' has been Applied!", "woocommerce"), "notice");
// }
// }
// }
// }
// }
// Create virtual coupon
public function couponLabel($label, $coupon)
{
if ($coupon) {
$coupon_label = $this->couponLabel;
$code = $coupon->get_code();
if ($code == $coupon_label || strtolower($code) == strtolower($coupon_label)) {
return ucfirst($coupon_label);
}
}
return $label;
}
// Change discount coupon label
public function applyFakeCoupons()
{
global $woocommerce; //apply_filters('woocommerce_applied_coupon');
$coupon = get_option('awdp_fee_label') ? get_option('awdp_fee_label') : 'Discount';
$coupon_code = apply_filters('woocommerce_coupon_code', $coupon);
if ( !in_array($coupon_code, $woocommerce->cart->get_applied_coupons()) && $this->discounts && true == $this->apply_wdp_coupon && WC()->cart ) {
$coupons_obj = new WC_Coupon($coupon_code);
$coupons_amount = $coupons_obj->get_amount();
if ($coupons_amount > 0) {
$woocommerce->cart->add_discount($coupon_code);
// wc_clear_notices(); // Clear Woocommerce notices
}
} else if ( in_array($coupon_code, $woocommerce->cart->get_applied_coupons()) ) {
$coupons_obj = new WC_Coupon($coupon_code);
$coupons_amount = $coupons_obj->get_amount();
if ($coupons_amount == 0) {
WC()->cart->remove_coupon($coupon_code);
// wc_clear_notices(); // Clear Woocommerce notices
}
}
$applied_coupons = WC()->cart->get_applied_coupons();
return true;
}
// Apply coupon
/**
* Cloning is forbidden.
*
* @since 1.0.0
*/
public function __clone()
{
_doing_it_wrong(__FUNCTION__, __('Cheatin’ huh?'), $this->_version);
}
// End Coupons
/**
* Unserializing instances of this class is forbidden.
*
* @since 1.0.0
*/
public function __wakeup()
{
_doing_it_wrong(__FUNCTION__, __('Cheatin’ huh?'), $this->_version);
}
protected function apply_discount_remainder($rule, $items_to_apply, $amount)
{
$total_discount = 0;
foreach ($items_to_apply as $item) {
for ($i = 0; $i < $item->quantity; $i++) {
// Find out how much price is available to discount for the item.
$discounted_price = $this->get_discounted_price_in_cents($item);
// $price_to_discount = (false) ? $discounted_price : $item->price;// check if apply_ sequential
$discount = min($discounted_price, 1);
// Store totals.
$total_discount += $discount;
// Store code and discount amount per item.
$this->discounts[$rule['id']]['discounts'][$item->key] += $discount;
if ($total_discount >= $amount) {
break 2;
}
}
if ($total_discount >= $amount) {
break;
}
}
return $total_discount;
}
public function get_discounted_price_in_cents($item, $include_tax = true, $sequential = false)
{
$actual_price = $item->get_data()['price'];
if ($include_tax) {
$price = wc_get_price_including_tax($item, array(
'price' => $actual_price,
));
} else {
$price = wc_get_price_excluding_tax($item, array(
'price' => $actual_price,
));
}
// if($sequential)
// return abs($price - wc_remove_number_precision($this->get_discount($item->get_id(), true)));
// else
return $price;
}
}