Discount Rules for WooCommerce - Version 1.4.9

Version Description

Download this release

Release Info

Developer flycart
Plugin Icon 128x128 Discount Rules for WooCommerce
Version 1.4.9
Comparing to
See all releases

Code changes from version 1.4.8 to 1.4.9

helper/general-helper-3.php ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if (!defined('ABSPATH')) exit; // Exit if accessed directly
3
+ include_once(WOO_DISCOUNT_DIR . '/helper/purchase.php');
4
+
5
+ /**
6
+ * Class woo_dicount_rules_generalHelper
7
+ */
8
+ if ( ! class_exists( 'woo_dicount_rules_generalHelper' ) ) {
9
+ class woo_dicount_rules_generalHelper
10
+ {
11
+
12
+ public $isPro;
13
+
14
+ /**
15
+ * @var string
16
+ */
17
+ public $default_page = 'pricing-rules';
18
+
19
+ /**
20
+ * To Process the View.
21
+ *
22
+ * @param $path
23
+ * @param $data
24
+ * @return bool|string
25
+ */
26
+ public function processBaseView($path, $data)
27
+ {
28
+ if (!file_exists($path)) return false;
29
+ $this->checkPluginState();
30
+ $purchase = new woo_dicount_rules_purchase();
31
+ $suffix = $purchase->getSuffix();
32
+ ob_start();
33
+ $config = $data;
34
+ $pro = $this->isPro;
35
+ $products = $this->getProductList();
36
+ $category = $this->getCategoryList();
37
+ $users = $this->getUserList();
38
+ $userRoles = $this->getUserRoles();
39
+ $countries = $this->getAllCountries();
40
+ if (!isset($config)) return false;
41
+ if (!isset($path) or is_null($config)) return false;
42
+ include($path);
43
+ $html = ob_get_contents();
44
+ ob_end_clean();
45
+ return $html;
46
+ }
47
+
48
+ public function checkPluginState()
49
+ {
50
+ $purchase = new woo_dicount_rules_purchase();
51
+ $this->isPro = $purchase->isPro();
52
+ return $this->isPro;
53
+ // $this->isPro = true;
54
+ }
55
+
56
+ /**
57
+ * To Retrieve the list of Users.
58
+ *
59
+ * @return array
60
+ */
61
+ public function getUserList()
62
+ {
63
+ $result = array();
64
+ foreach (get_users() as $user) {
65
+ $result[$user->ID] = '#' . $user->ID . ' ' . $user->user_email;
66
+ }
67
+ return $result;
68
+ }
69
+
70
+ /**
71
+ * To Retrieve the active tab.
72
+ *
73
+ * @return string
74
+ */
75
+ public function getCurrentTab()
76
+ {
77
+ $postData = \FlycartInput\FInput::getInstance();
78
+ $tab = $this->default_page;
79
+ $empty_tab = $postData->get('tab', null);
80
+ if (!empty($empty_tab) && $postData->get('tab', '') != '') {
81
+ $tab = sanitize_text_field($postData->get('tab', ''));
82
+ }
83
+ return $tab;
84
+ }
85
+
86
+ /**
87
+ * To Get Product List.
88
+ *
89
+ * @return array
90
+ */
91
+ public function getProductList()
92
+ {
93
+ $base = new woo_dicount_rules_WooDiscountBase();
94
+ $base = $base->getBaseConfig();
95
+ if (is_string($base)) $base = json_decode($base, true);
96
+ $show_draft = 0;
97
+ if(isset($base['show_draft']) && $base['show_draft'] == 1){
98
+ $show_draft = 1;
99
+ }
100
+ if($show_draft){
101
+ $postStatus = array('publish', 'pending', 'future', 'private', 'inherit');
102
+ } else {
103
+ $postStatus = array('publish', 'pending', 'draft', 'future', 'private', 'inherit');
104
+ }
105
+ $products = array();
106
+ $posts_raw = get_posts(array(
107
+ 'posts_per_page' => -1,
108
+ 'post_type' => 'product',
109
+ 'post_status' => $postStatus,
110
+ 'fields' => 'ids',
111
+ ));
112
+
113
+ foreach ($posts_raw as $post_id) {
114
+ $products[$post_id] = '#' . $post_id . ' ' . get_the_title($post_id);
115
+ }
116
+
117
+ return $products;
118
+ }
119
+
120
+ /**
121
+ * To Get All Countries.
122
+ *
123
+ * @return array
124
+ */
125
+ public function getAllCountries()
126
+ {
127
+ $countries = new WC_Countries();
128
+
129
+ if ($countries && is_array($countries->countries)) {
130
+ return array_merge(array(), $countries->countries);
131
+ } else {
132
+ return array();
133
+ }
134
+ }
135
+
136
+ /**
137
+ * To Get All Capabilities list.
138
+ *
139
+ * @return array
140
+ */
141
+ public function getCapabilitiesList()
142
+ {
143
+ $capabilities = array();
144
+
145
+ if (class_exists('Groups_User') && class_exists('Groups_Wordpress') && function_exists('_groups_get_tablename')) {
146
+
147
+ global $wpdb;
148
+ $capability_table = _groups_get_tablename('capability');
149
+ $all_capabilities = $wpdb->get_results('SELECT capability FROM ' . $capability_table);
150
+
151
+ if ($all_capabilities) {
152
+ foreach ($all_capabilities as $capability) {
153
+ $capabilities[$capability->capability] = $capability->capability;
154
+ }
155
+ }
156
+ } else {
157
+ global $wp_roles;
158
+
159
+ if (!isset($wp_roles)) {
160
+ get_role('administrator');
161
+ }
162
+
163
+ $roles = $wp_roles->roles;
164
+
165
+ if (is_array($roles)) {
166
+ foreach ($roles as $rolename => $atts) {
167
+ if (isset($atts['capabilities']) && is_array($atts['capabilities'])) {
168
+ foreach ($atts['capabilities'] as $capability => $value) {
169
+ if (!in_array($capability, $capabilities)) {
170
+ $capabilities[$capability] = $capability;
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
177
+
178
+ return array_merge(array(), $capabilities);
179
+ }
180
+
181
+ /**
182
+ * @return array
183
+ */
184
+ public function getUserRoles()
185
+ {
186
+ global $wp_roles;
187
+
188
+ if (!isset($wp_roles)) {
189
+ $wp_roles = new WP_Roles();
190
+ }
191
+
192
+ return array_merge(array(), $wp_roles->get_names());
193
+ }
194
+
195
+ /**
196
+ * Get list of roles assigned to current user
197
+ *
198
+ * @access public
199
+ * @return array
200
+ */
201
+ public static function getCurrentUserRoles()
202
+ {
203
+ $current_user = wp_get_current_user();
204
+ return $current_user->roles;
205
+ }
206
+
207
+ /**
208
+ * @return array
209
+ */
210
+ public function getCategoryList()
211
+ {
212
+ $result = array();
213
+
214
+ $post_categories_raw = get_terms(array('product_cat'), array('hide_empty' => 0));
215
+ $post_categories_raw_count = count($post_categories_raw);
216
+
217
+ foreach ($post_categories_raw as $post_cat_key => $post_cat) {
218
+ $category_name = $post_cat->name;
219
+
220
+ if ($post_cat->parent) {
221
+ $parent_id = $post_cat->parent;
222
+ $has_parent = true;
223
+
224
+ // Make sure we don't have an infinite loop here (happens with some kind of "ghost" categories)
225
+ $found = false;
226
+ $i = 0;
227
+
228
+ while ($has_parent && ($i < $post_categories_raw_count || $found)) {
229
+
230
+ // Reset each time
231
+ $found = false;
232
+ $i = 0;
233
+
234
+ foreach ($post_categories_raw as $parent_post_cat_key => $parent_post_cat) {
235
+
236
+ $i++;
237
+
238
+ if ($parent_post_cat->term_id == $parent_id) {
239
+ $category_name = $parent_post_cat->name . ' &rarr; ' . $category_name;
240
+ $found = true;
241
+
242
+ if ($parent_post_cat->parent) {
243
+ $parent_id = $parent_post_cat->parent;
244
+ } else {
245
+ $has_parent = false;
246
+ }
247
+
248
+ break;
249
+ }
250
+ }
251
+ }
252
+ }
253
+
254
+ $result[$post_cat->term_id] = $category_name;
255
+ }
256
+
257
+ return $result;
258
+ }
259
+
260
+ /**
261
+ * Get Category by passing product ID or Product.
262
+ *
263
+ * @param $item
264
+ * @param bool $is_id
265
+ * @return array
266
+ */
267
+ public static function getCategoryByPost($item, $is_id = false)
268
+ {
269
+ if ($is_id) {
270
+ $id = $item;
271
+ } else {
272
+ $id = $item['data']->get_id();
273
+ }
274
+ $id = intval($id);
275
+ if (!$id) return false;
276
+
277
+ $categories = array();
278
+ $current_categories = wp_get_post_terms($id, 'product_cat');
279
+
280
+ foreach ($current_categories as $category) {
281
+ $categories[] = $category->term_id;
282
+ }
283
+
284
+ return $categories;
285
+ }
286
+
287
+ /**
288
+ * To Parsing the Array from String to Int.
289
+ *
290
+ * @param array $array
291
+ */
292
+ public static function toInt(array &$array)
293
+ {
294
+ foreach ($array as $index => $item) {
295
+ $array[$index] = intval($item);
296
+ }
297
+ }
298
+
299
+ /**
300
+ * @param $version
301
+ * @return bool|mixed
302
+ */
303
+ public static function wcVersion($version)
304
+ {
305
+ if (defined('WC_VERSION') && WC_VERSION) {
306
+ return version_compare(WC_VERSION, $version, '>=');
307
+ } else if (defined('WOOCOMMERCE_VERSION') && WOOCOMMERCE_VERSION) {
308
+ return version_compare(WOOCOMMERCE_VERSION, $version, '>=');
309
+ } else {
310
+ return false;
311
+ }
312
+ }
313
+
314
+ /**
315
+ * @param $html
316
+ * @return bool|mixed
317
+ */
318
+ static function makeString($html)
319
+ {
320
+ if (is_null($html) || empty($html) || !isset($html)) return false;
321
+ $out = $html;
322
+ // This Process only helps, single level array.
323
+ if (is_array($html)) {
324
+ foreach ($html as $id => $value) {
325
+ self::escapeCode($value);
326
+ // Finally Eliminating the Special Chars.
327
+ // $value = preg_replace('/[^A-Za-z0-9]/', '', $value);
328
+ $html[$id] = $value;
329
+ }
330
+ return $out;
331
+ } else {
332
+ self::escapeCode($html);
333
+ // Finally Eliminating the Special Chars.
334
+ // $html = preg_replace('/[^A-Za-z0-9]/', '', $html);
335
+ return $html;
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Re-Arrange the Index of Array to Make Usable.[2-D Array Only]
341
+ * @param $rules
342
+ */
343
+ public static function reArrangeArray(&$rules)
344
+ {
345
+ $result = array();
346
+ foreach ($rules as $index => $item) {
347
+ foreach ($item as $id => $value) {
348
+ $result[$id] = $value;
349
+ }
350
+ }
351
+ $rules = $result;
352
+ }
353
+
354
+ /**
355
+ * @param $value
356
+ */
357
+ static function escapeCode(&$value)
358
+ {
359
+ // Four Possible tags for PHP to Init.
360
+ $value = preg_replace(array('/^<\?php.*\?\>/', '/^<\%.*\%\>/', '/^<\?.*\?\>/', '/^<\?=.*\?\>/'), '', $value);
361
+ $value = self::delete_all_between('<?php', '?>', $value);
362
+ $value = self::delete_all_between('<?', '?>', $value);
363
+ $value = self::delete_all_between('<?=', '?>', $value);
364
+ $value = self::delete_all_between('<%', '%>', $value);
365
+ $value = str_replace(array('<?php', '<?', '<?=', '<%', '?>'), '', $value);
366
+ }
367
+
368
+
369
+ /**
370
+ * @param $beginning
371
+ * @param $end
372
+ * @param $string
373
+ * @return mixed
374
+ */
375
+ static function delete_all_between($beginning, $end, $string)
376
+ {
377
+
378
+ if (!is_string($string)) return false;
379
+
380
+ $beginningPos = strpos($string, $beginning);
381
+ $endPos = strpos($string, $end);
382
+ if ($beginningPos === false || $endPos === false) {
383
+ return $string;
384
+ }
385
+
386
+ $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);
387
+
388
+ return str_replace($textToDelete, '', $string);
389
+ }
390
+
391
+ /**
392
+ * To get slider content through curl
393
+ * */
394
+ public static function getSideBarContent(){
395
+ $html = '';
396
+ if(is_callable('curl_init')) {
397
+ $ch = curl_init();
398
+ curl_setopt($ch, CURLOPT_URL, 'https://www.flycart.org/updates/woo-discount-rules.json');
399
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
400
+ $contents = curl_exec($ch);
401
+ $contents_decode = json_decode($contents);
402
+ if(isset($contents_decode['0']->promo_html)){
403
+ $html = $contents_decode['0']->promo_html;
404
+ }
405
+ }
406
+
407
+ return $html;
408
+ }
409
+ }
410
+ }
helper/purchase.php CHANGED
@@ -267,7 +267,7 @@ if ( ! class_exists( 'woo_dicount_rules_purchase' ) ) {
267
  $base = new woo_dicount_rules_WooDiscountBase();
268
  $config = $base->getBaseConfig();
269
  if (is_string($config)) $config = json_decode($config);
270
- $dlid = $config->license_key;
271
  if ( !empty($dlid) ) {
272
  $update_url .= '&dlid='.$dlid;
273
  }
267
  $base = new woo_dicount_rules_WooDiscountBase();
268
  $config = $base->getBaseConfig();
269
  if (is_string($config)) $config = json_decode($config);
270
+ $dlid = isset($config->license_key)? $config->license_key: null;
271
  if ( !empty($dlid) ) {
272
  $update_url .= '&dlid='.$dlid;
273
  }
includes/cart-rules-3.php ADDED
@@ -0,0 +1,880 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if (!defined('ABSPATH')) exit; // Exit if accessed directly
3
+ include_once(WOO_DISCOUNT_DIR . '/helper/general-helper.php');
4
+ include_once(WOO_DISCOUNT_DIR . '/includes/discount-base.php');
5
+
6
+ /**
7
+ * Class woo_dicount_rules_cartRules
8
+ */
9
+ if (!class_exists('woo_dicount_rules_cartRules')) {
10
+ class woo_dicount_rules_cartRules
11
+ {
12
+ /**
13
+ * @var string
14
+ */
15
+ private $option_name = 'woo_discount_cart_option';
16
+
17
+ /**
18
+ * @var string
19
+ */
20
+ public $post_type = 'woo_discount_cart';
21
+
22
+ /**
23
+ * @var bool
24
+ */
25
+ public $discount_applied = false;
26
+
27
+ /**
28
+ * @var
29
+ */
30
+ private $rules;
31
+
32
+ /**
33
+ * @var
34
+ */
35
+ public $rule_sets;
36
+
37
+ /**
38
+ * @var array
39
+ */
40
+ public $cart_items;
41
+
42
+ /**
43
+ * @var
44
+ */
45
+ public $sub_total;
46
+
47
+ /**
48
+ * @var int
49
+ */
50
+ public $discount_total = 0;
51
+
52
+ /**
53
+ * @var array
54
+ */
55
+ public $coupon_list;
56
+
57
+ /**
58
+ * @var string
59
+ */
60
+ public $coupon_code;
61
+
62
+ /**
63
+ * @var
64
+ */
65
+ public $matched_sets;
66
+
67
+ public $postData;
68
+
69
+ /**
70
+ * woo_dicount_rules_cartRules constructor.
71
+ */
72
+ public function __construct()
73
+ {
74
+ global $woocommerce;
75
+
76
+ $this->postData = \FlycartInput\FInput::getInstance();
77
+ $this->cart_items = (isset($woocommerce->cart->cart_contents) ? $woocommerce->cart->cart_contents : array());
78
+ $this->calculateCartSubtotal();
79
+ $this->coupon_list = (isset($woocommerce->cart->applied_coupons) ? $woocommerce->cart->applied_coupons : array());
80
+
81
+ // Check for Remove Coupon Request.
82
+ if (!is_null($this->postData->get('remove_coupon', null))) $this->removeWoocommerceCoupon($this->postData->get('remove_coupon'));
83
+
84
+ // Update Coupon Code
85
+ $this->coupon_code = strtolower($this->getCouponCode());
86
+
87
+
88
+ }
89
+
90
+ /**
91
+ * Save Cart Configs.
92
+ *
93
+ * @param array $request bulk request data.
94
+ * @return bool
95
+ */
96
+ public function save($request)
97
+ {
98
+ foreach ($request as $index => $value) {
99
+ if ($index !== 'discount_rule') {
100
+ // $request[$index] = generalHelper::makeString($value);
101
+ $request[$index] = woo_dicount_rules_generalHelper::makeString($value);
102
+ }
103
+ }
104
+
105
+ $id = (isset($request['rule_id']) ? $request['rule_id'] : false);
106
+
107
+ $id = intval($id);
108
+ if (!$id && $id != 0) return false;
109
+
110
+ $title = (isset($request['rule_name']) ? $request['rule_name'] : 'New');
111
+ $slug = str_replace(' ', '-', strtolower($title));
112
+
113
+ // To Lowercase.
114
+ $slug = strtolower($slug);
115
+
116
+ // Encoding String with Space.
117
+ $slug = str_replace(' ', '-', $slug);
118
+
119
+ $form = array(
120
+ 'rule_name',
121
+ 'rule_descr',
122
+ 'date_from',
123
+ 'date_to',
124
+ 'apply_to',
125
+ 'discount_type',
126
+ 'to_discount',
127
+ 'discount_rule',
128
+ 'rule_order',
129
+ 'status'
130
+ );
131
+
132
+ if ($id) {
133
+ $post = array(
134
+ 'ID' => $id,
135
+ 'post_title' => $title,
136
+ 'post_name' => $slug,
137
+ 'post_content' => 'New Rule',
138
+ 'post_type' => $this->post_type,
139
+ 'post_status' => 'publish'
140
+ );
141
+ wp_update_post($post);
142
+ } else {
143
+ $post = array(
144
+ 'post_title' => $title,
145
+ 'post_name' => $slug,
146
+ 'post_content' => 'New Rule',
147
+ 'post_type' => $this->post_type,
148
+ 'post_status' => 'publish'
149
+ );
150
+ $id = wp_insert_post($post);
151
+ $request['status'] = 'publish';
152
+ }
153
+
154
+ foreach ($request['discount_rule'] as $index => $value) {
155
+ $request['discount_rule'][$index] = woo_dicount_rules_generalHelper::makeString($value);
156
+ }
157
+
158
+ if (isset($request['discount_rule'])) $request['discount_rule'] = json_encode($request['discount_rule']);
159
+
160
+ if (is_null($id) || !isset($id)) return false;
161
+
162
+ foreach ($request as $index => $value) {
163
+ if (in_array($index, $form)) {
164
+ if (get_post_meta($id, $index)) {
165
+ update_post_meta($id, $index, $value);
166
+ } else {
167
+ add_post_meta($id, $index, $value);
168
+ }
169
+ }
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Load View Data.
175
+ *
176
+ * @param $option
177
+ * @param integer $id to load post.
178
+ * @return string mixed response.
179
+ */
180
+ public function view($option, $id)
181
+ {
182
+ $id = intval($id);
183
+ if (!$id) return false;
184
+
185
+ $post = get_post($id, 'OBJECT');
186
+ if (isset($post)) {
187
+ if (isset($post->ID)) {
188
+ $post->meta = get_post_meta($post->ID);
189
+ }
190
+ }
191
+ return $post;
192
+ }
193
+
194
+ /**
195
+ * List of Checklist.
196
+ */
197
+ public function checkPoint()
198
+ {
199
+ // Apply rules with products.
200
+ // NOT YET USED.
201
+ if ($this->discount_applied) return true;
202
+ }
203
+
204
+ /**
205
+ * Load List of Rules.
206
+ *
207
+ * @return mixed
208
+ */
209
+ public function getRules($onlyCount = false)
210
+ {
211
+ $posts = get_posts(array('post_type' => $this->post_type));
212
+ if ($onlyCount) return count($posts);
213
+ if (isset($posts) && count($posts) > 0) {
214
+ foreach ($posts as $index => $item) {
215
+ $posts[$index]->meta = get_post_meta($posts[$index]->ID);
216
+ }
217
+
218
+ $this->rules = $posts;
219
+ }
220
+ return $posts;
221
+ }
222
+
223
+ /**
224
+ * To Analyzing the Pricing Rules to Apply the Discount in terms of price.
225
+ */
226
+ public function analyse($woocommerce)
227
+ {
228
+ global $woocommerce;
229
+ // Re-arranging the Rules.
230
+ $this->organizeRules();
231
+ // Apply Group of Rules.
232
+ $this->applyRules();
233
+ // Get Overall Discounts.
234
+ $this->getDiscountAmount();
235
+ // Add a Coupon Virtually (Temporary access).
236
+ if ($this->discount_total != 0) {
237
+ add_filter('woocommerce_get_shop_coupon_data', array($this, 'addVirtualCoupon'), 10, 2);
238
+ add_action('woocommerce_after_calculate_totals', array($this, 'applyFakeCoupons'));
239
+ }
240
+ }
241
+
242
+ /**
243
+ *
244
+ */
245
+ public function appliedCoupons()
246
+ {
247
+
248
+ }
249
+
250
+
251
+ /**
252
+ * To Make record of discount changes.
253
+ *
254
+ * @return bool
255
+ */
256
+ public function makeLog()
257
+ {
258
+ if (is_null($this->coupon_code) || empty($this->coupon_code)) return false;
259
+
260
+ $discount_log = array(
261
+ 'coupon_name' => $this->coupon_code,
262
+ 'discount' => $this->discount_total,
263
+ );
264
+ WC()->session->set('woo_cart_discount', json_encode($discount_log));
265
+ }
266
+
267
+ /**
268
+ * Virtually add Coupon to apply the Discount.
269
+ *
270
+ * @param array $unknown_param
271
+ * @param string $old_coupon_code Existing Coupon
272
+ * @return array|bool
273
+ */
274
+ public function addVirtualCoupon($unknown_param, $old_coupon_code)
275
+ {
276
+ $coupon_code = $this->coupon_code;
277
+ // Getting Coupon Remove status from Session.
278
+ $is_removed = WC()->session->get('woo_coupon_removed');
279
+ // If Both are same, then it won't added.
280
+ if ($coupon_code == $is_removed) return false;
281
+
282
+ if ($old_coupon_code == $coupon_code) {
283
+ if ($this->postData->get('remove_coupon', false) == $coupon_code) return false;
284
+ $this->makeLog();
285
+ $coupon = array(
286
+ 'id' => 321123 . rand(2, 9),
287
+ 'type' => 'fixed_cart',
288
+ 'amount' => $this->discount_total,
289
+ 'individual_use' => false,
290
+ 'product_ids' => array(),
291
+ 'exclude_product_ids' => array(),
292
+ 'usage_limit' => '',
293
+ 'usage_limit_per_user' => '',
294
+ 'limit_usage_to_x_items' => '',
295
+ 'usage_count' => '',
296
+ 'expiry_date' => '',
297
+ 'apply_before_tax' => 'yes',
298
+ 'free_shipping' => false,
299
+ 'product_categories' => array(),
300
+ 'exclude_product_categories' => array(),
301
+ 'exclude_sale_items' => false,
302
+ 'minimum_amount' => '',
303
+ 'maximum_amount' => '',
304
+ 'customer_email' => '',
305
+ );
306
+
307
+ return $coupon;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * To Get the Coupon code that already specified.
313
+ *
314
+ * @return string
315
+ */
316
+ public function getCouponCode()
317
+ {
318
+ $config = new woo_dicount_rules_WooDiscountBase();
319
+ $config = $config->getBaseConfig();
320
+
321
+ if (is_string($config)) $config = json_decode($config, true);
322
+
323
+ // Pre-Defined alternative Coupon Code.
324
+ $coupon = 'Discount';
325
+
326
+ // Verify and overwrite the Coupon Code.
327
+ if (isset($config['coupon_name']) && $config['coupon_name'] != '') $coupon = $config['coupon_name'];
328
+ return $coupon;
329
+ }
330
+
331
+ /**
332
+ * Apply fake coupon to cart
333
+ *
334
+ * @access public
335
+ * @return void
336
+ */
337
+ public function applyFakeCoupons()
338
+ {
339
+ global $woocommerce;
340
+
341
+ // 'newyear' is a temporary coupon for validation.
342
+ $coupon_code = apply_filters('woocommerce_coupon_code', $this->coupon_code);
343
+ // Getting New Instance with the Coupon Code.
344
+ $the_coupon = new WC_Coupon($coupon_code);
345
+ // Validating the Coupon as Valid and discount status.
346
+ if ($the_coupon->is_valid() && !$woocommerce->cart->has_discount($coupon_code)) {
347
+
348
+ // Do not apply coupon with individual use coupon already applied
349
+ if ($woocommerce->cart->applied_coupons) {
350
+ foreach ($woocommerce->cart->applied_coupons as $code) {
351
+ $coupon = new WC_Coupon($code);
352
+ if ($coupon->individual_use == true) {
353
+ return false;
354
+ }
355
+ }
356
+ }
357
+
358
+ // Add coupon
359
+ $woocommerce->cart->applied_coupons[] = $coupon_code;
360
+ do_action('woocommerce_applied_coupon', $coupon_code);
361
+
362
+ return true;
363
+ }
364
+ }
365
+
366
+ /**
367
+ * Simply remove or reset the virtual coupon by set "empty" as value
368
+ * to "Woo's" session "woo_coupon_removed".
369
+ *
370
+ * @param $coupon
371
+ */
372
+ public function removeWoocommerceCoupon($coupon)
373
+ {
374
+ WC()->session->set('woo_coupon_removed', $coupon);
375
+ }
376
+
377
+ /**
378
+ *
379
+ */
380
+ public function removeCartDiscount()
381
+ {
382
+ global $woocommerce;
383
+
384
+ // Iterate over applied coupons and check each of them
385
+ foreach ($woocommerce->cart->applied_coupons as $code) {
386
+
387
+ // Check if coupon code matches our fake coupon code
388
+ if ($this->getCouponCode() === $code) {
389
+
390
+ // Get coupon
391
+ $coupon = new WC_Coupon($code);
392
+
393
+ // Remove coupon if it no longer exists
394
+ if (!$coupon->is_valid()) {
395
+
396
+ // Remove the coupon
397
+ add_filter('woocommerce_coupons_enabled', array($this, 'woocommerceEnableCoupons'));
398
+ $this->remove_woocommerce_coupon($code);
399
+ remove_filter('woocommerce_coupons_enabled', array($this, 'woocommerceEnableCoupons'));
400
+ }
401
+ }
402
+ }
403
+ }
404
+
405
+ /**
406
+ * @return string
407
+ */
408
+ public function woocommerceEnableCoupons()
409
+ {
410
+ return 'true';
411
+ }
412
+
413
+ /**
414
+ *
415
+ */
416
+ public function organizeRules()
417
+ {
418
+ // Loads the Rules to Global.
419
+ $this->getRules();
420
+ // Validate and Re-Assign the Rules.
421
+ $this->filterRules();
422
+ }
423
+
424
+ /**
425
+ * @return bool
426
+ */
427
+ public function applyRules()
428
+ {
429
+ global $woocommerce;
430
+ // If there is no rules, then return false.
431
+ if (!isset($this->rules)) return false;
432
+
433
+ // Check point having list of checklist to apply.
434
+ if ($this->checkPoint()) return false;
435
+
436
+ // To Generate Valid Rule sets.
437
+ $this->generateRuleSets();
438
+ }
439
+
440
+ /**
441
+ *
442
+ */
443
+ public function filterRules()
444
+ {
445
+ $rules = $this->rules;
446
+
447
+ if (is_null($rules) || !isset($rules)) return false;
448
+ // Start with empty set.
449
+ $rule_set = array();
450
+ foreach ($rules as $index => $rule) {
451
+ $status = (isset($rule->status) ? $rule->status : false);
452
+
453
+ // To Check as Plugin Active - InActive.
454
+ if ($status == 'publish') {
455
+ $date_from = (isset($rule->date_from) ? strtotime($rule->date_from) : false);
456
+ $date_to = (isset($rule->date_to) ? strtotime($rule->date_to) : false);
457
+ $today = strtotime(date('m/d/Y'));
458
+
459
+ // Validating Rule with Date of Expiry.
460
+ if (($date_from <= $today) && (($date_to == '') || ($date_to >= $today))) {
461
+ // Validating the Rule with its Order ID.
462
+ if (isset($rule->rule_order)) {
463
+ // If Order ID is '-', then this rule not going to implement.
464
+ if ($rule->rule_order !== '-') {
465
+ $rule_set[] = $rule;
466
+ }
467
+ }
468
+ }
469
+ }
470
+ }
471
+ $this->rules = $rule_set;
472
+
473
+ // To Order the Rules, based on its order ID.
474
+ $this->orderRules();
475
+ }
476
+
477
+ /**
478
+ * @return bool
479
+ */
480
+ public function orderRules()
481
+ {
482
+ if (empty($this->rules)) return false;
483
+
484
+ $ordered_rules = array();
485
+
486
+ // Make associative array with Order ID.
487
+ foreach ($this->rules as $index => $rule) {
488
+ if (isset($rule->rule_order)) {
489
+ if ($rule->rule_order != '') {
490
+ $ordered_rules[$rule->rule_order] = $rule;
491
+ }
492
+ }
493
+ }
494
+ // Order the Rules with it's priority.
495
+ ksort($ordered_rules);
496
+
497
+ $this->rules = $ordered_rules;
498
+ }
499
+
500
+ /**
501
+ * @return bool
502
+ */
503
+ public function generateRuleSets()
504
+ {
505
+ global $woocommerce;
506
+ $rule_sets = array();
507
+
508
+ if (!isset($this->rules)) return false;
509
+
510
+ // Loop the Rules set to collect matched rules.
511
+ foreach ($this->rules as $index => $rule) {
512
+ // General Rule Info.
513
+ $rule_sets[$index]['discount_type'] = 'price_discount';
514
+ $rule_sets[$index]['name'] = (isset($rule->rule_name) ? $rule->rule_name : 'Rule_' . $index);
515
+ $rule_sets[$index]['descr'] = (isset($rule->rule_descr) ? $rule->rule_descr : '');
516
+ $rule_sets[$index]['method'] = (isset($rule->rule_method) ? $rule->rule_method : 'qty_based');
517
+ $rule_sets[$index]['qty_based_on'] = (isset($rule->qty_based_on) ? $rule->qty_based_on : 'each_product');
518
+ $rule_sets[$index]['date_from'] = (isset($rule->date_from) ? $rule->date_from : false);
519
+ $rule_sets[$index]['date_to'] = (isset($rule->date_to) ? $rule->date_to : false);
520
+ $rule_sets[$index]['discount_rule'] = (isset($rule->discount_rule) ? $rule->discount_rule : false);
521
+ $rule_sets[$index]['discount_type'] = (isset($rule->discount_type) ? $rule->discount_type : false);
522
+ $rule_sets[$index]['to_discount'] = (isset($rule->to_discount) ? $rule->to_discount : false);
523
+ $rule_sets[$index]['enabled'] = $this->validateCart($rule_sets[$index]['discount_rule']);
524
+ }
525
+ $this->rule_sets = $rule_sets;
526
+ }
527
+
528
+ /**
529
+ * Get Overall discount amount across allover the rules that available.
530
+ *
531
+ * @return integer Total Discount Amount.
532
+ */
533
+ public function getDiscountAmount()
534
+ {
535
+ $discount = 0;
536
+ $discounts = array();
537
+ if (!isset($this->rule_sets)) return false;
538
+
539
+ // Get settings
540
+ $config = new woo_dicount_rules_WooDiscountBase();
541
+ $config = $config->getBaseConfig();
542
+ if (is_string($config)) $config = json_decode($config, true);
543
+ if(isset($config['cart_setup'])){
544
+ $cart_setup = $config['cart_setup'];
545
+ } else {
546
+ $cart_setup = 'all';
547
+ }
548
+
549
+ if(count($this->rule_sets)){
550
+ if(in_array($cart_setup, array('first', 'all'))){
551
+ if($cart_setup == 'first'){
552
+ // Processing the Totals.
553
+ foreach ($this->rule_sets as $index => $rule) {
554
+ if ($rule['enabled'] == true) {
555
+ $discounts['name'][$index] = $rule['name'];
556
+ $discounts['type'][$index] = $rule['discount_type'];
557
+ if ($rule['discount_type'] == 'price_discount') {
558
+ // Getting the Flat Rate of Discount.
559
+ $discounts['to_discount'][$index] = $this->calculateDiscount($this->sub_total, array('type' => 'price', 'value' => $rule['to_discount']));
560
+ } else {
561
+ // Getting the Percentage level of Discount.
562
+ $discounts['to_discount'][$index] = $this->calculateDiscount($this->sub_total, array('type' => 'percentage', 'value' => $rule['to_discount']));
563
+ }
564
+ // Sum of Available discount list.
565
+ $discount += $discounts['to_discount'][$index];
566
+ // Update the status of the status of the discount rule.
567
+ $discounts['is_enabled'][$index] = $rule['enabled'];
568
+ break;
569
+ }
570
+ }
571
+ } else {
572
+ // Processing the Totals.
573
+ foreach ($this->rule_sets as $index => $rule) {
574
+ if ($rule['enabled'] == true) {
575
+ $discounts['name'][$index] = $rule['name'];
576
+ $discounts['type'][$index] = $rule['discount_type'];
577
+ if ($rule['discount_type'] == 'price_discount') {
578
+ // Getting the Flat Rate of Discount.
579
+ $discounts['to_discount'][$index] = $this->calculateDiscount($this->sub_total, array('type' => 'price', 'value' => $rule['to_discount']));
580
+ } else {
581
+ // Getting the Percentage level of Discount.
582
+ $discounts['to_discount'][$index] = $this->calculateDiscount($this->sub_total, array('type' => 'percentage', 'value' => $rule['to_discount']));
583
+ }
584
+ // Sum of Available discount list.
585
+ $discount += $discounts['to_discount'][$index];
586
+ // Update the status of the status of the discount rule.
587
+ $discounts['is_enabled'][$index] = $rule['enabled'];
588
+ }
589
+ }
590
+ }
591
+ } else if($cart_setup == 'biggest'){
592
+ $biggestDiscount = 0;
593
+ // Processing the Totals.
594
+ foreach ($this->rule_sets as $index => $rule) {
595
+ if ($rule['enabled'] == true) {
596
+ if ($rule['discount_type'] == 'price_discount') {
597
+ // Getting the Flat Rate of Discount.
598
+ $newDiscount = $this->calculateDiscount($this->sub_total, array('type' => 'price', 'value' => $rule['to_discount']));
599
+ } else {
600
+ // Getting the Percentage level of Discount.
601
+ $newDiscount = $this->calculateDiscount($this->sub_total, array('type' => 'percentage', 'value' => $rule['to_discount']));
602
+ }
603
+
604
+ if($newDiscount > $biggestDiscount){
605
+ $biggestDiscount = $newDiscount;
606
+ $discounts['name'][1] = $rule['name'];
607
+ $discounts['type'][1] = $rule['discount_type'];
608
+ $discounts['to_discount'][1] = $newDiscount;
609
+ $discount = $newDiscount;
610
+ // Update the status of the status of the discount rule.
611
+ $discounts['is_enabled'][1] = $rule['enabled'];
612
+ }
613
+ }
614
+ }
615
+ }
616
+ }
617
+
618
+ $this->discount_total = $discount;
619
+ return $discounts;
620
+ }
621
+
622
+ /**
623
+ * Comparing the Rules with the each line item to check
624
+ * and return as, matched or not.
625
+ *
626
+ * @param array $rules
627
+ * @return bool true|false
628
+ */
629
+ public function validateCart($rules)
630
+ {
631
+ $this->calculateCartSubtotal();
632
+ $rules = (is_string($rules) ? json_decode($rules, true) : array());
633
+ // Simple array helper to re-arrange the structure.
634
+ woo_dicount_rules_generalHelper::reArrangeArray($rules);
635
+ foreach ($rules as $index => $rule) {
636
+ // Validating the Rules one by one.
637
+ if ($this->applyRule($index, $rule) == false) {
638
+ return false;
639
+ }
640
+ }
641
+ return true;
642
+ }
643
+
644
+ /**
645
+ * Applying bunch amount of rules with the line item.
646
+ *
647
+ * @param string $index Index of the Rule
648
+ * @param array $rule array of rule info.
649
+ * @return bool true|false as matched or not.
650
+ */
651
+ public function applyRule($index, $rule)
652
+ {
653
+ switch ($index) {
654
+
655
+ // Cart Subtotal.
656
+ case 'subtotal_least':
657
+ if ($this->sub_total < $rule) {
658
+ return false;
659
+ }
660
+ return true;
661
+ break;
662
+ case 'subtotal_less':
663
+ if ($this->sub_total >= $rule) {
664
+ return false;
665
+ }
666
+ return true;
667
+ break;
668
+
669
+ // Cart Item Count.
670
+ case 'item_count_least':
671
+ if (count($this->cart_items) < $rule) {
672
+ return false;
673
+ }
674
+ return true;
675
+ break;
676
+ case 'item_count_less':
677
+ if (count($this->cart_items) >= $rule) {
678
+ return false;
679
+ }
680
+ return true;
681
+ break;
682
+
683
+ // Quantity Count.
684
+ case 'quantity_least':
685
+ if ($this->cartItemQtyTotal() < $rule) {
686
+ return false;
687
+ }
688
+ return true;
689
+ break;
690
+ case 'quantity_less':
691
+ if ($this->cartItemQtyTotal() >= $rule) {
692
+ return false;
693
+ }
694
+ return true;
695
+ break;
696
+
697
+ // Logged In Users.
698
+ case 'users_in':
699
+ if (get_current_user_id() == 0 || !in_array(get_current_user_id(), $rule)) {
700
+ return false;
701
+ }
702
+ return true;
703
+ break;
704
+ case 'shipping_countries_in':
705
+ // $user_meta = get_user_meta(get_current_user_id());
706
+ $shippingCountry = WC()->customer->get_shipping_country();
707
+ // if (!$user_meta || !isset($user_meta['shipping_country']) || empty($user_meta['shipping_country']) || !in_array($user_meta['shipping_country'][0], $rule)) {
708
+ if (empty($shippingCountry) || !in_array($shippingCountry, $rule)) {
709
+ return false;
710
+ }
711
+ return true;
712
+ break;
713
+ case 'roles_in':
714
+ if (get_current_user_id() == 0 || count(array_intersect(woo_dicount_rules_generalHelper::getCurrentUserRoles(), $rule)) == 0) {
715
+ return false;
716
+ }
717
+ return true;
718
+ break;
719
+ case 'customer_email_tld':
720
+ $rule = explode(',', $rule);
721
+ foreach($rule as $key => $r){
722
+ $rule[$key] = trim($r);
723
+ $rule[$key] = trim($rule[$key], '.');
724
+ }
725
+ $postData = $this->postData->get('post_data', '', 'raw');
726
+ $postDataArray = array();
727
+ if($postData != ''){
728
+ parse_str($postData, $postDataArray);
729
+ }
730
+ $postBillingEmail = $this->postData->get('billing_email', '', 'raw');
731
+ if($postBillingEmail != ''){
732
+ $postDataArray['billing_email'] = $postBillingEmail;
733
+ }
734
+ if(!get_current_user_id()){
735
+ $order_id = $this->postData->get('order-received', 0);
736
+ if($order_id){
737
+ $order = new WC_Order( $order_id);
738
+ $postDataArray['billing_email'] = $order->billing_email;
739
+ }
740
+ }
741
+ if(isset($postDataArray['billing_email']) && $postDataArray['billing_email'] != ''){
742
+ $user_email = $postDataArray['billing_email'];
743
+ if(get_current_user_id()){
744
+ update_user_meta(get_current_user_id(), 'billing_email', $user_email);
745
+ }
746
+ $tld = $this->getTLDFromEmail($user_email);
747
+ if(in_array($tld, $rule)){
748
+ return true;
749
+ }
750
+ } else if(get_current_user_id()){
751
+ $user_email = get_user_meta( get_current_user_id(), 'billing_email', true );
752
+ if($user_email != '' && !empty($user_email)){
753
+ $tld = $this->getTLDFromEmail($user_email);
754
+ if(in_array($tld, $rule)){
755
+ return true;
756
+ }
757
+ } else {
758
+ $user_details = get_userdata( get_current_user_id() );
759
+ if(isset($user_details->data->user_email) && $user_details->data->user_email != ''){
760
+ $user_email = $user_details->data->user_email;
761
+ $tld = $this->getTLDFromEmail($user_email);
762
+ if(in_array($tld, $rule)){
763
+ return true;
764
+ }
765
+ }
766
+ }
767
+ }
768
+ return false;
769
+ break;
770
+ /*case 'categories_atleast_one':
771
+ if(count($rule)){
772
+ $w_categories = $this->getCartProductCaregories();
773
+ if(count($w_categories)){
774
+ foreach ($rule as $cat){
775
+ if(in_array($cat, $w_categories)){
776
+ return true;
777
+ }
778
+ }
779
+ }
780
+ }
781
+ return false;
782
+ break;*/
783
+
784
+ }
785
+
786
+ }
787
+
788
+ /**
789
+ * Get tld from email
790
+ * */
791
+ protected function getTLDFromEmail($email){
792
+ $emailArray = explode('@', $email);
793
+ if(isset($emailArray[1])){
794
+ $emailDomainArray = explode('.', $emailArray[1]);
795
+ if(count($emailDomainArray)>1){
796
+ unset($emailDomainArray[0]);
797
+ }
798
+ return implode('.', $emailDomainArray);
799
+ }
800
+ return $emailArray[0];
801
+ }
802
+
803
+ /**
804
+ * To get product categories
805
+ * */
806
+ /*public function getCartProductCaregories(){
807
+ global $woocommerce;
808
+ $product_cat_id = array();
809
+ if(count($woocommerce->cart->cart_contents)){
810
+ foreach ($woocommerce->cart->cart_contents as $cartItem) {
811
+ $terms = get_the_terms( $cartItem['product_id'], 'product_cat' );
812
+ if($terms)
813
+ foreach ($terms as $term) {
814
+ $product_cat_id[] = $term->term_id;
815
+ }
816
+ }
817
+ }
818
+ return $product_cat_id;
819
+ }*/
820
+
821
+ /**
822
+ * Get cart total amount
823
+ *
824
+ * @access public
825
+ * @return float
826
+ */
827
+ public function calculateCartSubtotal()
828
+ {
829
+ $cart_subtotal = 0;
830
+ // Iterate over all cart items and
831
+ foreach ($this->cart_items as $cart_item_key => $cart_item) {
832
+ $quantity = (isset($cart_item['quantity']) && $cart_item['quantity']) ? $cart_item['quantity'] : 1;
833
+ $cart_subtotal += $cart_item['data']->get_price() * $quantity;
834
+ }
835
+
836
+ $this->sub_total = (float)$cart_subtotal;
837
+ }
838
+
839
+ /**
840
+ * To Sum the Cart Item's Qty.
841
+ *
842
+ * @return int Total Qty of Cart.
843
+ */
844
+ public function cartItemQtyTotal()
845
+ {
846
+ global $woocommerce;
847
+ $cart_items = $woocommerce->cart->cart_contents;
848
+ $total_quantity = 0;
849
+
850
+ foreach ($cart_items as $cart_item) {
851
+ $current_quantity = (isset($cart_item['quantity']) && $cart_item['quantity']) ? $cart_item['quantity'] : 1;
852
+ $total_quantity += $current_quantity;
853
+ }
854
+ return $total_quantity;
855
+ }
856
+
857
+ /**
858
+ * Overall Discount Calculation based on Percentage or Flat.
859
+ *
860
+ * @param integer $sub_total Subtotal of the Cart.
861
+ * @param integer $adjustment percentage or discount of adjustment.
862
+ * @return integer Final Discount Amount.
863
+ */
864
+ public function calculateDiscount($sub_total, $adjustment)
865
+ {
866
+ $sub_total = ($sub_total < 0) ? 0 : $sub_total;
867
+
868
+ $discount = 0;
869
+
870
+ if ($adjustment['type'] == 'percentage') {
871
+ $discount = $sub_total * ($adjustment['value'] / 100);
872
+ } else if ($adjustment['type'] == 'price') {
873
+ $discount = $adjustment['value'];
874
+ }
875
+
876
+ return ($discount <= 0) ? 0 : $discount;
877
+ }
878
+
879
+ }
880
+ }
includes/discount-base.php CHANGED
@@ -1,9 +1,6 @@
1
  <?php
2
  if (!defined('ABSPATH')) exit; // Exit if accessed directly
3
 
4
- include_once(WOO_DISCOUNT_DIR . '/helper/general-helper.php');
5
- include_once(WOO_DISCOUNT_DIR . '/includes/pricing-rules.php');
6
- include_once(WOO_DISCOUNT_DIR . '/includes/cart-rules.php');
7
  global $woocommerce;
8
 
9
  /**
1
  <?php
2
  if (!defined('ABSPATH')) exit; // Exit if accessed directly
3
 
 
 
 
4
  global $woocommerce;
5
 
6
  /**
includes/pricing-rules-3.php ADDED
@@ -0,0 +1,1162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ if (!defined('ABSPATH')) exit; // Exit if accessed directly
3
+ include_once(WOO_DISCOUNT_DIR . '/helper/general-helper.php');
4
+
5
+ /**
6
+ * Class woo_dicount_rules_pricingRules
7
+ */
8
+ if (!class_exists('woo_dicount_rules_pricingRules')) {
9
+ class woo_dicount_rules_pricingRules
10
+ {
11
+ /**
12
+ * @var string
13
+ */
14
+ private $option_name = 'woo_discount_price_option';
15
+
16
+ /**
17
+ * @var string
18
+ */
19
+ public $post_type = 'woo_discount';
20
+
21
+ /**
22
+ * @var bool
23
+ */
24
+ public $discount_applied = false;
25
+
26
+ /**
27
+ * @var
28
+ */
29
+ private $rules;
30
+
31
+ /**
32
+ * @var
33
+ */
34
+ public $rule_sets;
35
+
36
+ /**
37
+ * @var
38
+ */
39
+ public $matched_sets;
40
+
41
+ /**
42
+ * @var
43
+ */
44
+ public $baseConfig;
45
+
46
+ /**
47
+ * @var
48
+ */
49
+ public $apply_to;
50
+
51
+ /**
52
+ * @var string
53
+ */
54
+ public $default_option = 'woo-discount-config';
55
+
56
+ public $postData;
57
+
58
+ /**
59
+ * woo_dicount_rules_pricingRules constructor.
60
+ */
61
+ public function __construct()
62
+ {
63
+ $this->updateBaseConfig();
64
+ $this->postData = \FlycartInput\FInput::getInstance();
65
+ }
66
+
67
+ /**
68
+ * Update the Base config with live.
69
+ */
70
+ public function updateBaseConfig()
71
+ {
72
+ $base = new woo_dicount_rules_WooDiscountBase();
73
+ $base = $base->getBaseConfig();
74
+ if (is_string($base)) $base = json_decode($base, true);
75
+ $this->baseConfig = $base;
76
+ $this->apply_to = (isset($base_config['price_setup']) ? $base_config['price_setup'] : 'all');
77
+ }
78
+
79
+ /**
80
+ * Saving the Price Rule Set.
81
+ *
82
+ * @param $request
83
+ * @return bool
84
+ */
85
+ public function save($request)
86
+ {
87
+ // var_dump($request);
88
+ // die();
89
+ // foreach ($request as $index => $value) {
90
+ // $request[$index] = $value;
91
+ // }
92
+
93
+ $id = (isset($request['rule_id']) ? $request['rule_id'] : false);
94
+
95
+ $id = intval($id);
96
+ if (!$id && $id != 0) return false;
97
+
98
+ $title = (isset($request['rule_name']) ? $request['rule_name'] : 'New');
99
+ $slug = str_replace(' ', '-', strtolower($title));
100
+
101
+ // To Lowercase.
102
+ $slug = strtolower($slug);
103
+
104
+ // Encoding String with Space.
105
+ $slug = str_replace(' ', '-', $slug);
106
+
107
+ if ($id) {
108
+ $post = array(
109
+ 'ID' => $id,
110
+ 'post_title' => $title,
111
+ 'post_name' => $slug,
112
+ 'post_content' => 'New Rule',
113
+ 'post_type' => $this->post_type,
114
+ 'post_status' => 'publish'
115
+ );
116
+ wp_update_post($post);
117
+ } else {
118
+ $post = array(
119
+ 'post_title' => $title,
120
+ 'post_name' => $slug,
121
+ 'post_content' => 'New Rule',
122
+ 'post_type' => $this->post_type,
123
+ 'post_status' => 'publish'
124
+ );
125
+ $id = wp_insert_post($post);
126
+ }
127
+
128
+ $form = array(
129
+ 'rule_name',
130
+ 'rule_descr',
131
+ 'rule_method',
132
+ 'qty_based_on',
133
+ 'date_from',
134
+ 'date_to',
135
+ 'apply_to',
136
+ 'customer',
137
+ 'min_qty',
138
+ 'max_qty',
139
+ 'discount_type',
140
+ 'to_discount',
141
+ 'status',
142
+ 'customer',
143
+ 'discount_range',
144
+ 'rule_order'
145
+ );
146
+
147
+ //----------------------------------------------------------------------------------------------------------
148
+ // Manage Products with it's ID or Category.
149
+ $apply_to = 'all_products';
150
+
151
+ if (isset($request['apply_to'])) $apply_to = $request['apply_to'];
152
+
153
+ if ($apply_to == 'specific_category') {
154
+ $apply_to = 'category_to_apply';
155
+ if(isset($request['is_cumulative']) && $request['is_cumulative'] == 1){
156
+ $request['is_cumulative'] = 1;
157
+ } else {
158
+ $request['is_cumulative'] = 0;
159
+ }
160
+ $form[] = 'is_cumulative';
161
+
162
+ if(isset($request['apply_child_categories']) && $request['apply_child_categories'] == 1){
163
+ $request['apply_child_categories'] = 1;
164
+ } else {
165
+ $request['apply_child_categories'] = 0;
166
+ }
167
+ $form[] = 'apply_child_categories';
168
+
169
+ } elseif ($apply_to == 'specific_products') {
170
+ $apply_to = 'product_to_apply';
171
+ }
172
+ $form[] = $apply_to;
173
+
174
+ if (isset($request[$apply_to])) $request[$apply_to] = json_encode($request[$apply_to]);
175
+ //----------------------------------------------------------------------------------------------------------
176
+
177
+ // Manage Users.
178
+ $apply_to = 'all';
179
+
180
+ if (isset($request['customer'])) $apply_to = $request['customer'];
181
+
182
+ if ($apply_to == 'only_given') {
183
+ $apply_to = 'users_to_apply';
184
+ }
185
+ $form[] = $apply_to;
186
+
187
+ if (isset($request[$apply_to])) $request[$apply_to] = json_encode($request[$apply_to]);
188
+ //----------------------------------------------------------------------------------------------------------
189
+
190
+ // Manage list of Discount Ranges.
191
+ if (isset($request['discount_range'])) {
192
+
193
+ foreach ($request['discount_range'] as $index => $value) {
194
+ $request['discount_range'][$index] = woo_dicount_rules_generalHelper::makeString($value);
195
+ $request['discount_range'][$index]['title'] = isset($request['rule_name']) ? $request['rule_name'] : '';
196
+
197
+ }
198
+
199
+ $request['discount_range'] = json_encode($request['discount_range']);
200
+ } else {
201
+ // Reset the Discount Range, if its empty.
202
+ $request['discount_range'] = '';
203
+ }
204
+
205
+ $request['status'] = 'publish';
206
+
207
+ if (is_null($id) || !isset($id)) return false;
208
+
209
+ foreach ($request as $index => $value) {
210
+ if (in_array($index, $form)) {
211
+ if (get_post_meta($id, $index)) {
212
+ update_post_meta($id, $index, $value);
213
+ } else {
214
+ add_post_meta($id, $index, $value);
215
+ }
216
+ }
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Load View with Specif post id.
222
+ *
223
+ * @param $option
224
+ * @param integer $id Post ID.
225
+ * @return string mixed response.
226
+ */
227
+ public function view($option, $id)
228
+ {
229
+ $id = intval($id);
230
+ if (!$id) return false;
231
+ $post = get_post($id, 'OBJECT');
232
+ if (isset($post)) {
233
+ if (isset($post->ID)) {
234
+ $post->meta = get_post_meta($post->ID);
235
+ }
236
+ }
237
+ return $post;
238
+ }
239
+
240
+ // -------------------------------------------------RULE IMPLEMENTATION---------------------------------------------
241
+
242
+ /**
243
+ * To Analyzing the Pricing Rules to Apply the Discount in terms of price.
244
+ */
245
+ public function analyse($woocommerce)
246
+ {
247
+ $this->organizeRules();
248
+ $this->applyRules();
249
+ $this->initAdjustment();
250
+ }
251
+
252
+ /**
253
+ * To Organizing the rules to make possible sets.
254
+ */
255
+ public function organizeRules()
256
+ {
257
+ // Loads the Rules to Global.
258
+ $this->getRules();
259
+ // Validate and Re-Assign the Rules.
260
+ $this->filterRules();
261
+ }
262
+
263
+ /**
264
+ * To Get Set of Rules.
265
+ *
266
+ * @return mixed
267
+ */
268
+ public function getRules($onlyCount = false)
269
+ {
270
+ $posts = get_posts(array('post_type' => $this->post_type));
271
+ if ($onlyCount) return count($posts);
272
+ if (isset($posts) && count($posts) > 0) {
273
+ foreach ($posts as $index => $item) {
274
+ $posts[$index]->meta = get_post_meta($posts[$index]->ID);
275
+ }
276
+ $this->rules = $posts;
277
+ }
278
+ return $posts;
279
+ }
280
+
281
+ /**
282
+ * To Updating the Log of Implemented Price Discounts.
283
+ *
284
+ * @return bool
285
+ */
286
+ public function makeLog()
287
+ {
288
+ if (is_null($this->matched_sets)) return false;
289
+
290
+ $discount_log = array(
291
+ 'line_discount' => $this->matched_sets,
292
+ );
293
+ WC()->session->set('woo_price_discount', json_encode($discount_log));
294
+ }
295
+
296
+ /**
297
+ * @return array
298
+ */
299
+ public function getBaseConfig()
300
+ {
301
+ $option = get_option($this->default_option);
302
+ if (!$option || is_null($option)) {
303
+ return array();
304
+ } else {
305
+ return $option;
306
+ }
307
+ }
308
+
309
+ /**
310
+ * List of Checklist.
311
+ */
312
+ public function checkPoint()
313
+ {
314
+ // Apply rules with products.
315
+ // NOT YET USED.
316
+ if ($this->discount_applied) return true;
317
+ }
318
+
319
+ /**
320
+ * Filter the Rules with some validations.
321
+ */
322
+ public function filterRules()
323
+ {
324
+ $rules = $this->rules;
325
+
326
+ if (is_null($rules) || !isset($rules)) return false;
327
+
328
+ // Start with empty set.
329
+ $rule_set = array();
330
+
331
+ foreach ($rules as $index => $rule) {
332
+ $status = (isset($rule->status) ? $rule->status : false);
333
+
334
+ // To Check as Plugin Active - InActive.
335
+ if ($status == 'publish') {
336
+ $date_from = (isset($rule->date_from) ? strtotime($rule->date_from) : false);
337
+ $date_to = (isset($rule->date_to) ? strtotime($rule->date_to) : false);
338
+ $today = strtotime(date('m/d/Y'));
339
+
340
+ // Validating Rule with Date of Expiry.
341
+ if (($date_from <= $today) && (($date_to == '') || ($date_to >= $today))) {
342
+
343
+ // Validating the Rule with its Order ID.
344
+ if (isset($rule->rule_order)) {
345
+ // If Order ID is '-', then this rule not going to implement.
346
+ if ($rule->rule_order !== '-') {
347
+ $rule_set[] = $rule;
348
+ }
349
+ }
350
+ }
351
+ }
352
+ }
353
+ $this->rules = $rule_set;
354
+
355
+ // To Order the Rules, based on its order ID.
356
+ $this->orderRules();
357
+ }
358
+
359
+ /**
360
+ * Ordering the Set of Rules.
361
+ *
362
+ * @return bool
363
+ */
364
+ public function orderRules()
365
+ {
366
+ if (empty($this->rules)) return false;
367
+
368
+ $ordered_rules = array();
369
+
370
+ // Make associative array with Order ID.
371
+ foreach ($this->rules as $index => $rule) {
372
+ if (isset($rule->rule_order)) {
373
+ if ($rule->rule_order != '') {
374
+ $ordered_rules[$rule->rule_order] = $rule;
375
+ }
376
+ }
377
+ }
378
+ // Order the Rules with it's priority.
379
+ ksort($ordered_rules);
380
+
381
+ $this->rules = $ordered_rules;
382
+ }
383
+
384
+ /**
385
+ * Apply the Rules to line items.
386
+ *
387
+ * @return bool
388
+ */
389
+ public function applyRules()
390
+ {
391
+ global $woocommerce;
392
+
393
+ // If there is no rules, then return false.
394
+ if (!isset($this->rules)) return false;
395
+
396
+ // Check point having list of checklist to apply.
397
+ if ($this->checkPoint()) return false;
398
+
399
+ // To Generate Valid Rule sets.
400
+ $this->generateRuleSets($woocommerce);
401
+ // Sort cart by price ascending
402
+
403
+ $cart_contents = $this->sortCartPrice($woocommerce->cart->cart_contents, 'asc');
404
+ foreach ($cart_contents as $index => $item) {
405
+ $this->matchRules($index, $item);
406
+ }
407
+ $this->makeLog();
408
+ }
409
+
410
+ /**
411
+ * Generate the Suitable and active rule sets.
412
+ *
413
+ * @param $woocommerce
414
+ * @return bool
415
+ */
416
+ public function generateRuleSets($woocommerce)
417
+ {
418
+ $rule_sets = array();
419
+
420
+ if (!isset($this->rules)) return false;
421
+
422
+ // Loop the Rules set to collect matched rules.
423
+ foreach ($this->rules as $index => $rule) {
424
+ // General Rule Info.
425
+ $rule_sets[$index]['discount_type'] = 'price_discount';
426
+ $rule_sets[$index]['name'] = (isset($rule->rule_name) ? $rule->rule_name : 'Rule_' . $index);
427
+ $rule_sets[$index]['descr'] = (isset($rule->rule_descr) ? $rule->rule_descr : '');
428
+ $rule_sets[$index]['method'] = (isset($rule->rule_method) ? $rule->rule_method : 'qty_based');
429
+ $rule_sets[$index]['qty_based_on'] = (isset($rule->qty_based_on) ? $rule->qty_based_on : 'each_product');
430
+ $rule_sets[$index]['date_from'] = (isset($rule->date_from) ? $rule->date_from : false);
431
+ $rule_sets[$index]['date_to'] = (isset($rule->date_to) ? $rule->date_to : false);
432
+
433
+ // List the type of apply, by Product or by Category.
434
+ if (isset($rule->apply_to)) {
435
+ // If Rule is processed by Specific Products, then..
436
+ if ($rule->apply_to == 'specific_products') {
437
+ if (isset($rule->product_to_apply)) {
438
+ $rule_sets[$index]['type']['specific_products'] = $this->checkWithProducts($rule, $woocommerce);
439
+ }
440
+ } else if ($rule->apply_to == 'specific_category') {
441
+ if (isset($rule->apply_child_categories) && $rule->apply_child_categories) {
442
+ $rule_sets[$index]['type']['apply_child_categories'] = 1;
443
+ } else {
444
+ $rule_sets[$index]['type']['apply_child_categories'] = 0;
445
+ }
446
+
447
+ if (isset($rule->category_to_apply)) {
448
+ $rule_sets[$index]['type']['specific_category'] = $this->checkWithCategory($rule, $woocommerce);
449
+ if($rule_sets[$index]['type']['apply_child_categories']){
450
+ $cat = $rule_sets[$index]['type']['specific_category'];
451
+ $rule_sets[$index]['type']['specific_category'] = $this->getAllSubCategories($cat);
452
+ }
453
+ }
454
+ if (isset($rule->is_cumulative) && $rule->is_cumulative) {
455
+ $rule_sets[$index]['type']['is_cumulative'] = 1;
456
+ } else {
457
+ $rule_sets[$index]['type']['is_cumulative'] = 0;
458
+ }
459
+ } else {
460
+ $rule_sets[$index]['type'] = 'all';
461
+ }
462
+
463
+ $rule_sets[$index]['discount'] = 0;
464
+ if (isset($rule->discount_range)) {
465
+ if ($rule->discount_range != '') {
466
+ $rule_sets[$index]['discount'] = $this->getDiscountRangeList($rule);
467
+ }
468
+ }
469
+
470
+ // Default setup for all customers.
471
+ $rule_sets[$index]['allow']['users'] = 'all';
472
+ // If Rule is processed by Specific Customers, then..
473
+ if ($rule->customer == 'only_given') {
474
+ if (isset($rule->users_to_apply)) {
475
+ $rule_sets[$index]['allow']['users'] = $this->checkWithUsers($rule, $woocommerce);
476
+ }
477
+ }
478
+ $rule_sets[$index]['apply_to'] = $rule->apply_to;
479
+ }
480
+
481
+ // If Current Customer is not Allowed to use this discount, then it's going to be removed.
482
+ if ($rule_sets[$index]['allow']['users'] == 'no') {
483
+ unset($rule_sets[$index]);
484
+ }
485
+ }
486
+ $this->rule_sets = $rule_sets;
487
+ }
488
+
489
+ /**
490
+ * Get all sub categories
491
+ * */
492
+ public function getAllSubCategories($cat){
493
+ $category_with_sub_cat = $cat;
494
+ foreach($cat as $c) {
495
+ $args = array('hierarchical' => 1,
496
+ 'show_option_none' => '',
497
+ 'hide_empty' => 0,
498
+ 'parent' => $c,
499
+ 'taxonomy' => 'product_cat');
500
+ $categories = get_categories( $args );
501
+ foreach($categories as $category) {
502
+ $category_with_sub_cat[] = $category->term_id;
503
+ }
504
+ }
505
+ $category_with_sub_cat = array_unique($category_with_sub_cat);
506
+
507
+ return $category_with_sub_cat;
508
+ }
509
+
510
+ /**
511
+ * Fetch back the Matched rules.
512
+ *
513
+ * @param $index
514
+ * @param array $item line item.
515
+ */
516
+ public function matchRules($index, $item)
517
+ {
518
+ $applied_rules = array();
519
+ $quantity = (isset($item['quantity']) ? $item['quantity'] : 0);
520
+ $i = 0;
521
+ foreach ($this->rule_sets as $id => $rule) {
522
+
523
+ if (isset($rule['type']) && isset($rule['apply_to'])) {
524
+
525
+ // Working with Products and Category.
526
+ switch ($rule['apply_to']) {
527
+
528
+ case 'specific_products':
529
+
530
+ if ($this->isItemInProductList($rule['type']['specific_products'], $item)) {
531
+ $applied_rules[$i]['amount'] = $this->getAdjustmentAmount($quantity, $this->array_first($rule['discount']));
532
+ $applied_rules[$i]['name'] = $rule['name'];
533
+ $applied_rules[$i]['item'] = $index;
534
+ $applied_rules[$i]['id'] = $item['product_id'];
535
+ }
536
+
537
+ break;
538
+
539
+ case 'specific_category':
540
+ if ($this->isItemInCategoryList($rule['type']['specific_category'], $item)) {
541
+ if(isset($rule['type']['is_cumulative']) && $rule['type']['is_cumulative']){
542
+ $totalQuantityInThisCategory = $this->getProductQuantityInThisCategory($rule['type']['specific_category']);
543
+ $quantity = $totalQuantityInThisCategory;
544
+ }
545
+ $applied_rules[$i]['amount'] = $this->getAdjustmentAmount($quantity, $this->array_first($rule['discount']));
546
+ $applied_rules[$i]['name'] = $rule['name'];
547
+ $applied_rules[$i]['item'] = $index;
548
+ $applied_rules[$i]['id'] = $item['product_id'];
549
+ }
550
+
551
+
552
+ break;
553
+
554
+ case 'all_products':
555
+ default:
556
+
557
+ $applied_rules[$i]['amount'] = $this->getAdjustmentAmount($quantity, $this->array_first($rule['discount']));
558
+ $applied_rules[$i]['name'] = $rule['name'];
559
+ $applied_rules[$i]['item'] = $index;
560
+ $applied_rules[$i]['id'] = $item['product_id'];
561
+
562
+ break;
563
+ }
564
+ }
565
+ $i++;
566
+ }
567
+ $this->matched_sets[$index] = $applied_rules;
568
+ }
569
+
570
+ /**
571
+ * Get quantity of products in specific category
572
+ * */
573
+ public function getProductQuantityInThisCategory($category){
574
+ global $woocommerce;
575
+ $quantity = 0;
576
+ if(count($woocommerce->cart->cart_contents)){
577
+ foreach ($woocommerce->cart->cart_contents as $cartItem) {
578
+ $terms = get_the_terms( $cartItem['product_id'], 'product_cat' );
579
+ if($terms){
580
+ $has = 0;
581
+ foreach ($terms as $term) {
582
+ if(in_array($term->term_id, $category)){
583
+ $has = 1;
584
+ }
585
+ }
586
+ if($has){
587
+ $quantity = $quantity + $cartItem['quantity'];
588
+ }
589
+ }
590
+ }
591
+ }
592
+ return $quantity;
593
+ }
594
+
595
+ /**
596
+ * Return the First index.
597
+ *
598
+ * @param $array
599
+ * @return mixed
600
+ */
601
+ public function array_first($array)
602
+ {
603
+ if (is_object($array)) $array = (array)$array;
604
+ if (is_array($array)) return $array;
605
+ foreach ($array as $first) {
606
+ return $first;
607
+ }
608
+ }
609
+
610
+ /**
611
+ * Return the Adjustment amount.
612
+ *
613
+ * @param $quantity
614
+ * @param $discount_range
615
+ * @return array|bool
616
+ */
617
+ public function getAdjustmentAmount($quantity, $discount_ranges)
618
+ {
619
+ $adjustment = array();
620
+ foreach($discount_ranges as $discount_range) {
621
+
622
+ if (!is_array($discount_range) && !is_object($discount_range)) return false;
623
+ $range = is_array($discount_range) ? (object) $discount_range : $discount_range;
624
+ $min = (isset($range->min_qty) ? $range->min_qty : 0);
625
+ $max = (isset($range->max_qty) ? $range->max_qty : false);
626
+
627
+ $type = (isset($range->discount_type) ? $range->discount_type : 'price_discount');
628
+
629
+ if ($max == false) continue;
630
+
631
+ if ((int)$min <= (int)$quantity && (int)$max >= (int)$quantity) {
632
+ $adjustment[$type] = (isset($range->to_discount) ? $range->to_discount : 0);
633
+ }
634
+
635
+ }
636
+
637
+ return $adjustment;
638
+ }
639
+
640
+ /**
641
+ * Validating the Active user with rule sets.
642
+ *
643
+ * @param $rule
644
+ * @return string
645
+ */
646
+ public function manageUserAccess($rule)
647
+ {
648
+ $allowed = 'no';
649
+ if (!isset($rule->users_to_apply)) return $allowed;
650
+
651
+ $users = $rule->users_to_apply;
652
+
653
+ if (is_string($users)) $users = json_decode($users, True);
654
+
655
+ if (!is_array($users)) return $allowed;
656
+
657
+ $user = get_current_user_id();
658
+
659
+ if (count(array_intersect($users, array($user))) > 0) {
660
+ $allowed = 'yes';
661
+ }
662
+
663
+ return $allowed;
664
+ }
665
+
666
+ /**
667
+ * To Check active cart items are in the rules list item.
668
+ *
669
+ * @param $product_list
670
+ * @param $product
671
+ * @return bool
672
+ */
673
+ public function isItemInProductList($product_list, $product)
674
+ {
675
+ if (!isset($product['product_id'])) return false;
676
+ if (!is_array($product_list)) $product_list = (array)$product_list;
677
+ if (count(array_intersect($product_list, array($product['product_id']))) == 1) {
678
+ return true;
679
+ } else {
680
+ return false;
681
+ }
682
+ }
683
+
684
+ /**
685
+ * To Check that the items are in specified category.
686
+ *
687
+ * @param $category_list
688
+ * @param $product
689
+ * @return bool
690
+ */
691
+ public function isItemInCategoryList($category_list, $product)
692
+ {
693
+
694
+ $helper = new woo_dicount_rules_generalHelper();
695
+ $all_category = $helper->getCategoryList();
696
+ if (!isset($product['product_id'])) return false;
697
+ $product_category = woo_dicount_rules_generalHelper::getCategoryByPost($product);
698
+
699
+ $status = false;
700
+ //check any one of category matches
701
+ $matching_cats = array_intersect($product_category, $category_list);
702
+ $result = !empty( $matching_cats );
703
+ if($result){
704
+ $status = true;
705
+ }
706
+
707
+ return $status;
708
+ }
709
+
710
+ /**
711
+ *
712
+ */
713
+ public function isUserInCustomerList()
714
+ {
715
+
716
+ }
717
+
718
+ /**
719
+ * Sort cart by price
720
+ *
721
+ * @access public
722
+ * @param array $cart
723
+ * @param string $order
724
+ * @return array
725
+ */
726
+ public function sortCartPrice($cart, $order)
727
+ {
728
+ $cart_sorted = array();
729
+
730
+ foreach ($cart as $cart_item_key => $cart_item) {
731
+ $cart_sorted[$cart_item_key] = $cart_item;
732
+ }
733
+
734
+ uasort($cart_sorted, array($this, 'sortCartByPrice_' . $order));
735
+
736
+ return $cart_sorted;
737
+ }
738
+
739
+ /**
740
+ * Sort cart by price uasort collable - ascending
741
+ *
742
+ * @access public
743
+ * @param mixed $first
744
+ * @param mixed $second
745
+ * @return bool
746
+ */
747
+ public function sortCartByPrice_asc($first, $second)
748
+ {
749
+ if (isset($first['data'])) {
750
+ if ($first['data']->get_price() == $second['data']->get_price()) {
751
+ return 0;
752
+ }
753
+ }
754
+ return ($first['data']->get_price() < $second['data']->get_price()) ? -1 : 1;
755
+ }
756
+
757
+ /**
758
+ * Sort cart by price uasort collable - descending
759
+ *
760
+ * @access public
761
+ * @param mixed $first
762
+ * @param mixed $second
763
+ * @return bool
764
+ */
765
+ public function sortCartByPrice_desc($first, $second)
766
+ {
767
+ if (isset($first['data'])) {
768
+ if ($first['data']->get_price() == $second['data']->get_price()) {
769
+ return 0;
770
+ }
771
+ }
772
+ return ($first['data']->get_price() > $second['data']->get_price()) ? -1 : 1;
773
+ }
774
+
775
+ /**
776
+ * Return the List of Products to Apply.
777
+ *
778
+ * @param $woocommerce
779
+ * @param $rule
780
+ * @return array
781
+ */
782
+ public function checkWithProducts($rule, $woocommerce)
783
+ {
784
+ $specific_product_list = array();
785
+ if (is_string($rule->product_to_apply)) {
786
+ $specific_product_list = json_decode($rule->product_to_apply, true);
787
+ }
788
+ return $specific_product_list;
789
+ }
790
+
791
+ /**
792
+ * Check with category list.
793
+ *
794
+ * @param $rule
795
+ * @param $woocommerce
796
+ * @return array|mixed
797
+ */
798
+ public function checkWithCategory($rule, $woocommerce)
799
+ {
800
+ $specific_category_list = array();
801
+ if (is_string($rule->category_to_apply)) {
802
+ $specific_category_list = json_decode($rule->category_to_apply, true);
803
+ }
804
+ return $specific_category_list;
805
+ }
806
+
807
+ /**
808
+ * Check with User list.
809
+ *
810
+ * @param $rule
811
+ * @param $woocommerce
812
+ * @return array|mixed
813
+ */
814
+ public function checkWithUsers($rule, $woocommerce)
815
+ {
816
+ // Return as , User is allowed to use this discount or not.
817
+ // Working Users.
818
+ return $this->manageUserAccess($rule);
819
+ }
820
+
821
+ /**
822
+ * To Return the Discount Ranges.
823
+ *
824
+ * @param $rule
825
+ * @return array|mixed
826
+ */
827
+ public function getDiscountRangeList($rule)
828
+ {
829
+ $discount_range_list = array();
830
+ if (is_string($rule->discount_range)) {
831
+ $discount_range_list = json_decode($rule->discount_range);
832
+ }
833
+ return $discount_range_list;
834
+ }
835
+
836
+ /**
837
+ * For Display the price discount of a product.
838
+ */
839
+ public function priceTable()
840
+ {
841
+ global $product;
842
+
843
+ $config = $this->baseConfig;
844
+ $show_discount = true;
845
+ // Base Config to Check whether display table or not.
846
+ if (isset($config['show_discount_table'])) {
847
+ if ($config['show_discount_table'] == 'show') {
848
+ $show_discount = true;
849
+ } else {
850
+ $show_discount = false;
851
+ }
852
+ }
853
+ // If Only allowed to display, then only its display the table.
854
+ if ($show_discount) {
855
+ $table_data = $this->generateDiscountTableData($product);
856
+ $path = WOO_DISCOUNT_DIR . '/view/template/discount-table.php';
857
+ echo $this->generateTableHtml($table_data, $path);
858
+ }
859
+
860
+ }
861
+
862
+ /**
863
+ * To generate the Discount table data.
864
+ *
865
+ * @param $product
866
+ * @return array|bool|string
867
+ */
868
+ public function generateDiscountTableData($product)
869
+ {
870
+ $id = (($product->get_id() != 0 && $product->get_id() != null) ? $product->get_id() : 0);
871
+ if ($id == 0) return false;
872
+
873
+ $this->organizeRules();
874
+
875
+ $discount_range = array();
876
+ foreach ($this->rules as $index => $rule) {
877
+ $status = false;
878
+
879
+ // Check with Active User Filter.
880
+ if (isset($rule->customer)) {
881
+ $status = false;
882
+ if ($rule->customer == 'all') {
883
+ $status = true;
884
+ } else {
885
+ $users = (is_string($rule->users_to_apply) ? json_decode($rule->users_to_apply, true) : array());
886
+ $user_id = get_current_user_id();
887
+ if (count(array_intersect($users, array($user_id))) > 0) {
888
+ $status = true;
889
+ }
890
+ }
891
+ }
892
+
893
+ if ($rule->apply_to == 'specific_products') {
894
+
895
+ // Check with Product Filter.
896
+ $products_to_apply = json_decode($rule->product_to_apply);
897
+
898
+ if ($rule->product_to_apply == null) $status = true;
899
+
900
+ if ($rule->product_to_apply != null) {
901
+ $status = false;
902
+ if (array_intersect($products_to_apply, array($id)) > 0) {
903
+ $status = true;
904
+ }
905
+ }
906
+ } elseif ($rule->apply_to == 'specific_category') {
907
+
908
+ // Check with Product Category Filter.
909
+ $category = woo_dicount_rules_generalHelper::getCategoryByPost($id, true);
910
+
911
+ if ($rule->category_to_apply == null) $status = true;
912
+
913
+ if ($rule->category_to_apply != null) {
914
+ $category_to_apply = json_decode($rule->category_to_apply);
915
+ if(isset($rule->apply_child_categories) && $rule->apply_child_categories == 1){
916
+ $category_to_apply = $this->getAllSubCategories($category_to_apply);
917
+ }
918
+ woo_dicount_rules_generalHelper::toInt($category_to_apply);
919
+ $status = false;
920
+ if (count(array_intersect($category_to_apply, $category)) > 0) {
921
+ $status = true;
922
+ }
923
+ }
924
+
925
+ } else if ($rule->apply_to == 'all_products') {
926
+ $status = true;
927
+ }
928
+
929
+
930
+ if ($status) {
931
+ $discount_range[] = (isset($rule->discount_range) ? json_decode($rule->discount_range) : array());
932
+ }
933
+ }
934
+ return $discount_range;
935
+ }
936
+
937
+ /**
938
+ * To Return the HTML table for show available discount ranges.
939
+ *
940
+ * @param $table_data
941
+ * @param $path
942
+ * @return bool|string
943
+ */
944
+ public function generateTableHtml($table_data, $path)
945
+ {
946
+ ob_start();
947
+ if (!isset($table_data)) return false;
948
+ if (!isset($path) || empty($path) || is_null($path)) return false;
949
+ if (!file_exists($path)) return false;
950
+ $data = $this->getBaseConfig();
951
+ include($path);
952
+ $html = ob_get_contents();
953
+ ob_clean();
954
+ return $html;
955
+ }
956
+
957
+ /**
958
+ * Start Implementing the adjustments.
959
+ *
960
+ * @return bool
961
+ */
962
+ public function initAdjustment()
963
+ {
964
+ global $woocommerce;
965
+
966
+ // Get settings
967
+ $config = new woo_dicount_rules_WooDiscountBase();
968
+ $config = $config->getBaseConfig();
969
+ if (is_string($config)) $config = json_decode($config, true);
970
+ if(isset($config['price_setup'])){
971
+ $type = $config['price_setup'];
972
+ } else {
973
+ $type = 'all';
974
+ }
975
+
976
+ $cart_items = $woocommerce->cart->cart_contents;
977
+
978
+ foreach ($cart_items as $cart_item_key => $cart_item) {
979
+ $this->applyAdjustment($cart_item, $cart_item_key, $type);
980
+ }
981
+ }
982
+
983
+ /**
984
+ * Start Implement adjustment on individual items in the cart.
985
+ *
986
+ * @param $cart_item
987
+ * @param $cart_item_key
988
+ * @param $type
989
+ * @return bool
990
+ */
991
+ public function applyAdjustment($cart_item, $cart_item_key, $type)
992
+ {
993
+ global $woocommerce;
994
+
995
+ // All Sets are Collected properly, just process with that.
996
+ if (!isset($cart_item)) return false;
997
+
998
+ // If Product having the rule sets then,
999
+ if (!isset($this->matched_sets[$cart_item_key])) return false;
1000
+
1001
+ $adjustment_set = $this->matched_sets[$cart_item_key];
1002
+
1003
+ $price = $woocommerce->cart->cart_contents[$cart_item_key]['data']->get_price();
1004
+
1005
+ if ($type == 'first') {
1006
+ // For Apply the First Rule.
1007
+ $discount = $this->getAmount($adjustment_set, $price, 'first');
1008
+ $amount = $price - $discount;
1009
+ $log = 'Discount | ' . $discount;
1010
+ $this->applyDiscount($cart_item_key, $amount, $log);
1011
+ } else if ($type == 'biggest') {
1012
+ // For Apply the Biggest Discount.
1013
+ $discount = $this->getAmount($adjustment_set, $price, 'biggest');
1014
+ $amount = $price - $discount;
1015
+ $log = 'Discount | ' . $discount;
1016
+ $this->applyDiscount($cart_item_key, $amount, $log);
1017
+ } else {
1018
+ // For Apply All Rules.
1019
+ $discount = $this->getAmount($adjustment_set, $price);
1020
+ $amount = $price - $discount;
1021
+ $log = 'Discount | ' . $discount;
1022
+ $this->applyDiscount($cart_item_key, $amount, $log);
1023
+ }
1024
+ }
1025
+
1026
+ /**
1027
+ * To Get Amount based on the Setting that specified.
1028
+ *
1029
+ * @param $sets
1030
+ * @param $price
1031
+ * @param string $by
1032
+ * @return bool|float|int
1033
+ */
1034
+ public function getAmount($sets, $price, $by = 'all')
1035
+ {
1036
+ $discount = 0;
1037
+ $overall_discount = 0;
1038
+
1039
+ if (!isset($sets) || empty($sets)) return false;
1040
+
1041
+ if ($price == 0) return $price;
1042
+
1043
+ // For the biggest price, it compares the current product's price.
1044
+ if ($by == 'biggest') {
1045
+ $discount = $this->getBiggestDiscount($sets, $price);
1046
+ return $discount;
1047
+ }
1048
+
1049
+ foreach ($sets as $id => $set) {
1050
+ // For the First price, it will return the amount after get hit.
1051
+ if ($by == 'first') {
1052
+ if (isset($set['amount']['percentage_discount'])) {
1053
+ $discount = ($price / 100) * $set['amount']['percentage_discount'];
1054
+ } else if (isset($set['amount']['price_discount'])) {
1055
+ $discount = $set['amount']['price_discount'];
1056
+ }
1057
+ return $discount;
1058
+ } else {
1059
+ // For All, All rules going to apply.
1060
+ if (isset($set['amount']['percentage_discount'])) {
1061
+ $discount = ($price / 100) * $set['amount']['percentage_discount'];
1062
+ // Append all Discounts.
1063
+ $overall_discount = $overall_discount + $discount;
1064
+ } else if (isset($set['amount']['price_discount'])) {
1065
+ $discount = $set['amount']['price_discount'];
1066
+ // Append all Discounts.
1067
+ $overall_discount = $overall_discount + $discount;
1068
+ }
1069
+ }
1070
+ }
1071
+ return $overall_discount;
1072
+ }
1073
+
1074
+ /**
1075
+ * To Return the Biggest Discount across the available rule sets.
1076
+ *
1077
+ * @param $discount_list
1078
+ * @param $price
1079
+ * @return float|int
1080
+ */
1081
+ public function getBiggestDiscount($discount_list, $price)
1082
+ {
1083
+ $big = 0;
1084
+ // $amount = $price;
1085
+ $amount = 0;
1086
+ foreach ($discount_list as $id => $discount_item) {
1087
+ $amount_type = (isset($discount_item['amount']['percentage_discount']) ? 'percentage_discount' : 'price_discount');
1088
+ if ($amount_type == 'percentage_discount') {
1089
+ if (isset($discount_item['amount']['percentage_discount'])) {
1090
+ $amount = (($price / 100) * $discount_item['amount']['percentage_discount']);
1091
+ }
1092
+ } else {
1093
+ if (isset($discount_item['amount']['price_discount'])) {
1094
+ $amount = $discount_item['amount']['price_discount'];
1095
+ }
1096
+ }
1097
+
1098
+ if ($big < $amount) {
1099
+ $big = $amount;
1100
+ }
1101
+ }
1102
+ return $big;
1103
+ }
1104
+
1105
+ /**
1106
+ * Finally Apply the Discount to the Cart item by update to WooCommerce Instance.
1107
+ *
1108
+ * @param $item
1109
+ * @param $amount
1110
+ * @param $log
1111
+ */
1112
+ public function applyDiscount($item, $amount, $log)
1113
+ {
1114
+ global $woocommerce;
1115
+ // Make sure item exists in cart
1116
+ if (!isset($woocommerce->cart->cart_contents[$item])) {
1117
+ return;
1118
+ }
1119
+ // Log changes
1120
+ $woocommerce->cart->cart_contents[$item]['woo_discount'] = array(
1121
+ 'original_price' => get_option('woocommerce_tax_display_cart') == 'excl' ? wc_get_price_excluding_tax( $woocommerce->cart->cart_contents[$item]['data'] ) : wc_get_price_including_tax( $woocommerce->cart->cart_contents[$item]['data'] ),
1122
+ 'log' => $log,
1123
+ );
1124
+
1125
+ // Actually adjust price in cart
1126
+ // $woocommerce->cart->cart_contents[$item]['data']->price = $amount;
1127
+ $woocommerce->cart->cart_contents[$item]['data']->set_price($amount);
1128
+
1129
+ }
1130
+
1131
+ /**
1132
+ * For Show the Actual Discount of a product.
1133
+ *
1134
+ * @param integer $item_price Actual Price.
1135
+ * @param object $cart_item Cart Items.
1136
+ * @param string $cart_item_key to identify the item from cart.
1137
+ * @return string processed price of a product.
1138
+ */
1139
+ public function replaceVisiblePricesCart($item_price, $cart_item, $cart_item_key)
1140
+ {
1141
+
1142
+ if (!isset($cart_item['woo_discount'])) {
1143
+ return $item_price;
1144
+ }
1145
+
1146
+ // Get price to display
1147
+ $price = get_option('woocommerce_tax_display_cart') == 'excl' ? wc_get_price_excluding_tax($cart_item['data']) : wc_get_price_including_tax($cart_item['data']);
1148
+
1149
+ // Format price to display
1150
+ $price_to_display = woo_dicount_rules_generalHelper::wcVersion('2.1') ? wc_price($price) : woocommerce_price($price);
1151
+ $original_price_to_display = woo_dicount_rules_generalHelper::wcVersion('2.1') ? wc_price($cart_item['woo_discount']['original_price']) : woocommerce_price($cart_item['woo_discount']['original_price']);
1152
+
1153
+ if ($cart_item['woo_discount']['original_price'] !== $price) {
1154
+ $item_price = '<span class="cart_price"><del>' . $original_price_to_display . '</del> <ins>' . $price_to_display . '</ins></span>';
1155
+ } else {
1156
+ $item_price = $price_to_display;
1157
+ }
1158
+
1159
+ return $item_price;
1160
+ }
1161
+ }
1162
+ }
includes/pricing-rules.php CHANGED
@@ -1050,7 +1050,7 @@ if (!class_exists('woo_dicount_rules_pricingRules')) {
1050
  // For the First price, it will return the amount after get hit.
1051
  if ($by == 'first') {
1052
  if (isset($set['amount']['percentage_discount'])) {
1053
- $discount = ((int)$price / 100) * (int)$set['amount']['percentage_discount'];
1054
  } else if (isset($set['amount']['price_discount'])) {
1055
  $discount = $set['amount']['price_discount'];
1056
  }
@@ -1058,7 +1058,7 @@ if (!class_exists('woo_dicount_rules_pricingRules')) {
1058
  } else {
1059
  // For All, All rules going to apply.
1060
  if (isset($set['amount']['percentage_discount'])) {
1061
- $discount = ((int)$price / 100) * (int)$set['amount']['percentage_discount'];
1062
  // Append all Discounts.
1063
  $overall_discount = $overall_discount + $discount;
1064
  } else if (isset($set['amount']['price_discount'])) {
@@ -1081,7 +1081,8 @@ if (!class_exists('woo_dicount_rules_pricingRules')) {
1081
  public function getBiggestDiscount($discount_list, $price)
1082
  {
1083
  $big = 0;
1084
- $amount = $price;
 
1085
  foreach ($discount_list as $id => $discount_item) {
1086
  $amount_type = (isset($discount_item['amount']['percentage_discount']) ? 'percentage_discount' : 'price_discount');
1087
  if ($amount_type == 'percentage_discount') {
@@ -1094,7 +1095,7 @@ if (!class_exists('woo_dicount_rules_pricingRules')) {
1094
  }
1095
  }
1096
 
1097
- if ((int)$big < (int)$amount) {
1098
  $big = $amount;
1099
  }
1100
  }
1050
  // For the First price, it will return the amount after get hit.
1051
  if ($by == 'first') {
1052
  if (isset($set['amount']['percentage_discount'])) {
1053
+ $discount = ($price / 100) * $set['amount']['percentage_discount'];
1054
  } else if (isset($set['amount']['price_discount'])) {
1055
  $discount = $set['amount']['price_discount'];
1056
  }
1058
  } else {
1059
  // For All, All rules going to apply.
1060
  if (isset($set['amount']['percentage_discount'])) {
1061
+ $discount = ($price / 100) * $set['amount']['percentage_discount'];
1062
  // Append all Discounts.
1063
  $overall_discount = $overall_discount + $discount;
1064
  } else if (isset($set['amount']['price_discount'])) {
1081
  public function getBiggestDiscount($discount_list, $price)
1082
  {
1083
  $big = 0;
1084
+ // $amount = $price;
1085
+ $amount = 0;
1086
  foreach ($discount_list as $id => $discount_item) {
1087
  $amount_type = (isset($discount_item['amount']['percentage_discount']) ? 'percentage_discount' : 'price_discount');
1088
  if ($amount_type == 'percentage_discount') {
1095
  }
1096
  }
1097
 
1098
+ if ($big < $amount) {
1099
  $big = $amount;
1100
  }
1101
  }
loader.php CHANGED
@@ -26,9 +26,47 @@ if(!function_exists('get_plugin_data')){
26
  */
27
  define('WOO_DISCOUNT_VERSION', get_plugin_data(plugin_dir_path(__FILE__).'woo-discount-rules.php')['Version']);
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  include_once('includes/discount-base.php');
30
- include_once('includes/pricing-rules.php');
31
- include_once('helper/general-helper.php');
32
  include_once('helper/purchase.php');
33
  require_once __DIR__ . '/vendor/autoload.php';
34
 
26
  */
27
  define('WOO_DISCOUNT_VERSION', get_plugin_data(plugin_dir_path(__FILE__).'woo-discount-rules.php')['Version']);
28
 
29
+ /**
30
+ * check WooCommerce version
31
+ */
32
+ if (!function_exists('woo_discount_checkWooCommerceVersion3')) {
33
+ function woo_discount_checkWooCommerceVersion3($version = "3.0")
34
+ {
35
+ // If get_plugins() isn't available, require it
36
+ if ( ! function_exists( 'get_plugins' ) )
37
+ require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
38
+
39
+ // Create the plugins folder and file variables
40
+ $plugin_folder = get_plugins( '/' . 'woocommerce' );
41
+ $plugin_file = 'woocommerce.php';
42
+
43
+ // If the plugin version number is set, return it
44
+ if ( isset( $plugin_folder[$plugin_file]['Version'] ) ) {
45
+ $woocommerce_version = $plugin_folder[$plugin_file]['Version'];
46
+
47
+ } else {
48
+ // Otherwise return null
49
+ $woocommerce_version = null;
50
+ }
51
+
52
+ if( version_compare( $woocommerce_version, $version, ">=" ) ) {
53
+ return true;
54
+ }
55
+ }
56
+ }
57
+
58
+
59
+ $woocommerce_v3 = woo_discount_checkWooCommerceVersion3();
60
+ if($woocommerce_v3){
61
+ include_once('includes/pricing-rules-3.php');
62
+ include_once('helper/general-helper-3.php');
63
+ include_once('includes/cart-rules-3.php');
64
+ } else {
65
+ include_once('includes/pricing-rules.php');
66
+ include_once('helper/general-helper.php');
67
+ include_once('includes/cart-rules.php');
68
+ }
69
  include_once('includes/discount-base.php');
 
 
70
  include_once('helper/purchase.php');
71
  require_once __DIR__ . '/vendor/autoload.php';
72
 
readme.txt CHANGED
@@ -4,7 +4,7 @@ Donate link: https://flycart.org/
4
  Tags: woocommerce, ecommerce, discounts, coupons, promotion, campaigns, sales, price rules, advanced coupons, advanced discounts
5
  Requires at least: 4.4.1
6
  Tested up to: 4.7
7
- Stable tag: 1.4.8
8
  License: GPLv3 or later
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
@@ -116,4 +116,4 @@ More information could be found in the documentation
116
  = 1.4.0 - 26/10/16 =
117
  * PHP 5.3 compatibility added
118
 
119
- == Upgrade notice ==
4
  Tags: woocommerce, ecommerce, discounts, coupons, promotion, campaigns, sales, price rules, advanced coupons, advanced discounts
5
  Requires at least: 4.4.1
6
  Tested up to: 4.7
7
+ Stable tag: 1.4.9
8
  License: GPLv3 or later
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
116
  = 1.4.0 - 26/10/16 =
117
  * PHP 5.3 compatibility added
118
 
119
+ == Upgrade notice ==
woo-discount-rules.php CHANGED
@@ -5,7 +5,7 @@
5
  * Description: Simple Discount Rules for WooCommerce.
6
  * Author: Flycart Technologies LLP
7
  * Author URI: https://www.flycart.org
8
- * Version: 1.4.8
9
  * Slug: woo-discount-rules
10
  * Text Domain: woo-discount-rules
11
  * Requires at least: 4.6.1
5
  * Description: Simple Discount Rules for WooCommerce.
6
  * Author: Flycart Technologies LLP
7
  * Author URI: https://www.flycart.org
8
+ * Version: 1.4.9
9
  * Slug: woo-discount-rules
10
  * Text Domain: woo-discount-rules
11
  * Requires at least: 4.6.1