-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbt-bundle-builder-for-wc.php
More file actions
2700 lines (2293 loc) · 106 KB
/
Copy pathbt-bundle-builder-for-wc.php
File metadata and controls
2700 lines (2293 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Bundle Builder for WooCommerce
* Plugin URI: https://demo.betatech.co/bundle-builder
* Description: Create customizable bundle promotions with tiered discounts based on quantity. Now with advanced analytics, reporting, and coupon tracking.
* Version: 1.0.2
* Requires at least: 6.0
* Requires PHP: 7.4
* Author: Betatech
* Author URI: https://betatech.co
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: bt-bundle-builder-for-wc
* Domain Path: /languages
* WC requires at least: 7.0
* WC tested up to: 9.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'MMB_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'MMB_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'MMB_VERSION', '1.0.2' );
define( 'MMB_DB_VERSION', '2.1' ); // Database version for schema updates
/**
* Get the fully-qualified bundles table name.
*
* @since 2.1
*
* @return string
*/
function mmb_get_table_name() {
global $wpdb;
$raw_name = $wpdb->prefix . 'mmb_bundles';
$sanitized = preg_replace( '/[^A-Za-z0-9_]/', '', $raw_name );
return esc_sql( $sanitized ?: $raw_name );
}
/**
* Apply database schema changes using dbDelta
*
* @since 2.1
*
* @param string $schema_sql The SQL schema to apply
*/
function mmb_dbDelta( $schema_sql ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $schema_sql );
}
/**
* Get the SQL statement used for dbDelta
*
* @since 2.1
*
* @return string
*/
function mmb_get_table_schema_sql() {
global $wpdb;
$table_name = mmb_get_table_name();
return "CREATE TABLE {$table_name} (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
description longtext,
enabled tinyint(1) DEFAULT 1,
use_quantity tinyint(1) DEFAULT 0,
max_quantity int DEFAULT 10,
discount_tiers longtext,
product_ids longtext,
heading_text varchar(255) DEFAULT 'Select Your Products Below',
hint_text varchar(255) DEFAULT 'Bundle 2, 3, 4 or 5 items and watch the savings grow.',
primary_color varchar(7) DEFAULT '#4caf50',
accent_color varchar(7) DEFAULT '#45a049',
hover_bg_color varchar(7) DEFAULT '#388e3c',
hover_accent_color varchar(7) DEFAULT '#2e7d32',
button_text_color varchar(7) DEFAULT '#ffffff',
button_text varchar(255) DEFAULT 'Add Bundle to Cart',
progress_text varchar(255) DEFAULT 'Your Savings Progress',
cart_behavior varchar(20) DEFAULT 'sidecart',
show_bundle_title tinyint(1) DEFAULT 1,
show_bundle_description tinyint(1) DEFAULT 1,
show_heading_text tinyint(1) DEFAULT 1,
show_hint_text tinyint(1) DEFAULT 1,
show_progress_text tinyint(1) DEFAULT 1,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
primary key (id)
)";
}
/**
* Check and upgrade database if needed
* Runs on every admin page load to ensure database is up to date
*
* @since 2.1
*/
function mmb_check_database_upgrade() {
if ( ! is_admin() ) {
return;
}
global $wpdb;
$current_db_version = get_option( 'mmb_db_version', '1.0' );
if ( version_compare( $current_db_version, MMB_DB_VERSION, '<' ) ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$previous_error = $wpdb->last_error;
$schema_sql = mmb_get_table_schema_sql();
dbDelta( $schema_sql );
$had_error = ! empty( $wpdb->last_error ) && $wpdb->last_error !== $previous_error;
update_option( 'mmb_db_version', MMB_DB_VERSION );
if ( current_user_can( 'manage_options' ) ) {
add_action(
'admin_notices',
function () use ( $had_error ) {
?>
<div class="notice notice-<?php echo $had_error ? 'error' : 'success'; ?> <?php echo $had_error ? '' : 'is-dismissible'; ?>">
<p>
<strong><?php echo esc_html__( 'Bundle Builder:', 'bt-bundle-builder-for-wc' ); ?></strong>
<?php
if ( $had_error ) {
echo esc_html__( 'Database update encountered an issue. Please review the debug log for details.', 'bt-bundle-builder-for-wc' );
} else {
echo esc_html__( 'Database schema verified successfully.', 'bt-bundle-builder-for-wc' );
}
?>
</p>
</div>
<?php
}
);
}
}
}
add_action( 'admin_init', 'mmb_check_database_upgrade' );
/**
* Helper function for debug logging
* Logs to WooCommerce logger if logging is enabled in settings
*
* @param string $message Log message
* @param string $level Log level (debug, info, notice, warning, error, critical, alert, emergency)
*/
function mmb_debug_log( $message, $level = 'info' ) {
// Check if logging is enabled in settings
$logging_enabled = get_option( 'mmb_enable_logging', 'no' );
if ( $logging_enabled !== 'yes' ) {
return;
}
// Use WooCommerce logger if available
if ( function_exists( 'wc_get_logger' ) ) {
$logger = wc_get_logger();
$logger->log( $level, $message, array( 'source' => 'bt-bundle-builder-for-wc' ) );
}
}
/**
* Check if WooCommerce is active
*
* @since 1.0.0
* @return bool
*/
function mmb_is_woocommerce_active() {
return class_exists( 'WooCommerce' );
}
/**
* Admin notice if WooCommerce is not active
*
* @since 1.0.0
*/
function mmb_woocommerce_missing_notice() {
?>
<div class="notice notice-error">
<p>
<strong><?php echo esc_html__( 'Bundle Builder for WooCommerce', 'bt-bundle-builder-for-wc' ); ?></strong>
<?php echo esc_html__( 'requires WooCommerce to be installed and active.', 'bt-bundle-builder-for-wc' ); ?>
<a href="<?php echo esc_url( admin_url( 'plugin-install.php?s=woocommerce&tab=search&type=term' ) ); ?>">
<?php echo esc_html__( 'Install WooCommerce', 'bt-bundle-builder-for-wc' ); ?>
</a>
</p>
</div>
<?php
}
/**
* Deactivate plugin if WooCommerce is not active
*
* @since 1.0.0
*/
function mmb_check_woocommerce_dependency() {
if ( ! mmb_is_woocommerce_active() ) {
// Deactivate the plugin
deactivate_plugins( plugin_basename( __FILE__ ) );
// Show admin notice
add_action( 'admin_notices', 'mmb_woocommerce_missing_notice' );
// Prevent plugin from loading
return false;
}
return true;
}
// Main plugin class
class BT_Bundle_Builder {
private static $instance = null;
private $frontend_assets_forced = false;
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public function __construct() {
$this->includes();
$this->hooks();
// Run database upgrade check only once per version
$db_version = get_option( 'mmb_db_version', '1.0' );
if ( version_compare( $db_version, MMB_DB_VERSION, '<' ) ) {
$this->maybe_upgrade_database();
update_option( 'mmb_db_version', MMB_DB_VERSION );
}
}
private function includes() {
require_once MMB_PLUGIN_DIR . 'includes/class-settings.php';
require_once MMB_PLUGIN_DIR . 'includes/class-bundle-manager.php';
require_once MMB_PLUGIN_DIR . 'includes/class-frontend.php';
require_once MMB_PLUGIN_DIR . 'includes/class-cart.php';
require_once MMB_PLUGIN_DIR . 'includes/class-shortcode.php';
}
private function hooks() {
// Admin hooks
add_action( 'admin_menu', [ $this, 'register_admin_menu' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_scripts' ] );
add_action( 'admin_head', [ $this, 'add_menu_icon_styles' ] ); // Inline styles for menu icon
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), [ $this, 'add_action_links' ] );
// Frontend hooks
add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_frontend_scripts' ] );
// Database setup
register_activation_hook( __FILE__, [ $this, 'activate_plugin' ] );
// HPOS Compatibility
add_action( 'before_woocommerce_init', [ $this, 'declare_hpos_compatibility' ] );
}
/**
* Declare compatibility with WooCommerce HPOS (High-Performance Order Storage)
*
* @since 1.0.0
*/
public function declare_hpos_compatibility() {
if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
'custom_order_tables',
__FILE__,
true
);
}
}
/**
* Add settings link on plugin page
*/
public function add_action_links( $links ) {
$settings_link = '<a href="' . admin_url( 'admin.php?page=bt-bundle-builder' ) . '">' . __( 'Settings', 'bt-bundle-builder-for-wc' ) . '</a>';
array_unshift( $links, $settings_link );
return $links;
}
public function register_admin_menu() {
add_menu_page(
__( 'Bundle Builder', 'bt-bundle-builder-for-wc' ),
__( 'Bundle Builder', 'bt-bundle-builder-for-wc' ),
'manage_options',
'bt-bundle-builder',
[ $this, 'admin_page' ],
MMB_PLUGIN_URL . 'assets/img/mix-match-icon.svg',
30
);
// Add analytics submenu page
add_submenu_page(
'bt-bundle-builder',
__( 'Bundle Analytics', 'bt-bundle-builder-for-wc' ),
__( 'Analytics', 'bt-bundle-builder-for-wc' ),
'manage_options',
'mmb-analytics',
[ $this, 'analytics_page' ]
);
// Add diagnostics submenu page
add_submenu_page(
'bt-bundle-builder',
__( 'Diagnostics', 'bt-bundle-builder-for-wc' ),
__( 'Diagnostics', 'bt-bundle-builder-for-wc' ),
'manage_options',
'mmb-diagnostics',
[ $this, 'diagnostics_page' ]
);
// Add settings submenu page
add_submenu_page(
'bt-bundle-builder',
__( 'Settings', 'bt-bundle-builder-for-wc' ),
__( 'Settings', 'bt-bundle-builder-for-wc' ),
'manage_options',
'mmb-settings',
[ $this, 'settings_page' ]
);
}
/**
* Add inline styles for menu icon on all admin pages
*/
public function add_menu_icon_styles() {
?>
<style type="text/css">
#adminmenu #toplevel_page_bt-bundle-builder .wp-menu-image img {
width: 20px !important;
height: 20px !important;
padding: 6px 0 !important;
opacity: 0.6;
}
#adminmenu #toplevel_page_bt-bundle-builder:hover .wp-menu-image img,
#adminmenu #toplevel_page_bt-bundle-builder.wp-has-current-submenu .wp-menu-image img,
#adminmenu #toplevel_page_bt-bundle-builder.current .wp-menu-image img {
opacity: 1;
}
</style>
<?php
}
public function admin_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
include MMB_PLUGIN_DIR . 'admin/bundle-editor.php';
}
public function enqueue_admin_scripts( $hook ) {
// Always ensure dashicons are loaded on all admin pages
wp_enqueue_style( 'dashicons' );
// Only load plugin-specific assets on our plugin pages
if ( strpos( $hook, 'bt-bundle-builder' ) === false && strpos( $hook, 'mmb-' ) === false ) {
return;
}
// Load main admin styles only on Bundle Builder pages
// Using filemtime for cache busting during development
$css_version = MMB_VERSION;
$js_version = MMB_VERSION;
if ( file_exists( MMB_PLUGIN_DIR . 'assets/css/admin.css' ) ) {
$css_version .= '-' . filemtime( MMB_PLUGIN_DIR . 'assets/css/admin.css' );
}
if ( file_exists( MMB_PLUGIN_DIR . 'assets/js/admin.js' ) ) {
$js_version .= '-' . filemtime( MMB_PLUGIN_DIR . 'assets/js/admin.js' );
}
wp_enqueue_style( 'mix-match-admin', MMB_PLUGIN_URL . 'assets/css/admin.css', array( 'dashicons' ), $css_version );
wp_enqueue_script( 'mix-match-admin', MMB_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery', 'wp-api' ), $js_version, true );
wp_localize_script( 'mix-match-admin', 'mmb_admin', array(
'nonce' => wp_create_nonce( 'mmb_admin_nonce' ),
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
// Analytics-specific assets (only on analytics page)
// Check for both possible hook formats: 'mmb-analytics' or 'bt-bundle-builder_page_mmb-analytics'
// WordPress uses format: {parent_slug}_page_{submenu_slug}
$is_analytics_page = ( strpos( $hook, 'mmb-analytics' ) !== false ) ||
( $hook === 'bt-bundle-builder_page_mmb-analytics' ) ||
( strpos( $hook, 'bt-bundle-builder_page_mmb-analytics' ) !== false );
if ( $is_analytics_page ) {
// Debug: Log hook for troubleshooting
mmb_debug_log( 'MMB Analytics: Hook detected: ' . $hook, 'debug' );
$analytics_css_version = MMB_VERSION;
$analytics_js_version = MMB_VERSION;
if ( file_exists( MMB_PLUGIN_DIR . 'assets/css/analytics-dashboard.css' ) ) {
$analytics_css_version .= '-' . filemtime( MMB_PLUGIN_DIR . 'assets/css/analytics-dashboard.css' );
}
if ( file_exists( MMB_PLUGIN_DIR . 'assets/js/analytics-dashboard.js' ) ) {
$analytics_js_version .= '-' . filemtime( MMB_PLUGIN_DIR . 'assets/js/analytics-dashboard.js' );
}
wp_enqueue_style( 'mmb-analytics-dashboard', MMB_PLUGIN_URL . 'assets/css/analytics-dashboard.css', array( 'dashicons' ), $analytics_css_version );
$chart_js_version = '4.4.0';
$chart_js_path = MMB_PLUGIN_DIR . 'assets/js/vendor/chart.umd.min.js';
// Check if Chart.js file exists
if ( ! file_exists( $chart_js_path ) ) {
// Log error if file doesn't exist
mmb_debug_log( 'MMB: Chart.js file not found at: ' . $chart_js_path, 'error' );
} else {
$chart_js_version .= '-' . filemtime( $chart_js_path );
}
// Enqueue Chart.js - load in footer but ensure it's available
wp_enqueue_script( 'mmb-chart-js', MMB_PLUGIN_URL . 'assets/js/vendor/chart.umd.min.js', array(), $chart_js_version, false ); // Load in header to ensure it's available
// Add inline script to verify Chart.js loaded
wp_add_inline_script( 'mmb-chart-js', 'console.log("MMB: Chart.js script enqueued");', 'after' );
// Enqueue analytics dashboard script with Chart.js as dependency
wp_enqueue_script( 'mmb-analytics-dashboard', MMB_PLUGIN_URL . 'assets/js/analytics-dashboard.js', array( 'jquery', 'mmb-chart-js' ), $analytics_js_version, true );
}
}
public function enqueue_frontend_scripts() {
if ( ! $this->should_enqueue_frontend_assets() ) {
return;
}
$css_path = MMB_PLUGIN_DIR . 'assets/css/frontend.css';
$js_path = MMB_PLUGIN_DIR . 'assets/js/frontend.js';
$css_version = MMB_VERSION;
$js_version = MMB_VERSION;
if ( file_exists( $css_path ) ) {
$css_version .= '-' . filemtime( $css_path );
}
if ( file_exists( $js_path ) ) {
$js_version .= '-' . filemtime( $js_path );
}
wp_enqueue_style( 'mix-match-frontend', MMB_PLUGIN_URL . 'assets/css/frontend.css', [], $css_version );
wp_enqueue_script( 'mix-match-frontend', MMB_PLUGIN_URL . 'assets/js/frontend.js', [], $js_version, true );
// Get bundle discount info for JavaScript
$bundle_discount_data = [];
if ( WC()->session ) {
$session_data = WC()->session->get( 'mmb_bundle_discount' );
if ( $session_data && ! empty( $session_data['product_ids'] ) ) {
$bundle_discount_data = $session_data;
}
}
wp_localize_script( 'mix-match-frontend', 'mmb_frontend', [
'nonce' => wp_create_nonce( 'mmb_frontend_nonce' ),
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'cart_url' => wc_get_cart_url(),
'bundle_discount' => $bundle_discount_data,
'discount_label' => __( 'Bundle Discount', 'bt-bundle-builder-for-wc' ),
]);
}
/**
* Allow developers to explicitly request frontend assets.
* Useful when the shortcode is rendered outside standard content areas.
*/
public function force_frontend_assets() {
$this->frontend_assets_forced = true;
}
/**
* Determine whether frontend assets should be loaded on the current request.
*/
private function should_enqueue_frontend_assets() {
if ( is_admin() ) {
return false;
}
$should_load = false;
if ( $this->frontend_assets_forced ) {
$should_load = true;
} elseif ( $this->current_view_has_shortcode() ) {
$should_load = true;
}
/**
* Filter whether Mix & Match should enqueue frontend assets.
*
* @param bool $should_load Whether assets should be loaded.
*/
return apply_filters( 'mmb_should_enqueue_frontend_assets', $should_load );
}
/**
* Check if the current page content contains the Mix & Match shortcode.
*/
private function current_view_has_shortcode() {
if ( is_singular() ) {
global $post;
if ( $this->post_contains_bundle_shortcode( $post ) ) {
return true;
}
}
if ( is_home() || is_front_page() || is_archive() ) {
global $posts;
if ( ! empty( $posts ) ) {
foreach ( $posts as $post ) {
if ( $this->post_contains_bundle_shortcode( $post ) ) {
return true;
}
}
}
}
return false;
}
/**
* Helper to check if a post has the [mmb_bundle] shortcode.
*
* @param WP_Post|null $post
*/
private function post_contains_bundle_shortcode( $post ) {
return ( $post instanceof WP_Post ) && has_shortcode( $post->post_content, 'mmb_bundle' );
}
private function maybe_upgrade_database() {
try {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( mmb_get_table_schema_sql() );
// Log success for debugging
mmb_debug_log( 'MMB: Database upgrade successful' );
} catch ( Exception $e ) {
// Log error for debugging
mmb_debug_log( 'MMB Database upgrade error: ' . $e->getMessage(), 'error' );
// Store error for admin notice
update_option( 'mmb_db_upgrade_error', $e->getMessage() );
}
}
public function activate_plugin() {
try {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( mmb_get_table_schema_sql() );
// Run upgrade check
$this->maybe_upgrade_database();
// Set initial database version
update_option( 'mmb_db_version', MMB_DB_VERSION );
flush_rewrite_rules();
// Log success for debugging
mmb_debug_log( 'MMB: Plugin activation successful' );
} catch ( Exception $e ) {
// Log error for debugging
mmb_debug_log( 'MMB Plugin activation error: ' . $e->getMessage(), 'error' );
// Store error for admin notice
update_option( 'mmb_activation_error', $e->getMessage() );
// Re-throw to let WordPress handle the error
throw $e;
}
}
public function analytics_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
// Handle form submissions for date filtering
$post_nonce = isset( $_POST['mmb_analytics_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['mmb_analytics_nonce'] ) ) : '';
if ( $post_nonce && wp_verify_nonce( $post_nonce, 'mmb_analytics_action' ) ) {
$this->handle_analytics_form_submission();
}
$date_range = '30days';
$start_date = '';
$end_date = '';
// Prefer GET parameters with nonce verification
$get_nonce = isset( $_GET['mmb_analytics_nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['mmb_analytics_nonce'] ) ) : '';
if ( $get_nonce && wp_verify_nonce( $get_nonce, 'mmb_analytics_filter' ) ) {
$date_range = isset( $_GET['date_range'] ) ? sanitize_text_field( wp_unslash( $_GET['date_range'] ) ) : $date_range;
$start_date = isset( $_GET['start_date'] ) ? sanitize_text_field( wp_unslash( $_GET['start_date'] ) ) : '';
$end_date = isset( $_GET['end_date'] ) ? sanitize_text_field( wp_unslash( $_GET['end_date'] ) ) : '';
} else {
// Fallback to POST (legacy) if nonce missing
$date_range = isset( $_POST['date_range'] ) ? sanitize_text_field( wp_unslash( $_POST['date_range'] ) ) : $date_range;
$start_date = isset( $_POST['start_date'] ) ? sanitize_text_field( wp_unslash( $_POST['start_date'] ) ) : $start_date;
$end_date = isset( $_POST['end_date'] ) ? sanitize_text_field( wp_unslash( $_POST['end_date'] ) ) : $end_date;
}
// Get analytics data using global function
$analytics_data = mmb_get_analytics_data( $date_range, $start_date, $end_date );
include MMB_PLUGIN_DIR . 'admin/analytics-dashboard.php';
}
public function diagnostics_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
include MMB_PLUGIN_DIR . 'admin/diagnostics.php';
}
public function settings_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
// Handle settings form submission
$settings_nonce = isset( $_POST['mmb_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['mmb_settings_nonce'] ) ) : '';
if ( $settings_nonce && wp_verify_nonce( $settings_nonce, 'mmb_settings_action' ) ) {
$enable_logging = isset( $_POST['mmb_enable_logging'] ) ? 'yes' : 'no';
update_option( 'mmb_enable_logging', $enable_logging );
echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved successfully!', 'bt-bundle-builder-for-wc' ) . '</p></div>';
}
include MMB_PLUGIN_DIR . 'admin/settings.php';
}
/**
* Handle analytics form submission
*/
private function handle_analytics_form_submission() {
// Form data will be processed in get_analytics_data method
// Redirect to prevent form resubmission
wp_safe_redirect( add_query_arg( 'settings-updated', 'true', menu_page_url( 'mmb-analytics' ) ) );
exit;
}
}
// Plugin initialization moved to mmb_init_plugin() function
// which runs on 'plugins_loaded' hook to ensure WooCommerce is available
// AJAX Handlers
add_action( 'wp_ajax_mmb_save_bundle', 'mmb_save_bundle' );
add_action( 'wp_ajax_mmb_get_bundles', 'mmb_get_bundles' );
add_action( 'wp_ajax_mmb_delete_bundle', 'mmb_delete_bundle' );
add_action( 'wp_ajax_mmb_search_products', 'mmb_search_products' );
add_action( 'wp_ajax_mmb_get_products_by_ids', 'mmb_get_products_by_ids' );
add_action( 'wp_ajax_nopriv_mmb_update_bundle_items', 'mmb_update_bundle_items' );
add_action( 'wp_ajax_mmb_update_bundle_items', 'mmb_update_bundle_items' );
add_action( 'wp_ajax_nopriv_mmb_add_bundle_to_cart', 'mmb_add_bundle_to_cart' );
add_action( 'wp_ajax_mmb_add_bundle_to_cart', 'mmb_add_bundle_to_cart' );
add_action( 'wp_ajax_woocommerce_ajax_add_to_cart', 'mmb_wc_ajax_add_to_cart' );
add_action( 'wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'mmb_wc_ajax_add_to_cart' );
add_action( 'wp_ajax_mmb_wc_ajax_add_to_cart', 'mmb_wc_ajax_add_to_cart' );
add_action( 'wp_ajax_nopriv_mmb_wc_ajax_add_to_cart', 'mmb_wc_ajax_add_to_cart' );
// AJAX handler for debug function
add_action( 'wp_ajax_mmb_debug_coupon_state', 'mmb_debug_coupon_state' );
function mmb_save_bundle() {
check_ajax_referer( 'mmb_admin_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( __( 'Unauthorized', 'bt-bundle-builder-for-wc' ) );
}
// Debug: Log what PHP receives
$bundle_manager = new MMB_Bundle_Manager();
$result = $bundle_manager->save_bundle( wp_unslash( $_POST ) );
if ( $result ) {
wp_send_json_success( $result );
} else {
// Return detailed error message
global $wpdb;
$error_message = $wpdb->last_error ? $wpdb->last_error : __( 'Failed to save bundle', 'bt-bundle-builder-for-wc' );
wp_send_json_error( $error_message );
}
}
function mmb_get_bundles() {
check_ajax_referer( 'mmb_admin_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( __( 'Unauthorized', 'bt-bundle-builder-for-wc' ) );
}
$bundle_manager = new MMB_Bundle_Manager();
$bundles = $bundle_manager->get_all_bundles();
// Debug: Log what we're sending
foreach ( $bundles as $bundle ) {
}
wp_send_json_success( $bundles );
}
function mmb_delete_bundle() {
check_ajax_referer( 'mmb_admin_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( __( 'Unauthorized', 'bt-bundle-builder-for-wc' ) );
}
$bundle_id = isset( $_POST['bundle_id'] ) ? intval( wp_unslash( $_POST['bundle_id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( ! $bundle_id ) {
wp_send_json_error( __( 'Invalid bundle ID', 'bt-bundle-builder-for-wc' ) );
}
$bundle_manager = new MMB_Bundle_Manager();
if ( $bundle_manager->delete_bundle( $bundle_id ) ) {
wp_send_json_success( __( 'Bundle deleted', 'bt-bundle-builder-for-wc' ) );
} else {
wp_send_json_error( __( 'Failed to delete bundle', 'bt-bundle-builder-for-wc' ) );
}
}
function mmb_update_bundle_items() {
// Ensure WooCommerce is available
if ( ! function_exists( 'WC' ) ) {
wp_send_json_error( __( 'WooCommerce not available', 'bt-bundle-builder-for-wc' ) );
return;
}
// Ensure session is available for all users (including logged-out)
// This must happen BEFORE nonce verification for logged-out users
if ( ! WC()->session ) {
if ( ! class_exists( 'WC_Session_Handler' ) ) {
include_once WC_ABSPATH . 'includes/class-wc-session-handler.php';
}
WC()->session = new WC_Session_Handler();
// Initialize session with customer ID
$customer_id = WC()->session->get_customer_id();
if ( ! $customer_id ) {
if ( is_user_logged_in() ) {
$customer_id = get_current_user_id();
} else {
// Generate guest ID
$customer_id = 'mmb_guest_' . wp_generate_uuid4();
}
WC()->session->set_customer_id( $customer_id );
}
WC()->session->init();
// Set session cookie for guest users
if ( ! headers_sent() && ! is_user_logged_in() ) {
WC()->session->set_customer_session_cookie( true );
}
}
// Verify nonce for security (after session is initialized)
check_ajax_referer( 'mmb_frontend_nonce', 'nonce' );
// Debug logging
$bundle_id = isset( $_POST['bundle_id'] ) ? intval( wp_unslash( $_POST['bundle_id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Missing
$product_ids_raw = isset( $_POST['product_ids'] ) ? sanitize_textarea_field( wp_unslash( $_POST['product_ids'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
// Parse product_ids if it's JSON
if ( is_string( $product_ids_raw ) ) {
// Remove escaping that URLSearchParams adds
$product_ids_clean = wp_unslash( $product_ids_raw );
$product_ids = json_decode( $product_ids_clean, true );
} else {
$product_ids = (array) $product_ids_raw;
}
if ( json_last_error() !== JSON_ERROR_NONE ) {
}
if ( ! $bundle_id || empty( $product_ids ) ) {
wp_send_json_error( __( 'Invalid data', 'bt-bundle-builder-for-wc' ) );
}
$bundle_manager = new MMB_Bundle_Manager();
$bundle = $bundle_manager->get_bundle( $bundle_id );
if ( ! $bundle ) {
wp_send_json_error( __( 'Bundle not found', 'bt-bundle-builder-for-wc' ) );
}
// Count total items (including quantities) for tier calculation
$item_count = count( $product_ids );
// Calculate discount based on total item count
$tier = $bundle_manager->get_applicable_tier( $bundle, $item_count );
// Calculate prices - group products by ID and count quantities
$products_map = [];
$total_price = 0;
foreach ( $product_ids as $item ) {
// Handle both old format (just IDs) and new format (objects with product_id and variation_id)
if ( is_array( $item ) || is_object( $item ) ) {
$item = (array) $item;
$product_id = isset( $item['product_id'] ) ? intval( $item['product_id'] ) : 0;
$variation_id = isset( $item['variation_id'] ) ? intval( $item['variation_id'] ) : 0;
} else {
$product_id = intval( $item );
$variation_id = 0;
}
// Create unique key for product/variation combination
$key = $product_id . '_' . $variation_id;
// Get the actual product (variation or simple)
$actual_product_id = $variation_id ? $variation_id : $product_id;
$product = wc_get_product( $actual_product_id );
if ( $product ) {
$price = (float) $product->get_price();
$total_price += $price; // Add price for each item (quantity is represented by multiple entries)
// Group products by key and accumulate quantity
if ( ! isset( $products_map[ $key ] ) ) {
$products_map[ $key ] = [
'id' => $product_id,
'product_id' => $product_id,
'variation_id' => $variation_id,
'name' => $product->get_name(),
'price' => $price,
'quantity' => 0,
];
}
$products_map[ $key ]['quantity']++;
}
}
// Convert map to array for response
$products_data = array_values( $products_map );
$discount_amount = ( $total_price * $tier['discount'] ) / 100;
$final_price = $total_price - $discount_amount;
$response_data = [
'products' => $products_data,
'subtotal' => $total_price,
'total_price' => $final_price,
'discount_percentage' => $tier['discount'],
'discount_amount' => $discount_amount,
'item_count' => $item_count,
];
// Debug logging
wp_send_json_success( $response_data );
}
function mmb_search_products() {
check_ajax_referer( 'mmb_admin_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( __( 'Unauthorized', 'bt-bundle-builder-for-wc' ) );
}
$search = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
$args = [
'post_type' => 'product',
'posts_per_page' => 100,
'orderby' => 'title',
'order' => 'ASC',
];
if ( ! empty( $search ) ) {
$args['s'] = $search;
}
$products = get_posts( $args );
$formatted = [];
foreach ( $products as $product_post ) {
$product = wc_get_product( $product_post->ID );
if ( $product ) {
$formatted[] = [
'id' => $product->get_id(),
'name' => $product->get_name(),
'price' => wc_price( $product->get_price() ),
];
}
}
wp_send_json_success( $formatted );
}
/**
* Ajax handler to fetch specific products by ID.
*
* This is used by the admin UI to ensure previously selected products are
* always available in the local cache, even if they do not match the current
* search query.
*
* @since 1.0.0
* @return void
*/
function mmb_get_products_by_ids() {
check_ajax_referer( 'mmb_admin_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( __( 'Unauthorized', 'bt-bundle-builder-for-wc' ) );
}
$product_ids = [];
$raw_ids_array = filter_input( INPUT_POST, 'product_ids', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( null !== $raw_ids_array && false !== $raw_ids_array ) {
$raw_ids_array = wp_unslash( $raw_ids_array );
$raw_ids_array = array_map( 'sanitize_text_field', $raw_ids_array );
$product_ids = array_map( 'absint', $raw_ids_array );
} else {
$raw_ids_string = filter_input( INPUT_POST, 'product_ids', FILTER_UNSAFE_RAW ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( null !== $raw_ids_string && '' !== $raw_ids_string ) {
$raw_ids_string = sanitize_textarea_field( wp_unslash( $raw_ids_string ) );
$decoded = json_decode( $raw_ids_string, true );
if ( is_array( $decoded ) ) {
$product_ids = array_map( 'absint', $decoded );
} else {
$parts = array_filter( array_map( 'trim', explode( ',', $raw_ids_string ) ) );
$product_ids = array_map( 'absint', $parts );
}
}
}
$product_ids = array_values( array_unique( array_filter( $product_ids ) ) );
if ( empty( $product_ids ) ) {
wp_send_json_success( [] );
}
$args = [
'post_type' => [ 'product', 'product_variation' ],
'post__in' => $product_ids,
'posts_per_page' => count( $product_ids ),
'orderby' => 'post__in',
];
$products = get_posts( $args );
$formatted = [];
foreach ( $products as $product_post ) {
$product = wc_get_product( $product_post->ID );
if ( ! $product ) {
continue;
}
$formatted[] = [
'id' => $product->get_id(),
'name' => $product->get_name(),
'price' => wc_price( $product->get_price() ),
];
}
wp_send_json_success( $formatted );
}
function mmb_add_bundle_to_cart() {
// Ensure WooCommerce is available
if ( ! function_exists( 'WC' ) ) {
wp_send_json_error( __( 'WooCommerce not available', 'bt-bundle-builder-for-wc' ) );
return;
}
// Ensure session is available for all users (including logged-out)
// This must happen BEFORE nonce verification for logged-out users
if ( ! WC()->session ) {
if ( ! class_exists( 'WC_Session_Handler' ) ) {
include_once WC_ABSPATH . 'includes/class-wc-session-handler.php';
}
WC()->session = new WC_Session_Handler();
// Initialize session with customer ID
$customer_id = WC()->session->get_customer_id();
if ( ! $customer_id ) {
if ( is_user_logged_in() ) {
$customer_id = get_current_user_id();
} else {
// Generate guest ID
$customer_id = 'mmb_guest_' . wp_generate_uuid4();
}
WC()->session->set_customer_id( $customer_id );