<?php

/**
 * Plugin Name: BundlePress – Advanced Grouped Product Bundle Builder
 * Plugin URI: https://dominopress.com/plugin/bundlepress
 * Description: Professional WooCommerce bundle builder. Create and manage custom WooCommerce bundle products with flexible pricing and display options.
 * Version: 1.3.7
 * Author: Dominopress
 * Author URI: https://dominopress.com
 * Text Domain: bundlepress
 * Domain Path: /languages
 * Requires at least: 6.8
 * Tested up to: 7.0
 * Requires PHP: 7.4
 * WC requires at least: 8.0
 * WC tested up to: 10.8
 * License: GPLv2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 */

defined('ABSPATH') || exit;

// Declare HPOS compatibility
add_action('before_woocommerce_init', function () {
    if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
    }
});

// Define constants
define('BUNDLEPRESS_VERSION', '1.3.7');
define('BUNDLEPRESS_PATH', plugin_dir_path(__FILE__));
define('BUNDLEPRESS_URL', plugin_dir_url(__FILE__));

// Include requirement files
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-db.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-remote-api.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-settings-api.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-api.php';
require_once BUNDLEPRESS_PATH . 'includes/Customization/class-bundlepress-customization-api.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-event-tracker.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-deactivation-survey.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-bundle-api.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-bundle-display.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-bundle-product.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-bundle-upsell.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-analytics-handler.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-insights.php';
require_once BUNDLEPRESS_PATH . 'includes/class-bundlepress-other-plugins.php';

// Bundle type handlers
require_once BUNDLEPRESS_PATH . 'includes/Handlers/class-bundlepress-volume-handler.php';
require_once BUNDLEPRESS_PATH . 'includes/Handlers/class-bundlepress-mixmatch-handler.php';
require_once BUNDLEPRESS_PATH . 'includes/Handlers/class-bundlepress-fbt-handler.php';
require_once BUNDLEPRESS_PATH . 'includes/Handlers/class-bundlepress-bxgy-handler.php';
require_once BUNDLEPRESS_PATH . 'includes/Handlers/class-bundlepress-fixed-handler.php';

class BundlePress_Plugin
{
    public function __construct()
    {
        // Text domain
        add_action('plugins_loaded', [$this, 'load_textdomain']);

        // Activation hooks
        register_activation_hook(__FILE__, ['BundlePress_DB', 'init']);
        register_activation_hook(__FILE__, [$this, 'plugin_activation_redirect']);
        register_activation_hook(__FILE__, ['BundlePress_Event_Tracker', 'track_install']);

        // Deactivation hook
        register_deactivation_hook(__FILE__, ['BundlePress_Insights', 'on_deactivation']);
        register_deactivation_hook(__FILE__, ['BundlePress_Event_Tracker', 'track_deactivation']);

        // Initialize event tracker and deactivation survey
        BundlePress_Event_Tracker::init();
        BundlePress_Deactivation_Survey::init();

        // Also check tables on admin init
        add_action('admin_init', [$this, 'check_tables']);
        add_action('admin_init', [$this, 'handle_activation_redirect']);

        // Initialize core API (always needed)
        new BundlePress_API();
        new BundlePress_Settings_API('bundlepress/v1');
        new BundlePress_Customization_API('bundlepress/v1');

        // Initialize Bundle Builder features
        new BundlePress_Bundle_API('bundlepress/v1');
        new BundlePress_Analytics_Handler('bundlepress/v1');
        new BundlePress_Bundle_Display();
        new BundlePress_Bundle_Product();
        new BundlePress_Bundle_Upsell();

        // Initialize Insights
        BundlePress_Insights::get_instance();
        BundlePress_Other_Plugins::init();

        add_action('init', [$this, 'register_post_types']);
        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);

        // Frontend Scripts - for bundles
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_scripts']);
        add_action('wp_head', [$this, 'inject_frontend_styles']);

        // Plugin action links
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'add_plugin_action_links']);
    }

    public function load_textdomain()
    {
        load_plugin_textdomain('bundlepress', false, dirname(plugin_basename(__FILE__)) . '/languages');
    }

    public function add_plugin_action_links($links)
    {
        $create_bundle_link = '<a href="' . esc_url(admin_url('admin.php?page=bundlepress')) . '">' . __('Create Bundle', 'bundlepress') . '</a>';
        array_unshift($links, $create_bundle_link);
        return $links;
    }

    public function register_post_types()
    {
        register_post_type('bundlepress_bundle', [
            'labels' => [
                'name' => __('Bundles', 'bundlepress'),
                'singular_name' => __('Bundle', 'bundlepress'),
            ],
            'public' => false,
            'show_ui' => false,
            'capability_type' => 'post',
            'hierarchical' => false,
            'supports' => ['title', 'editor', 'thumbnail'],
            'rewrite' => false,
            'query_var' => true,
        ]);
    }

    public function check_tables()
    {
        global $wpdb;
        $bundles_table = $wpdb->prefix . 'bundlepress_bundles';
        $analytics_table = $wpdb->prefix . 'bundlepress_analytics';
        $customizations_table = $wpdb->prefix . 'bundlepress_customizations';

        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $bundles_exists = $wpdb->get_var("SHOW TABLES LIKE '$bundles_table'");
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $analytics_exists = $wpdb->get_var("SHOW TABLES LIKE '$analytics_table'");
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $customizations_exists = $wpdb->get_var("SHOW TABLES LIKE '$customizations_table'");

        if (!$bundles_exists || !$analytics_exists || !$customizations_exists) {
            BundlePress_DB::init();
        } else {
            BundlePress_DB::maybe_update_db();
        }
    }

    public function plugin_activation_redirect()
    {
        // Set a transient to trigger redirect after activation
        set_transient('bundlepress_activation_redirect', true, 30);
        update_option('bundlepress_just_activated', 'yes');

        // Set first activation time if not set
        if (!get_option('bundlepress_first_activated')) {
            update_option('bundlepress_first_activated', time());
        }
    }

    public function handle_activation_redirect()
    {
        // Check if we should redirect
        if (get_transient('bundlepress_activation_redirect')) {
            delete_transient('bundlepress_activation_redirect');

            // Only redirect if not doing bulk activation
            if (!isset($_GET['activate-multi'])) {
                wp_safe_redirect(admin_url('admin.php?page=bundlepress'));
                exit;
            }
        }
    }

    public function register_menu()
    {
        // Main Menu
        add_menu_page(
            __('BundlePress', 'bundlepress'),
            __('BundlePress', 'bundlepress'),
            'manage_options',
            'bundlepress',
            [$this, 'render_admin_page'],
            'dashicons-cart',
            6
        );

        // Alias for the main menu page
        add_submenu_page(
            'bundlepress',
            __('All Bundles', 'bundlepress'),
            __('All Bundles', 'bundlepress'),
            'manage_options',
            'bundlepress',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'bundlepress',
            __('Create New Bundle', 'bundlepress'),
            __('Create New Bundle', 'bundlepress'),
            'manage_options',
            'bundlepress-new-bundle',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'bundlepress',
            __('Analytics', 'bundlepress'),
            __('Analytics', 'bundlepress'),
            'manage_options',
            'bundlepress-analytics',
            [$this, 'render_admin_page']
        );

        add_submenu_page(
            'bundlepress',
            __('Customization', 'bundlepress'),
            __('Customization', 'bundlepress'),
            'manage_options',
            'bundlepress-customization',
            [$this, 'render_admin_page']
        );
    }

    public function enqueue_scripts($hook)
    {
        $allowed_hooks = [
            'toplevel_page_bundlepress',
            'bundle-builder_page_bundlepress-settings',
            'bundlepress_page_bundlepress-settings',
            'bundlepress_page_bundlepress-analytics',
            'bundlepress_page_bundlepress-bundle-builder',
            'bundlepress_page_bundlepress-new-bundle',
            'bundlepress_page_bundlepress-customization'
        ];

        if (!in_array($hook, $allowed_hooks)) {
            return;
        }

        $script_path = BUNDLEPRESS_PATH . 'assets/admin.js';
        $script_url = BUNDLEPRESS_URL . 'assets/admin.js';
        $vendors_path = BUNDLEPRESS_PATH . 'assets/vendors.js';
        $vendors_url = BUNDLEPRESS_URL . 'assets/vendors.js';

        $dependencies = ['wp-element'];

        if (file_exists($vendors_path)) {
            wp_enqueue_script(
                'bundlepress-vendors',
                $vendors_url,
                [],
                filemtime($vendors_path),
                true
            );
            $dependencies[] = 'bundlepress-vendors';
        }

        if (file_exists($script_path)) {
            wp_enqueue_script(
                'bundlepress-admin',
                $script_url,
                $dependencies,
                filemtime($script_path),
                true
            );

            // Determine current page to pass to React
            $currentPage = 'bundle-builder';

            if ($hook === 'bundlepress_page_bundlepress-settings') {
                $currentPage = 'settings';
            } elseif ($hook === 'bundlepress_page_bundlepress-customization') {
                $currentPage = 'customization';
            } elseif ($hook === 'bundlepress_page_bundlepress-analytics') {
                $currentPage = 'analytics';
            } elseif ($hook === 'bundlepress_page_bundlepress-new-bundle') {
                $currentPage = 'new-bundle';
            } elseif ($hook === 'bundlepress_page_bundlepress-bundle-builder' || $hook === 'toplevel_page_bundlepress') {
                $currentPage = 'bundle-builder';
                wp_enqueue_media();
                wp_enqueue_editor();
            }

            wp_localize_script('bundlepress-admin', 'bundlePressData', [
                'rootUrl' => home_url(),
                'apiUrl' => rest_url('bundlepress/v1/'),
                'pluginUrl' => BUNDLEPRESS_URL,
                'nonce' => wp_create_nonce('wp_rest'),
                'currentPage' => $currentPage,
                'currencySymbol' => get_woocommerce_currency_symbol(),
                'decimalSeparator' => wc_get_price_decimal_separator(),
                'thousandSeparator' => wc_get_price_thousand_separator(),
                'priceDecimals' => wc_get_price_decimals(),
                'priceFormat' => get_woocommerce_price_format(),
                'settings' => BundlePress_Settings_API::get_feature_settings(),
                'isPro' => function_exists('bundlepress_pro_fs') && bundlepress_pro_fs()->can_use_premium_code(),
            ]);

            // Hide standard WordPress footer but allow scrolling
            echo '<style>
                #wpfooter { display: none !important; }
                #wpbody-content { padding-bottom: 0 !important; }
                html, body, #wpwrap, #wpbody, #wpbody-content { 
                    overflow: visible !important; 
                    height: auto !important; 
                    min-height: 100vh;
                }
                #bundlepress-root { min-height: 100vh; }
                .update-nag, .notice, .error, .is-dismissible { display: none !important; }
            </style>';
        }
    }

    public function render_admin_page()
    {
        echo '<div id="bundlepress-root"></div>';
    }

    public function enqueue_frontend_scripts()
    {
        // Force WC session to start for guest users to ensure consistent nonces
        if (function_exists('WC') && WC()->session && !WC()->session->has_session()) {
            WC()->session->set_customer_session_cookie(true);
        }

        // ---- Frontend CSS (overrides WooCommerce p-margin rules) ----
        $css_path = BUNDLEPRESS_PATH . 'assets/bundlepress-frontend.css';
        $css_url = BUNDLEPRESS_URL . 'assets/bundlepress-frontend.css';
        if (file_exists($css_path)) {
            wp_enqueue_style(
                'bundlepress-frontend',
                $css_url,
                [],
                filemtime($css_path)
            );
        }

        // Widgets Frontend Loader (for bundles)
        $widgets_path = BUNDLEPRESS_PATH . 'assets/widgets.js';
        $widgets_url = BUNDLEPRESS_URL . 'assets/widgets.js';

        if (file_exists($widgets_path)) {
            wp_enqueue_script(
                'bundlepress-widgets',
                $widgets_url,
                ['react', 'react-dom'],
                filemtime($widgets_path),
                true
            );

            $cart_items = [];
            if (function_exists('WC') && WC()->cart) {
                foreach (WC()->cart->get_cart() as $item) {
                    $cart_items[] = [
                        'product_id' => (int) $item['product_id'],
                        'quantity' => (int) $item['quantity'],
                        'bundle_id' => isset($item['_bundlepress_bundle']) ? (int) $item['_bundlepress_bundle'] : 0
                    ];
                }
            }

            wp_localize_script('bundlepress-widgets', 'bundlePressData', [
                'restUrl' => esc_url_raw(rest_url()),
                'rootUrl' => esc_url_raw(home_url()),
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('wc_store_api'),
                'wpRestNonce' => wp_create_nonce('wp_rest'),
                'currencySymbol' => get_woocommerce_currency_symbol(),
                'decimalSeparator' => wc_get_price_decimal_separator(),
                'thousandSeparator' => wc_get_price_thousand_separator(),
                'priceDecimals' => wc_get_price_decimals(),
                'priceFormat' => get_woocommerce_price_format(),
                'cartItems' => $cart_items,
                'settings' => BundlePress_Settings_API::get_feature_settings(),
                'customizations' => BundlePress_Customization_API::get_customizations_data(),
            ]);
        }
    }

    public function inject_frontend_styles()
    {
?>
        <style id="bundlepress-header-overrides">
            /* Bundle UI Fixes */
            #bundlepress-bundle-root {
                width: 100% !important;
                display: block !important;
                clear: both !important;
                margin: 20px 0 !important;
            }

            .bundlepress-bundle-display {
                width: 100% !important;
                max-width: 100% !important;
            }

            /* Upsell widget */
            .bundlepress-upsell-root {
                width: 100% !important;
                display: block !important;
                clear: both !important;
            }

            /*
            * WooCommerce adds: .woocommerce div.product div.summary p { margin: 1em 0; }
            * which beats Chakra UI's inline margin:0. We counter it here with equal or
            * higher specificity, loaded AFTER woocommerce.css.
            */
            #bundlepress-bundle-root p,
            #bundlepress-bundle-root span,
            .bundlepress-upsell-root p,
            .bundlepress-upsell-root span,
            .bundlepress-bundle-display p,
            .bundlepress-bundle-display span {
                margin: 0;
                padding: 0;
            }

            /* Match WooCommerce's exact selector depth to guarantee we win */
            .woocommerce div.product div.summary #bundlepress-bundle-root p,
            .woocommerce div.product div.summary .bundlepress-upsell-root p,
            .woocommerce div.product div.summary .bundlepress-bundle-display p,
            .woocommerce-cart .bundlepress-upsell-root p {
                margin: 0 !important;
            }
        </style>
<?php
    }
}

new BundlePress_Plugin();
