<?php
/**
 * Plugin Name: BundlePress – Grouped Product Bundle Builder for WooCommerce
 * 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.1.0
 * Author: Dominopress
 * Author URI: https://dominopress.com
 * Text Domain: bundlepress
 * Requires at least: 6.8
 * Tested up to: 6.9
 * Requires PHP: 7.4
 * WC requires at least: 8.0
 * WC tested up to: 8.6
 * 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.1.0');
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/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-store-notice.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()
    {
        // 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_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');

        // 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 Store Notice & Insights
        BundlePress_Store_Notice::init();
        new BundlePress_Insights();
        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']);
    }

    public function register_post_types()
    {
        register_post_type('bundlepress_bundle', [
            'labels' => [
                'name' => 'Bundles',
                'singular_name' => 'Bundle',
            ],
            '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';
        $settings_table = $wpdb->prefix . 'bundlepress_settings';
        $analytics_table = $wpdb->prefix . 'bundlepress_analytics';

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

        if (!$bundles_exists || !$settings_exists || !$analytics_exists) {
            BundlePress_DB::init();
        }
    }

    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');
    }

    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-settings'));
                exit;
            }
        }
    }

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

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

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

        // Add Settings submenu for BundlePress core settings
        add_submenu_page(
            'bundlepress',
            'Settings',
            'Settings',
            'manage_options',
            'bundlepress-settings',
            [$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'
        ];

        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';

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

        if (file_exists($script_path)) {
            wp_enqueue_script(
                'bundlepress-admin',
                $script_url,
                ['bundlepress-vendors', 'wp-element'],
                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-analytics') {
                $currentPage = 'analytics';
            } 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(),
                'settings' => BundlePress_Settings_API::get_feature_settings(),
            ]);

            // 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(),
                'cartItems' => $cart_items,
                'settings' => BundlePress_Settings_API::get_feature_settings(),
            ]);
        }
    }

    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();
