public function check_install()
 {
     if (!defined('IFRAME_REQUEST') && get_option('wc_dynamic_pricing_db_version') !== WC_Dynamic_Pricing::instance()->db_version) {
         $this->do_update();
         update_option('wc_dynamic_pricing_db_version', WC_Dynamic_Pricing::instance()->db_version);
     }
 }
 public function adjust_cart($temp_cart)
 {
     $num_decimals = apply_filters('woocommerce_dynamic_pricing_get_decimals', (int) get_option('woocommerce_price_num_decimals'));
     if ($this->adjustment_sets && count($this->adjustment_sets)) {
         foreach ($this->adjustment_sets as $set_id => $set) {
             $q = $this->get_cart_total($set);
             $matched = false;
             $pricing_rules = $set->pricing_rules;
             $is_valid_for_user = $set->is_valid_for_user();
             $collector = $set->get_collector();
             $targets = $set->targets;
             if ($is_valid_for_user && is_array($pricing_rules) && sizeof($pricing_rules) > 0) {
                 foreach ($pricing_rules as $rule) {
                     if ($rule['from'] == '*') {
                         $rule['from'] = 0;
                     }
                     if (empty($rule['to']) || $rule['to'] == '*') {
                         $rule['to'] = $q;
                     }
                     if ($q >= $rule['from'] && $q <= $rule['to']) {
                         $matched = true;
                         //Adjust the cart items.
                         foreach ($temp_cart as $cart_item_key => $cart_item) {
                             if ($collector['type'] == 'cat') {
                                 $process_discounts = false;
                                 $terms = wp_get_post_terms($cart_item['product_id'], 'product_cat', array('fields' => 'ids'));
                                 if (count(array_intersect($targets, $terms)) > 0) {
                                     $process_discounts = apply_filters('woocommerce_dynamic_pricing_process_product_discounts', true, $cart_item['data'], 'advanced_totals', $this);
                                 }
                             } else {
                                 $process_discounts = apply_filters('woocommerce_dynamic_pricing_process_product_discounts', true, $cart_item['data'], 'advanced_totals', $this);
                             }
                             if (!$process_discounts) {
                                 continue;
                             }
                             if (!$this->is_cumulative($cart_item, $cart_item_key)) {
                                 if ($this->is_item_discounted($cart_item, $cart_item_key)) {
                                     continue;
                                 }
                             }
                             $original_price = $this->get_price_to_discount($cart_item, $cart_item_key);
                             if ($original_price) {
                                 $amount = apply_filters('woocommerce_dynamic_pricing_get_rule_amount', $rule['amount'], $rule, $cart_item, $this);
                                 if ($amount > 1) {
                                     $amount = $amount / 100;
                                 }
                                 $price_adjusted = round(floatval($original_price) - floatval($amount) * $original_price, (int) $num_decimals);
                                 WC_Dynamic_Pricing::apply_cart_item_adjustment($cart_item_key, $original_price, $price_adjusted, $this->module_id, $set_id);
                             }
                         }
                     }
                 }
             }
             //Only process the first matched rule set
             if ($matched) {
                 return;
             }
         }
     }
 }
function woocommerce_gravityforms_get_updated_price()
{
    global $woocommerce;
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-type: application/json');
    $variation_id = isset($_POST['variation_id']) ? $_POST['variation_id'] : '';
    $product_id = isset($_POST['product_id']) ? $_POST['product_id'] : 0;
    $gform_total = isset($_POST['gform_total']) ? $_POST['gform_total'] : 0;
    $product_data = null;
    if (function_exists('get_product')) {
        $product_data = get_product($variation_id > 0 ? $variation_id : $product_id);
    } else {
        if ($variation_id > 0) {
            $product_data = new WC_Product_Variation($variation_id);
        } else {
            $product_data = new WC_Product($product_id);
        }
    }
    $discount_price = false;
    $gforms_discount_price = false;
    $base_price = $product_data->get_price();
    if (class_exists('WC_Dynamic_Pricing')) {
        $working_price = $base_price;
        $dynamic_pricing = WC_Dynamic_Pricing::instance();
        foreach ($dynamic_pricing->modules as $module) {
            if ($module->module_type == 'simple') {
                //Make sure we are using the price that was just discounted.
                $working_price = $discount_price ? $discount_price : $base_price;
                $working_price = $module->get_product_working_price($working_price, $product_data);
                if (floatval($working_price)) {
                    $discount_price = $module->get_discounted_price_for_shop($product_data, $working_price);
                }
            }
        }
        $gforms_base_price = $base_price + $gform_total;
        $gforms_working_price = $base_price + $gform_total;
        foreach ($dynamic_pricing->modules as $module) {
            if ($module->module_type == 'simple') {
                //Make sure we are using the price that was just discounted.
                $gforms_working_price = $gforms_discount_price ? $gforms_discount_price : $gforms_base_price;
                $gforms_working_price = $module->get_product_working_price($gforms_working_price, $product_data);
                if (floatval($gforms_working_price)) {
                    $gforms_discount_price = $module->get_discounted_price_for_shop($product_data, $gforms_working_price);
                }
            }
        }
    }
    $price = $discount_price ? $discount_price : $base_price;
    $gform_final_total = $gforms_discount_price ? $gforms_discount_price : $price + $gform_total;
    $result = array('formattedBasePrice' => apply_filters('woocommerce_gform_base_price', woocommerce_price($price), $product_data), 'formattedTotalPrice' => apply_filters('woocommerce_gform_total_price', woocommerce_price($gform_final_total), $product_data), 'formattedVariationTotal' => apply_filters('woocommerce_gform_variation_total_price', woocommerce_price($gform_total), $product_data));
    echo json_encode($result);
    die;
}
 public function enqueue($hook)
 {
     global $post, $woocommerce;
     if ($hook == 'woocommerce_page_wc_dynamic_pricing' || $post && $post->post_type == 'product') {
         if (floatval($woocommerce->version) >= 2.0) {
             wp_enqueue_style('woocommerce-pricing-admin', WC_Dynamic_Pricing::plugin_url() . '/assets/admin/admin.css');
             wp_enqueue_script('woocommerce-pricing-admin', WC_Dynamic_Pricing::plugin_url() . '/assets/admin/admin.js', array('jquery', 'jquery-ui-datepicker'));
         } else {
             wp_enqueue_style('woocommerce-pricing-admin', WC_Dynamic_Pricing::plugin_url() . '/assets/legacy/admin/admin.css');
             wp_enqueue_script('woocommerce-pricing-admin', WC_Dynamic_Pricing::plugin_url() . '/assets/legacy/admin/admin.js', array('jquery'));
         }
         wp_localize_script('woocommerce-pricing-admin', 'woocommerce_pricing_admin', array('calendar_image' => $woocommerce->plugin_url() . '/assets/images/calendar.png'));
         // Enqueue jQuery UI styles
         $jquery_version = isset($wp_scripts->registered['jquery-ui-core']->ver) ? $wp_scripts->registered['jquery-ui-core']->ver : '1.9.2';
         wp_enqueue_style('jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/' . $jquery_version . '/themes/smoothness/jquery-ui.css');
     }
 }
 public function adjust_cart($temp_cart)
 {
     foreach ($temp_cart as $cart_item_key => $values) {
         $temp_cart[$cart_item_key] = $values;
         $temp_cart[$cart_item_key]['available_quantity'] = $values['quantity'];
     }
     foreach ($temp_cart as $cart_item_key => $cart_item) {
         $process_discounts = apply_filters('woocommerce_dynamic_pricing_process_product_discounts', true, $cart_item['data'], 'advanced_product', $this, $cart_item);
         if (!$process_discounts) {
             continue;
         }
         if (!$this->is_cumulative($cart_item, $cart_item_key)) {
             if ($this->is_item_discounted($cart_item, $cart_item_key)) {
                 continue;
             }
         }
         $product_adjustment_sets = $this->get_pricing_rule_sets($cart_item);
         if ($product_adjustment_sets && count($product_adjustment_sets)) {
             //Process block discounts first
             foreach ($product_adjustment_sets as $set_id => $set) {
                 if ($set->target_variations && isset($cart_item['variation_id']) && !in_array($cart_item['variation_id'], $set->target_variations)) {
                     continue;
                 }
                 //check if this set is valid for the current user;
                 $is_valid_for_user = $set->is_valid_for_user();
                 if (!$is_valid_for_user) {
                     continue;
                 }
                 $original_price = $this->get_price_to_discount($cart_item, $cart_item_key);
                 if ($original_price) {
                     $price_adjusted = false;
                     if ($set->mode == 'block') {
                         $price_adjusted = $this->get_block_adjusted_price($set, $original_price, $cart_item);
                     } elseif ($set->mode == 'bulk') {
                         $price_adjusted = $this->get_adjusted_price($set, $original_price, $cart_item);
                     }
                     if ($price_adjusted !== false && floatval($original_price) != floatval($price_adjusted)) {
                         WC_Dynamic_Pricing::apply_cart_item_adjustment($cart_item_key, $original_price, $price_adjusted, 'advanced_product', $set_id);
                         break;
                     }
                 }
             }
         }
     }
 }
 public function adjust_cart($cart)
 {
     if ($this->available_rulesets && count($this->available_rulesets)) {
         foreach ($cart as $cart_item_key => $cart_item) {
             $is_applied = apply_filters('woocommerce_dynamic_pricing_is_applied_to_product', $this->is_applied_to_product($cart_item['data']), $this->module_id, $this);
             $process_discounts = apply_filters('woocommerce_dynamic_pricing_process_product_discounts', true, $cart_item['data'], 'groups', $this);
             if (!$process_discounts) {
                 continue;
             }
             if ($is_applied) {
                 if (!$this->is_cumulative($cart_item, $cart_item_key)) {
                     if ($this->is_item_discounted($cart_item, $cart_item_key)) {
                         continue;
                     }
                 }
                 $original_price = $this->get_price_to_discount($cart_item, $cart_item_key);
                 $_product = $cart_item['data'];
                 $price_adjusted = false;
                 $applied_rule = false;
                 $applied_rule_set = false;
                 $applied_rule_set_id;
                 foreach ($this->available_rulesets as $set_id => $pricing_rule_set) {
                     if ($this->is_applied_to_product($_product)) {
                         $rule = $pricing_rule_set;
                         $temp = $this->get_adjusted_price($rule, $original_price);
                         if (!$price_adjusted || $temp < $price_adjusted) {
                             $price_adjusted = $temp;
                             $applied_rule = $rule;
                             $applied_rule_set = $pricing_rule_set;
                             $applied_rule_set_id = $set_id;
                         }
                     }
                 }
                 if ($price_adjusted !== false && floatval($original_price) != floatval($price_adjusted)) {
                     WC_Dynamic_Pricing::apply_cart_item_adjustment($cart_item_key, $original_price, $price_adjusted, $this->module_id, $applied_rule_set_id);
                 }
             }
         }
     }
 }
 public function adjust_cart($temp_cart)
 {
     if ($this->adjustment_sets && count($this->adjustment_sets)) {
         $valid_sets = wp_list_filter($this->adjustment_sets, array('is_valid_rule' => true, 'is_valid_for_user' => true));
         if (empty($valid_sets)) {
             return;
         }
         foreach ($temp_cart as $cart_item_key => $values) {
             $temp_cart[$cart_item_key] = $values;
             $temp_cart[$cart_item_key]['available_quantity'] = $values['quantity'];
         }
         //Process block discounts first
         foreach ($valid_sets as $set_id => $set) {
             if ($set->mode != 'block') {
                 continue;
             }
             //check if this set is valid for the current user;
             $is_valid_for_user = $set->is_valid_for_user();
             if (!$is_valid_for_user) {
                 continue;
             }
             //Lets actuall process the rule.
             //Setup the matching quantity
             $targets = $set->targets;
             $collector = $set->get_collector();
             $q = 0;
             if (isset($collector['args']) && isset($collector['args']['cats']) && is_array($collector['args']['cats'])) {
                 foreach ($collector['args']['cats'] as $cat_id) {
                     $q += WC_Dynamic_Pricing_Counter::get_category_count($cat_id);
                 }
             } else {
                 continue;
                 //no categories
             }
             $rule = reset($set->pricing_rules);
             //block rules can only have one line item.
             if ($q < $rule['from']) {
                 //continue;
             }
             if ($rule['repeating'] == 'yes') {
                 $b = floor($q / $rule['from']);
                 //blocks - this is how many times has the required amount been met.
             } else {
                 $b = 1;
             }
             $ct = 0;
             //clean targets
             $mt = 0;
             $cq = 0;
             //matched clean quantity;
             $mq = 0;
             //matched mixed quantity;
             foreach ($temp_cart as $cart_item_key => &$cart_item) {
                 $terms = wp_get_post_terms($cart_item['product_id'], 'product_cat', array('fields' => 'ids'));
                 if (count(array_intersect($collector['args']['cats'], $terms)) > 0) {
                     if (count(array_intersect($targets, $terms)) > 0) {
                         $mq += $cart_item['available_quantity'];
                     } else {
                         $cq += $cart_item['available_quantity'];
                     }
                 }
                 if (count(array_intersect($targets, $terms)) > 0) {
                     if (count(array_intersect($collector['args']['cats'], $terms)) == 0) {
                         $ct += $cart_item['quantity'];
                     } else {
                         $mt += $cart_item['quantity'];
                     }
                 }
             }
             $rt = $ct + $mt;
             //remaining targets.
             $rcq = $cq;
             //remaining clean quantity
             $rmq = $mq;
             //remaining mixed quantity
             $tt = 0;
             //the total number of items we can discount.
             //for each block reduce the amount of remaining items which can make up a discount by the amount required.
             if ($rcq || $rmq) {
                 for ($x = 0; $x < $b; $x++) {
                     //If the remaining clean quantity minus what is required to make a block is greater than 0 there are more clean quantity items remaining.
                     //This means we don't have to eat into mixed quantities yet.
                     if ($rcq - $rule['from'] >= 0) {
                         $rcq -= $rule['from'];
                         $tt += $rule['adjust'];
                         //If the total items that can be dicsounted is greater than the number of clean items to be discounted, reduce the
                         //mixed quantity by the difference, because those items will be discounted and can not count towards making another discounted item.
                         if ($tt > $ct) {
                             $rmq -= $tt - $ct;
                         }
                         if ($tt > $mt + $ct) {
                             $tt = $mt + $ct;
                         }
                         $rt -= $ct + $mt - $tt;
                     } else {
                         //how many items left over from clean quantities.  if we have a buy two get one free, we may have one quantity of clean item, and two mixed items.
                         $l = $rcq ? $rule['from'] - $rcq : 0;
                         if ($rcq > 0) {
                             //If the remaining mixed quantity minus the left overs trigger items is more than 0, we have another discount available
                             if ($rt - $l > 0) {
                                 $tt += min($rt - $l, $rule['adjust']);
                             }
                             $rt -= $ct + $mt - $tt;
                         } elseif ($rmq > 0) {
                             $rt -= $rule['from'];
                             //$rt -= ($ct + $mt) - $tt;
                             if ($rt > 0) {
                                 $tt += min($rt, $rule['adjust']);
                                 $rt -= min($rt, $rule['adjust']);
                                 $rmq = $rmq - $l - ($rule['adjust'] + $rule['from']);
                             }
                         }
                         $rcq = 0;
                     }
                 }
                 foreach ($temp_cart as $cart_item_key => $ctitem) {
                     $price_adjusted = false;
                     $original_price = $this->get_price_to_discount($ctitem, $cart_item_key);
                     //Check if the original price is free, we don't want to apply any of these discounts, or use any of them up by
                     //applying a discount to a free item.
                     $op_check = floatval($original_price);
                     if (empty($op_check) && $rule['type'] != 'fixed_adjustment') {
                         continue;
                     }
                     $terms = wp_get_post_terms($ctitem['product_id'], 'product_cat', array('fields' => 'ids'));
                     if (count(array_intersect($targets, $terms)) > 0) {
                         $price_adjusted = $this->get_block_adjusted_price($ctitem, $original_price, $rule, $tt);
                         if ($tt > $ctitem['quantity']) {
                             $tt -= $ctitem['quantity'];
                             $temp_cart[$cart_item_key]['available_quantity'] = 0;
                         } else {
                             $temp_cart[$cart_item_key]['available_quantity'] = $ctitem['quantity'] - $tt;
                             $tt = 0;
                         }
                         if ($price_adjusted !== false && floatval($original_price) != floatval($price_adjusted)) {
                             WC_Dynamic_Pricing::apply_cart_item_adjustment($cart_item_key, $original_price, $price_adjusted, 'advanced_category', $set_id);
                         }
                     }
                 }
             }
         }
         //Now process bulk rules
         foreach ($valid_sets as $set_id => $set) {
             if ($set->mode != 'bulk') {
                 continue;
             }
             //check if this set is valid for the current user;
             $is_valid_for_user = $set->is_valid_for_user();
             if (!$is_valid_for_user) {
                 continue;
             }
             //Lets actuall process the rule.
             //Setup the matching quantity
             $targets = $set->targets;
             //Get the quantity to compare
             $collector = $set->get_collector();
             $q = 0;
             foreach ($temp_cart as $t_cart_item_key => $t_cart_item) {
                 $process_discounts = apply_filters('woocommerce_dynamic_pricing_process_product_discounts', true, $t_cart_item['data'], 'advanced_category', $this, $t_cart_item);
                 if (!$process_discounts) {
                     continue;
                 }
                 $terms = wp_get_post_terms($t_cart_item['product_id'], 'product_cat', array('fields' => 'ids'));
                 if (count(array_intersect($targets, $terms)) > 0) {
                     if (!$this->is_cumulative($t_cart_item, $t_cart_item_key)) {
                         if ($this->is_item_discounted($t_cart_item, $t_cart_item_key)) {
                             continue;
                         }
                     }
                     if (isset($collector['type']) && $collector['type'] == 'cat_product') {
                         $q = $t_cart_item['quantity'];
                     } else {
                         $q = 0;
                         if (isset($collector['args']) && isset($collector['args']['cats']) && is_array($collector['args']['cats'])) {
                             foreach ($temp_cart as $lck => $l_cart_item) {
                                 if (is_object_in_term($l_cart_item['product_id'], 'product_cat', $collector['args']['cats'])) {
                                     if (apply_filters('woocommerce_dynamic_pricing_count_categories_for_cart_item', true, $l_cart_item, $lck)) {
                                         $q += (int) $l_cart_item['quantity'];
                                     }
                                 }
                             }
                         }
                     }
                     $price_adjusted = false;
                     $original_price = $this->get_price_to_discount($t_cart_item, $t_cart_item_key);
                     if (is_array($set->pricing_rules) && sizeof($set->pricing_rules) > 0) {
                         foreach ($set->pricing_rules as $rule) {
                             $price_adjusted = $this->get_bulk_adjusted_price($t_cart_item, $original_price, $rule, $q);
                             if ($price_adjusted !== false) {
                                 break;
                             }
                         }
                     }
                     if ($price_adjusted !== false && floatval($original_price) != floatval($price_adjusted)) {
                         WC_Dynamic_Pricing::apply_cart_item_adjustment($t_cart_item_key, $original_price, $price_adjusted, 'advanced_category', $set_id);
                     }
                 }
             }
         }
     }
 }
    private function meta_box_javascript()
    {
        ?>
			<script type="text/javascript">

				jQuery(document).ready(function ($) {
		<?php 
        do_action('woocommerce_dynamic_pricing_metabox_js', 'advanced_category');
        ?>
					var set_index = 0;
					var rule_indexes = new Array();

					$('.woocommerce_pricing_ruleset').each(function () {
						var length = $('table tbody tr', $(this)).length;
						if (length == 1) {
							$('.delete_pricing_rule', $(this)).hide();
						}
					});


					$("#woocommerce-pricing-add-ruleset").click(function (event) {
						event.preventDefault();

						var set_index = $("#woocommerce-pricing-rules-wrap").data('setindex') + 1;
						$("#woocommerce-pricing-rules-wrap").data('setindex', set_index);

						var data = {
							set_index: set_index,
							post:<?php 
        echo isset($_GET['post']) ? $_GET['post'] : 0;
        ?>
,
							action: 'create_empty_category_ruleset'
						}

						$.post(ajaxurl, data, function (response) {
							$('#woocommerce-pricing-rules-wrap').append(response);

						});
					});

					$('#woocommerce-pricing-rules-wrap').delegate('.pricing_rule_apply_to', 'change', function (event) {
						var value = $(this).val();

						if (value != 'roles' && $('.roles', $(this).parent()).is(':visible')) {
							$('.roles', $(this).parent()).fadeOut();
							$('.roles input[type=checkbox]', $(this).closest('div')).removeAttr('checked');
						}

						if (value == 'roles') {
							$('.roles', $(this).parent()).fadeIn();
						}

					});

					$('#woocommerce-pricing-rules-wrap').delegate('.pricing_rule_mode', 'change', function (event) {
						var value = $(this).val();
						if (value != 'block') {
							$('table.block', $(this).closest('div.woocommerce_pricing_ruleset')).parent().fadeOut('fast', function () {
								$('table.continuous', $(this).closest('div.woocommerce_pricing_ruleset')).parent().fadeIn();
							});
						} else {

							$('table.continuous', $(this).closest('div.woocommerce_pricing_ruleset')).parent().fadeOut('fast', function () {
								$('table.block', $(this).closest('div.woocommerce_pricing_ruleset')).parent().fadeIn();
							});
						}
					});

					//Remove Pricing Set
					$('#woocommerce-pricing-rules-wrap').delegate('.delete_pricing_ruleset', 'click', function (event) {
						event.preventDefault();
						DeleteRuleSet($(this).data('name'));
						return false;
					});

					//Add Button
					$('#woocommerce-pricing-rules-wrap').delegate('.add_pricing_rule', 'click', function (event) {
						event.preventDefault();
						InsertContinuousRule($(this).data('index'), $(this).data('name'));
					});

					$('#woocommerce-pricing-rules-wrap').delegate('.add_pricing_blockrule', 'click', function (event) {
						event.preventDefault();
						InsertBlockRule($(this).data('index'), $(this).data('name'));
					});



					//Remove Button                
					$('#woocommerce-pricing-rules-wrap').delegate('.delete_pricing_rule', 'click', function (event) {
						event.preventDefault();
						DeleteRule($(this).data('index'), $(this).data('name'));
					});

					//Remove Button                
					$('#woocommerce-pricing-rules-wrap').delegate('.delete_pricing_blockrule', 'click', function (event) {
						event.preventDefault();
						DeleteBlockRule($(this).closest('tr'), $(this).closest('table'));
					});

					$("#woocommerce-pricing-rules-wrap").sortable(
						{
							handle: 'h4.first',
							containment: 'parent',
							axis: 'y'
						});

					function InsertContinuousRule(previousRowIndex, name) {


						var $index = $("#woocommerce-pricing-rules-table-" + name).data('lastindex') + 1;
						$("#woocommerce-pricing-rules-table-" + name).data('lastindex', $index);

						var html = '';
						html += '<tr id="pricing_rule_row_' + name + '_' + $index + '">';
						html += '<td>';
						html += '<input class="int_pricing_rule" id="pricing_rule_from_input_' + name + '_' + $index + '" type="text" name="pricing_rules[' + name + '][rules][' + $index + '][from]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<input class="int_pricing_rule" id="pricing_rule_to_input_' + name + '_' + $index + '" type="text" name="pricing_rules[' + name + '][rules][' + $index + '][to]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<select id="pricing_rule_type_value_' + name + '_' + $index + '" name="pricing_rules[' + name + '][rules][' + $index + '][type]">';
						html += '<option value="price_discount">Price Discount</option>';
						html += '<option value="percentage_discount">Percentage Discount</option>';
						html += '<option value="fixed_price">Fixed Price</option>';
						html += '</select>';
						html += '</td>';
						html += '<td>';
						html += '<input class="float_pricing_rule" id="pricing_rule_amount_input_' + $index + '" type="text" name="pricing_rules[' + name + '][rules][' + $index + '][amount]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<a data-index="' + $index + '" data-name="' + name + '" class="add_pricing_rule"><img  src="<?php 
        echo WC_Dynamic_Pricing::plugin_url() . '/assets/images/add.png';
        ?>
" title="add another rule" alt="add another rule" style="cursor:pointer; margin:0 3px;" /></a>';
						html += '<a data-index="' + $index + '" data-name="' + name + '" class="delete_pricing_rule"><img data-index="' + $index + '" src="<?php 
        echo WC_Dynamic_Pricing::plugin_url() . '/assets/images/remove.png';
        ?>
" title="remove rule" alt="remove rule" style="cursor:pointer; margin:0 3px;" /></a>';
						html += '</td>';
						html += '</tr>';

						$('#pricing_rule_row_' + name + '_' + previousRowIndex).after(html);
						$('.delete_pricing_rule', "#woocommerce-pricing-rules-table-" + name).show();

					}

					function InsertBlockRule(previousRowIndex, name) {
						var $index = $("#woocommerce-pricing-blockrules-table-" + name).data('lastindex') + 1;
						$("#woocommerce-pricing-blockrules-table-" + name).data('lastindex', $index);

						var html = '';
						html += '<tr id="pricing_blockrule_row_' + name + '_' + $index + '">';
						html += '<td>';
						html += '<input class="int_pricing_blockrule" type="text" name="pricing_rules[' + name + '][blockrules][' + $index + '][from]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<input class="int_pricing_blockrule" type="text" name="pricing_rules[' + name + '][blockrules][' + $index + '][to]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<select name="pricing_rules[' + name + '][blockrules][' + $index + '][type]">';
						html += '<option value="price_discount">Price Discount</option>';
						html += '<option value="percentage_discount">Percentage Discount</option>';
						html += '<option value="fixed_price">Fixed Price</option>';
						html += '</select>';
						html += '</td>';
						html += '<td>';
						html += '<input class="float_pricing_rule" id="pricing_rule_amount_input_' + $index + '" type="text" name="pricing_rules[' + name + '][blockrules][' + $index + '][amount]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<select name="pricing_rules[' + name + '][blockrules][' + $index + '][repeating]">';
						html += '<option value="no">No</option>';
						html += '<option value="yes">Yes</option>';
						html += '</select>';
						html += '</td>';
						html += '<td width="48">';
						html += '<a data-index="' + $index + '" data-name="' + name + '" class="add_pricing_blockrule"><img  src="<?php 
        echo WC_Dynamic_Pricing::plugin_url() . '/assets/images/add.png';
        ?>
" title="add another rule" alt="add another rule" style="cursor:pointer; margin:0 3px;" /></a>';
						html += '<a data-index="' + $index + '" data-name="' + name + '" class="delete_pricing_blockrule"><img data-index="' + $index + '" src="<?php 
        echo WC_Dynamic_Pricing::plugin_url() . '/assets/images/remove.png';
        ?>
" title="remove rule" alt="remove rule" style="cursor:pointer; margin:0 3px;" /></a>';
						html += '</td>';
						html += '</tr>';

						$('#pricing_blockrule_row_' + name + '_' + previousRowIndex).after(html);
						$('.delete_pricing_blockrule', "#woocommerce-pricing-blockrules-table-" + name).show();
					}

					function DeleteRule(index, name) {
						if (confirm("Are you sure you would like to remove this price adjustment?")) {
							$('#pricing_rule_row_' + name + '_' + index).remove();

							var $index = $('tbody tr', "#woocommerce-pricing-rules-table-" + name).length;
							if ($index > 1) {
								$('.delete_pricing_rule', "#woocommerce-pricing-rules-table-" + name).show();
							} else {
								$('.delete_pricing_rule', "#woocommerce-pricing-rules-table-" + name).hide();
							}
						}
					}

					function DeleteBlockRule($tr, $table) {
						if (confirm("Are you sure you would like to remove this price adjustment?")) {
							$tr.remove();

							var count = $('tr', $table).length;
							if (count > 1) {
								$('.delete_pricing_blockrule', $table).show();
							} else {
								$('.delete_pricing_blockrule', $table).hide();
							}
						}
					}

					function DeleteRuleSet(name) {
						if (confirm('Are you sure you would like to remove this dynamic price set?')) {
							$('#woocommerce-pricing-ruleset-' + name).slideUp().remove();
						}

						return false;
					}


				});



			</script>
			<?php 
    }
    private function meta_box_javascript()
    {
        ?>
			<script type="text/javascript">

				jQuery(document).ready(function ($) {
		<?php 
        do_action('woocommerce_dynamic_pricing_metabox_js', 'advanced_totals');
        ?>

					var set_index = 0;
					var rule_indexes = new Array();

					$('.woocommerce_pricing_ruleset').each(function () {
						var length = $('table tbody tr', $(this)).length;
						if (length == 1) {
							$('.delete_pricing_rule', $(this)).hide();
						}
					});


					$("#woocommerce-pricing-add-ruleset").click(function (event) {
						event.preventDefault();

						var set_index = $("#woocommerce-pricing-rules-wrap").data('setindex') + 1;
						$("#woocommerce-pricing-rules-wrap").data('setindex', set_index);

						var data = {
							set_index: set_index,
							post:<?php 
        echo isset($_GET['post']) ? $_GET['post'] : 0;
        ?>
,
							action: 'create_empty_totals_ruleset'
						}

						$.post(ajaxurl, data, function (response) {
							$('#woocommerce-pricing-rules-wrap').append(response);

						});
					});

					$('#woocommerce-pricing-rules-wrap').delegate('.pricing_rule_apply_to', 'change', function (event) {
						var value = $(this).val();
						if (value != 'roles') {
							$('.roles', $(this).parent()).fadeOut();
							$('.roles input[type=checkbox]', $(this).closest('div')).removeAttr('checked');
						} else {
							$('.roles', $(this).parent()).fadeIn();
						}
					});

					$('#woocommerce-pricing-rules-wrap').delegate('.pricing_rule_when', 'change', function (event) {
						var value = $(this).val();
						if (value != 'cat') {
							$('.cats', $(this).closest('div')).fadeOut();
							$('.cats input[type=checkbox]', $(this).closest('div')).removeAttr('checked');
						} else {
							$('.cats', $(this).closest('div')).fadeIn();
						}
					});

					//Remove Pricing Set
					$('#woocommerce-pricing-rules-wrap').delegate('.delete_pricing_ruleset', 'click', function (event) {
						event.preventDefault();
						DeleteRuleSet($(this).data('name'));
					});

					//Add Button
					$('#woocommerce-pricing-rules-wrap').delegate('.add_pricing_rule', 'click', function (event) {
						event.preventDefault();
						InsertRule($(this).data('index'), $(this).data('name'));
					});



					//Remove Button                
					$('#woocommerce-pricing-rules-wrap').delegate('.delete_pricing_rule', 'click', function (event) {
						event.preventDefault();
						DeleteRule($(this).data('index'), $(this).data('name'));
					});

					//Validation
					$('#woocommerce-pricing-rules-wrap').delegate('.int_pricing_rule', 'keydown', function (event) {
						// Allow only backspace, delete and tab
						if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 190) {
							// let it happen, don't do anything
						}
						else {
							if (event.shiftKey && event.keyCode == 56) {
								if ($(this).val().length > 0) {
									event.preventDefault();
								} else {
									return true;
								}
							} else if (event.shiftKey) {
								event.preventDefault();
							} else if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
								event.preventDefault();
							} else {
								if ($(this).val() == "*") {
									event.preventDefault();
								}
							}
						}
					});

					$('#woocommerce-pricing-rules-wrap').delegate('.float_pricing_rule', 'keydown', function (event) {
						// Allow only backspace, delete and tab
						if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 190) {
							// let it happen, don't do anything
						}
						else {
							// Ensure that it is a number and stop the keypress
							if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
								event.preventDefault();
							}
						}
					});

					$("#woocommerce-pricing-rules-wrap").sortable(
						{
							handle: 'h4.first',
							containment: 'parent',
							axis: 'y'
						});

					function InsertRule(previousRowIndex, name) {


						var $index = $("#woocommerce-pricing-rules-table-" + name).data('lastindex') + 1;
						$("#woocommerce-pricing-rules-table-" + name).data('lastindex', $index);

						var html = '';
						html += '<tr id="pricing_rule_row_' + name + '_' + $index + '">';
						html += '<td>';
						html += '<input class="int_pricing_rule" id="pricing_rule_from_input_' + name + '_' + $index + '" type="text" name="pricing_rules[' + name + '][rules][' + $index + '][from]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<input class="int_pricing_rule" id="pricing_rule_to_input_' + name + '_' + $index + '" type="text" name="pricing_rules[' + name + '][rules][' + $index + '][to]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<select id="pricing_rule_type_value_' + name + '_' + $index + '" name="pricing_rules[' + name + '][rules][' + $index + '][type]">';
						html += '<option value="percentage_discount">Percentage Discount</option>';
						html += '</select>';
						html += '</td>';
						html += '<td>';
						html += '<input class="float_pricing_rule" id="pricing_rule_amount_input_' + $index + '" type="text" name="pricing_rules[' + name + '][rules][' + $index + '][amount]" value="" /> ';
						html += '</td>';
						html += '<td>';
						html += '<a data-index="' + $index + '" data-name="' + name + '" class="add_pricing_rule"><img  src="<?php 
        echo WC_Dynamic_Pricing::plugin_url() . '/assets/images/add.png';
        ?>
" title="add another rule" alt="add another rule" style="cursor:pointer; margin:0 3px;" /></a>';
						html += '<a data-index="' + $index + '" data-name="' + name + '" class="delete_pricing_rule"><img data-index="' + $index + '" src="<?php 
        echo WC_Dynamic_Pricing::plugin_url() . '/assets/images/remove.png';
        ?>
" title="remove rule" alt="remove rule" style="cursor:pointer; margin:0 3px;" /></a>';
						html += '</td>';
						html += '</tr>';

						$('#pricing_rule_row_' + name + '_' + previousRowIndex).after(html);
						$('.delete_pricing_rule', "#woocommerce-pricing-rules-table-" + name).show();

					}

					function DeleteRule(index, name) {
						if (confirm("Are you sure you would like to remove this price adjustment?")) {
							$('#pricing_rule_row_' + name + '_' + index).remove();

							var $index = $('tbody tr', "#woocommerce-pricing-rules-table-" + name).length;
							if ($index > 1) {
								$('.delete_pricing_rule', "#woocommerce-pricing-rules-table-" + name).show();
							} else {
								$('.delete_pricing_rule', "#woocommerce-pricing-rules-table-" + name).hide();
							}
						}
					}

					function DeleteRuleSet(name) {
						if (confirm('Are you sure you would like to remove this dynamic price set?')) {
							$('#woocommerce-pricing-ruleset-' + name).slideUp().remove();
						}
					}

				});

			</script>
			<?php 
    }
 private function print_price_fields($product_id = 0, $form_prefix = "")
 {
     if (!$product_id) {
         global $product;
         if ($product) {
             $product_id = $product->id;
         }
     } else {
         $product = wc_get_product($product_id);
     }
     if (!$product_id || empty($product)) {
         if (!empty($this->current_product_id_to_be_displayed)) {
             $product_id = $this->current_product_id_to_be_displayed;
             $product = wc_get_product($product_id);
         } else {
             $this->tm_epo_totals_batch($form_prefix);
             return;
         }
     }
     if (!$product_id || empty($product)) {
         return;
     }
     $cpf_price_array = $this->get_product_tm_epos($product_id);
     if (!$cpf_price_array) {
         return;
     }
     if ($cpf_price_array && $this->tm_epo_enable_final_total_box_all == "no") {
         $global_price_array = $cpf_price_array['global'];
         $local_price_array = $cpf_price_array['local'];
         if (empty($global_price_array) && empty($local_price_array)) {
             return;
         }
     }
     if (!$cpf_price_array && $this->tm_epo_enable_final_total_box_all == "no") {
         return;
     }
     if ($form_prefix) {
         $form_prefix = "_" . $form_prefix;
     }
     // WooCommerce Dynamic Pricing & Discounts
     if (class_exists('RP_WCDPD') && !empty($GLOBALS['RP_WCDPD'])) {
         $price = $this->get_RP_WCDPD($product);
         if ($price) {
             $price['product'] = array();
             if ($price['is_multiprice']) {
                 foreach ($price['rules'] as $variation_id => $variation_rule) {
                     foreach ($variation_rule as $rulekey => $pricerule) {
                         $price['product'][$variation_id][] = array("min" => $pricerule["min"], "max" => $pricerule["max"], "value" => $pricerule["type"] != "percentage" ? apply_filters('woocommerce_tm_epo_price', $pricerule["value"], "", false) : $pricerule["value"], "type" => $pricerule["type"]);
                     }
                 }
             } else {
                 foreach ($price['rules'] as $rulekey => $pricerule) {
                     $price['product'][0][] = array("min" => $pricerule["min"], "max" => $pricerule["max"], "value" => $pricerule["type"] != "percentage" ? apply_filters('woocommerce_tm_epo_price', $pricerule["value"], "", false) : $pricerule["value"], "type" => $pricerule["type"]);
                 }
             }
         } else {
             $price = array();
             $price['product'] = array();
         }
         $price['price'] = apply_filters('woocommerce_tm_epo_price', $product->get_price(), "", false);
     } else {
         if (class_exists('WC_Dynamic_Pricing')) {
             $id = isset($product->variation_id) ? $product->variation_id : $product->id;
             $dp = WC_Dynamic_Pricing::instance();
             if ($dp && is_object($dp) && property_exists($dp, "discounted_products") && isset($dp->discounted_products[$id])) {
                 $_price = $dp->discounted_products[$id];
             } else {
                 $_price = $product->get_price();
             }
         } else {
             $_price = apply_filters('woocommerce_tm_epo_price_compatibility', $product->get_price(), $product);
         }
         $price = array();
         $price['product'] = array();
         $price['price'] = apply_filters('woocommerce_tm_epo_price', $_price, "", false);
     }
     $variations = array();
     $variations_subscription_period = array();
     $variations_subscription_sign_up_fee = array();
     foreach ($product->get_children() as $child_id) {
         $variation = $product->get_child($child_id);
         if (!$variation->exists()) {
             continue;
         }
         if (class_exists('WC_Subscriptions_Product')) {
             $variations_subscription_period[$child_id] = WC_Subscriptions_Product::get_price_string($variation, array('subscription_price' => false, 'sign_up_fee' => false, 'trial_length' => false));
             $variations_subscription_sign_up_fee[$child_id] = $variation->subscription_sign_up_fee;
         } else {
             $variations_subscription_period[$child_id] = '';
             $variations_subscription_sign_up_fee[$child_id] = '';
         }
         $variations[$child_id] = apply_filters('woocommerce_tm_epo_price_compatibility', apply_filters('woocommerce_tm_epo_price', $variation->get_price(), "", false), $variation, $child_id);
     }
     $is_subscription = false;
     $subscription_period = '';
     $subscription_sign_up_fee = 0;
     if (class_exists('WC_Subscriptions_Product')) {
         if (WC_Subscriptions_Product::is_subscription($product)) {
             $is_subscription = true;
             $subscription_period = WC_Subscriptions_Product::get_price_string($product, array('subscription_price' => false, 'sign_up_fee' => false, 'trial_length' => false));
             $subscription_sign_up_fee = WC_Subscriptions_Product::get_sign_up_fee($product);
         }
     }
     global $woocommerce;
     $cart = $woocommerce->cart;
     $_tax = new WC_Tax();
     $taxrates = $_tax->get_rates($product->get_tax_class());
     unset($_tax);
     $tax_rate = 0;
     foreach ($taxrates as $key => $value) {
         $tax_rate = $tax_rate + floatval($value['rate']);
     }
     $taxable = $product->is_taxable();
     $tax_display_mode = get_option('woocommerce_tax_display_shop');
     $tax_string = "";
     if ($taxable && $this->tm_epo_global_tax_string_suffix == "yes") {
         if ($tax_display_mode == 'excl') {
             //if ( $cart->tax_total > 0 && $cart->prices_include_tax ) {
             $tax_string = ' <small>' . WC()->countries->ex_tax_or_vat() . '</small>';
             //}
         } else {
             //if ( $cart->tax_total > 0 && !$cart->prices_include_tax ) {
             $tax_string = ' <small>' . WC()->countries->inc_tax_or_vat() . '</small>';
             //}
         }
     }
     $force_quantity = 0;
     if ($this->cart_edit_key) {
         $cart_item_key = $this->cart_edit_key;
         $cart_item = WC()->cart->get_cart_item($cart_item_key);
         if (isset($cart_item["quantity"])) {
             $force_quantity = $cart_item["quantity"];
         }
     }
     if (!$this->is_bto) {
         if (empty($this->epo_internal_counter) || !isset($this->epo_internal_counter_check["tc" . $this->epo_internal_counter])) {
             // First time displaying totals and fields haven't been displayed
             $this->epo_internal_counter++;
             $this->epo_internal_counter_check["tc" . $this->epo_internal_counter] = $this->epo_internal_counter;
         } else {
             // Fields have already been displayed
             unset($this->epo_internal_counter_check["tc" . $this->epo_internal_counter]);
             $this->current_product_id_to_be_displayed = 0;
         }
         $_epo_internal_counter = $this->epo_internal_counter;
     } else {
         $_epo_internal_counter = 0;
     }
     wc_get_template('tm-totals.php', array('theme_name' => $this->get_theme('Name'), 'variations' => esc_html(json_encode((array) $variations)), 'variations_subscription_period' => esc_html(json_encode((array) $variations_subscription_period)), 'variations_subscription_sign_up_fee' => esc_html(json_encode((array) $variations_subscription_sign_up_fee)), 'subscription_period' => $subscription_period, 'subscription_sign_up_fee' => $subscription_sign_up_fee, 'is_subscription' => $is_subscription, 'is_sold_individually' => $product->is_sold_individually(), 'hidden' => $this->tm_meta_cpf['override_final_total_box'] ? $this->tm_epo_final_total_box == 'hide' ? ' hidden' : '' : ($this->tm_meta_cpf['override_final_total_box'] == 'hide' ? ' hidden' : ''), 'form_prefix' => $form_prefix, 'type' => esc_html($product->product_type), 'price' => esc_html(is_object($product) ? apply_filters('woocommerce_tm_final_price', $price['price'], $product) : ''), 'taxable' => $taxable, 'tax_display_mode' => $tax_display_mode, 'prices_include_tax' => $cart->prices_include_tax, 'tax_rate' => $tax_rate, 'tax_string' => $tax_string, 'product_price_rules' => esc_html(json_encode((array) $price['product'])), 'fields_price_rules' => $this->tm_epo_dpd_enable == "no" ? 0 : 1, 'tm_epo_dpd_suffix' => $this->tm_epo_dpd_suffix, 'tm_epo_dpd_prefix' => $this->tm_epo_dpd_prefix, 'force_quantity' => $force_quantity, 'product_id' => $product_id, 'epo_internal_counter' => $_epo_internal_counter), $this->_namespace, $this->template_path);
 }
 public static function init()
 {
     if (self::$instance == null) {
         self::$instance = new WC_Dynamic_Pricing();
     }
 }