# Product Bundle Quantity

**Contributors:** kundankb
**Tags:** bundles, quantity, discounts, product bundles, customizable colors, license management
**Requires at least:** 5.9
**Tested up to:** 6.9
**Stable tag:** 2.5.0
**Requires PHP:** 7.4
**WC requires at least:** 5.0
**WC tested up to:** 8.5
**License:** GPLv2 or later
**License URI:** http://www.gnu.org/licenses/gpl-2.0.html

Create custom product bundles with specific quantities and discounts for WooCommerce. Fully customizable with color options, theme auto-detection, flexible display controls, and premium license management.

## Description

Product Bundle Quantity is a comprehensive WooCommerce extension that allows you to create and manage product bundles with custom quantities, images, and discounts. Perfect for stores selling items in bulk or offering volume discounts, this plugin provides a seamless shopping experience with fully customizable frontend appearance.

### What This Plugin Does

- **Create Bundle Packages**: Set up multiple bundle options per product, each with specific quantities
- **Visual Bundle Selection**: Customers see attractive bundle cards with custom images and pricing
- **Smart Pricing**: Automatic price calculations with optional discount percentages (premium feature)
- **Seamless Cart Integration**: Selected bundles automatically add the correct quantity and pricing to cart
- **Fully Customizable**: Match your theme's colors automatically or customize every visual element
- **Premium License System**: Optional upgrade for advanced features like discounts and per-product colors

### Perfect For

- Bulk sales (e.g., "Buy 3, 6, or 12 units")
- Volume discounts (e.g., "Save 10% on packs of 6")
- Product samplers (e.g., "Try 3 flavors" or "Sample pack")
- Gift sets and bundles
- Wholesale pricing tiers
- Any scenario where you want to encourage larger purchases

## Features

### Bundle Management
- Easy-to-use admin interface for creating and managing product bundles
- Supports multiple bundles per product, each with unique images and discounts
- Seamless integration with WooCommerce's product gallery and cart system
- Shortcode support: **[kund_bundle_options]** for flexible placement
- Dynamic pricing calculation with real-time updates
- Custom bundle images that sync with product gallery

### Premium License Management (NEW in 2.5.0)
- **Secure License Activation**: API-based license validation system
- **Premium Feature Control**: Feature-specific access management
- **Dashboard Integration**: Dedicated dashboard with statistics and quick actions
- **License Status Monitoring**: Real-time license validation and expiration tracking
- **Automatic License Checks**: Daily cron job for license status verification
- **Grace Period Handling**: Smart expiration notifications and warnings
- **Multi-Site Support**: Device ID-based activation tracking
- **Cache Optimization**: 12-hour transient caching for performance

### Premium Features (License Required)
- **Custom Colors per Product**: Override global color settings for individual products (Premium)
- **Product Discounts**: Set custom discount percentages on bundle quantities (Premium)
- **Priority Support**: Direct access to expert support team (Premium)

### Color Customization
- **9 Customizable Colors**: Complete control over all frontend visual elements
- **Automatic Theme Detection**: Auto-detect and apply your WordPress theme's color palette
- **Per-Product Overrides**: Set custom colors for individual products (Premium feature)
- **WCAG 2.1 AA Compliant**: Built-in contrast ratio validation for accessibility
- **Live Preview**: See color changes in real-time with WordPress color picker
- **Smart Color Mapping**: Intelligent theme color detection from theme.json and theme mods

### Display Controls
- **Toggle Stock Label**: Show/hide the "In Stock" indicator
- **Toggle Security Message**: Control visibility of the security assurance message
- **Flexible Configuration**: Global settings with per-product customization
- **Tabbed Settings Interface**: Organized settings with Colors and Display Options tabs

### Performance & Compatibility
- Modern CSS custom properties for efficient styling
- Minimal performance impact with optimized code
- Compatible with all modern WordPress and WooCommerce versions
- Works seamlessly with block themes and classic themes
- **HPOS Compatible**: Full support for WooCommerce High-Performance Order Storage
- Transient caching for license validation to reduce API calls

## Installation

1. Upload the plugin files to the `/wp-content/plugins/product-bundle-quantity` directory, or install the plugin directly through the WordPress plugins screen.
2. Activate the plugin through the 'Plugins' screen in WordPress.
3. Navigate to the product edit screen where you want to add bundles.
4. Use the new **Bundle Quantity Options** section to add and configure your bundles.

## Usage

### Activating Premium License (NEW in 2.5.0)

1. Navigate to **Bundle Quantities** > **License** in the WordPress admin menu
2. Enter your license key (format: XXXX-XXXX-XXXX-XXXX)
3. Click **Activate License**
4. Once activated, premium features will be unlocked automatically
5. View license status, expiration date, and active features in the dashboard

**Note**: Purchase your premium license at [codemoksha.com](https://codemoksha.com)

### Using the Dashboard

1. Navigate to **Bundle Quantities** > **Dashboard**
2. View plugin statistics including:
   - Number of products with bundles enabled
   - Premium features activation status
   - Plugin version information
3. Access quick actions:
   - Add New Product
   - Configure Settings
   - View Bundle Products
   - Activate Premium License (if not already active)
4. Check license status and premium feature availability

### Creating Bundles

1. Go to **Products** > **All Products** and edit the product for which you want to create bundles
2. Scroll down to the **Product Data** > **Bundle Quantities** tab
3. Check **Enable Bundle Quantity** to activate bundles for this product
4. Click **Add Bundle Option** to create a new bundle
5. Enter the quantity and upload an image for the bundle
6. **Premium Only**: Set a discount percentage (requires active license)
7. Repeat for any additional bundles you want to create
8. Save or update the product

**Note**: Without a premium license, discount fields will be disabled and bundles will show without discounts.

### Customizing Colors

#### Global Settings
1. Navigate to **Bundle Quantities** > **Settings**
2. In the **Colors** tab:
   - Click **Auto-Detect Theme Colors** to automatically match your theme
   - Or manually customize each of the 9 color options using the color picker
   - The system will warn you if color contrast doesn't meet accessibility standards
3. In the **Display Options** tab:
   - Toggle **Show "In Stock" label** on/off
   - Toggle **Show security message** on/off
4. Click **Save Changes**

#### Per-Product Customization (Premium Feature)
1. Edit any product with bundle quantities enabled
2. In the **Bundle Quantities** tab, check **Use Custom Colors** (requires premium license)
3. Customize up to 4 key colors for this specific product:
   - Selected Bundle Border
   - Selected Bundle Background
   - Add to Cart Button
   - Saving Badge
4. These settings will override global colors for this product only
5. Click the **Manage Global Settings** button to edit site-wide colors

**Note**: Per-product color customization requires an active premium license.

### Using the Shortcode

You can place bundle options anywhere on your product page using the shortcode:

```
[kund_bundle_options]
```

This is useful if you want to override the default placement or use bundles in custom page templates.

### Frontend Display

Once bundles are created, they will appear on the single product page as selectable options. Customers can:
- Click on a bundle to select it
- View the bundle image, quantity, and price per unit
- See the total price with discount applied (if available)
- Add the selected bundle to cart with one click

The appearance will match your customized colors and display settings. The default "Add to Cart" button is automatically replaced with the bundle interface when bundles are enabled for a product.

## Frequently Asked Questions

### General Questions

**Q: Can I create multiple bundles for a single product?**
A: Yes, you can create as many bundles as needed, each with its own image and discount (discount requires premium license).

**Q: How do I remove or edit a bundle?**
A: In the product edit screen, simply delete or modify the bundle in the **Bundle Quantity Options** section.

**Q: Does the plugin work with variable products?**
A: Currently, the plugin is designed for simple products. Variable product support may be added in future versions.

**Q: Does this plugin affect my site's performance?**
A: No. The plugin uses modern CSS custom properties for efficient styling with minimal overhead. License validation is cached for 12 hours to minimize API calls.

### License & Premium Features

**Q: How do I get a premium license?**
A: Visit [codemoksha.com](https://codemoksha.com) to purchase a premium license key.

**Q: What happens if my license expires?**
A: You'll receive warnings 30 days before expiration. After expiration, premium features (discounts and per-product colors) will be disabled, but basic bundle functionality remains active.

**Q: Can I use my license on multiple sites?**
A: License activation is tied to a specific domain. For multiple sites, you'll need separate licenses or an agency/multi-site license.

**Q: How does license validation work?**
A: The plugin validates your license with the Code Moksha API server. Validation results are cached for 12 hours, and a daily cron job checks license status to ensure continued validity.

**Q: What features are available without a premium license?**
A: Without a premium license, you can:
- Create bundle quantities for products
- Upload custom images for bundles
- Use global color settings
- Toggle display options (stock label, security message)
- Use theme auto-detection for colors

**Q: What premium features require a license?**
A: Premium features include:
- Setting discount percentages on bundles
- Per-product color customization
- Priority support

### Customization Questions

**Q: How does theme color detection work?**
A: The plugin automatically detects colors from your active theme's `theme.json` (for block themes) or theme customizer settings (for classic themes). Simply click "Auto-Detect Theme Colors" in the settings.

**Q: Can I use different colors for different products?**
A: Yes! With a premium license, set global colors in Bundle Quantities > Settings, then enable "Use Custom Colors" on individual products to override the global settings.

**Q: Is the plugin accessible?**
A: Yes! The plugin includes built-in WCAG 2.1 AA contrast ratio validation and will warn you if color combinations don't meet accessibility standards.

**Q: Can I hide the stock label or security message?**
A: Yes, you can control the visibility of both elements in Bundle Quantities > Settings > Display Options.

**Q: Can I place bundles in a custom location on the product page?**
A: Yes! Use the `[kund_bundle_options]` shortcode to place bundle options anywhere you want.

### Technical Questions

**Q: Is the plugin compatible with WooCommerce HPOS?**
A: Yes, the plugin fully supports WooCommerce High-Performance Order Storage (HPOS).

**Q: Does the plugin work with block themes?**
A: Yes, the plugin is compatible with both classic and block themes, and can automatically detect colors from block theme's theme.json.

**Q: How often does the plugin check license validity?**
A: A daily cron job validates the license status. Manual checks can be performed from the License page using the "Check License Status" button.

## Screenshots

1. **Admin Interface** - Easily create and manage product bundles.

![Product quantity bundle backend](assets/images/backend.png?raw=true "Product quantity bundle backend")

2. **Frontend Display** - Customers can choose from multiple bundles on the product page.


![Product quantity bundle frontend](assets/images/frontend1.png?raw=true "Product quantity bundle frontend 1")
![Product quantity bundle frontend](assets/images/frontend2.png?raw=true "Product quantity bundle frontend 2")


## Changelog

### 2.5.0 - 2025-12-29

#### Major Features - Premium License System
- **Complete License Management System**
  - API-based license validation with Code Moksha licensing server
  - Secure license activation/deactivation workflow
  - Real-time license status monitoring
  - Feature-specific access control (custom colors, product discounts)
  - Daily automated license validity checks via WP Cron
  - 12-hour transient caching to minimize API requests

- **Dashboard Interface**
  - New dedicated dashboard at Bundle Quantities > Dashboard
  - License status banner (premium/free)
  - Plugin statistics (products with bundles, active features, version)
  - Quick action cards (Add Product, Settings, View Products, Activate License)
  - Features overview with free vs premium comparison
  - Getting Started guide
  - Support & Resources links

- **License Management Page**
  - Dedicated license page at Bundle Quantities > License
  - License activation form with validation
  - License status display (active, expired, inactive)
  - Purchase and expiration date tracking
  - Active features list from API response
  - Manual license check and cache refresh options
  - Masked license key display for security
  - Premium features list with access status

#### Premium Features Gating
- **Product Discounts** (Premium Only)
  - Discount percentage fields disabled for free users
  - Premium upgrade prompts in product edit screen
  - Discounts automatically set to empty for non-premium users
  - Visual indicators showing locked features

- **Per-Product Custom Colors** (Premium Only)
  - Color customization fields locked without license
  - Upgrade notices in Bundle Quantities tab
  - Seamless fallback to global colors for free users

#### Technical Improvements
- Device ID generation for multi-site tracking
- Flexible API feature name matching (handles various formats)
- Fail-open policy for valid licenses (customer-friendly)
- Comprehensive debug logging (WP_DEBUG mode)
- WordPress admin notices for license expiration warnings
- Automatic status updates based on expiration dates
- Proper nonce and capability checks on all AJAX endpoints
- Complete sanitization of license data

#### User Experience
- Clear premium vs free feature separation
- Helpful upgrade prompts throughout admin interface
- Non-intrusive premium feature notices
- License expiration warnings (30 days before expiry)
- Debug mode for administrators (?kbq_debug parameter)
- Improved admin menu structure with Dashboard, Settings, and License pages

#### Security & Performance
- All license API communications over HTTPS
- Transient caching reduces server load
- Input sanitization on all license operations
- Rate limiting considerations in API design
- Secure license key masking in UI
- WP Options API for persistent storage

#### Bug Fixes
- Fixed checkbox state handling in display options tab
- Improved license data persistence with proper sanitization callback
- Enhanced error messages for API failures
- Graceful degradation when license API is unavailable

### 2.4.0 - 2025-12-22

#### Major Features
- **Complete Color Customization System**
  - Added 9 customizable color options for all frontend elements
  - Implemented WordPress Iris color picker integration
  - Created dedicated settings page under WooCommerce menu with tabbed interface

- **Automatic Theme Color Detection**
  - Auto-detect colors from theme.json (Block themes)
  - Auto-detect colors from theme customizer (Classic themes)
  - Smart color mapping with intelligent fallbacks
  - One-click "Auto-Detect Theme Colors" button

- **Per-Product Color Overrides**
  - Allow custom colors for individual products
  - Seamless fallback to global settings
  - Easy toggle to enable/disable per-product customization

- **Display Toggle Controls**
  - Toggle "In Stock" label visibility
  - Toggle security message visibility
  - Visual previews in admin settings

#### Accessibility & Performance
- **WCAG 2.1 AA Compliance**
  - Real-time contrast ratio validation
  - Automatic warnings for insufficient contrast
  - Minimum 4.5:1 ratio enforcement for text

- **Performance Optimizations**
  - CSS custom properties for efficient styling
  - Single inline style block (minimal overhead)
  - WordPress Options API caching
  - Conditional asset loading

#### User Experience
- Settings organized in intuitive tabbed interface (Colors | Display Options)
- Live color preview with WordPress color picker
- Clear descriptions and help text
- Link to global settings from product edit page

#### Technical Improvements
- Updated to WordPress 5.9+ minimum requirement
- PHP 7.4+ requirement
- WooCommerce 5.0+ compatibility
- Modern CSS custom properties with fallbacks
- Complete internationalization support
- WordPress coding standards compliant
- Security: All inputs sanitized, all outputs escaped
- Nonces and capability checks on all forms
- WooCommerce HPOS compatibility declared

#### Bug Fixes
- Fixed admin.css path typo in enqueue function
- Improved error handling for theme detection
- Enhanced color sanitization with validation

### 2.2.0 - Initial Release
- Basic bundle creation and management features
- Multiple bundles per product support
- Custom images for bundles
- Discount percentage support
- Cart integration with pricing adjustments

## Menu Structure

The plugin adds a new top-level menu in WordPress admin with the following pages:

- **Bundle Quantities** (Main Menu)
  - **Dashboard** - Overview of plugin statistics, license status, and quick actions
  - **Settings** - Configure global colors and display options
  - **License** - Activate and manage your premium license

All pages are accessible to users with `manage_woocommerce` capability.

## Free vs Premium

### Free Features
- Create unlimited bundle quantities for products
- Upload custom images for each bundle
- 9 customizable global colors for frontend display
- Automatic theme color detection
- Display option toggles (stock label, security message)
- Shortcode support for flexible placement
- WooCommerce HPOS compatibility
- WCAG 2.1 AA contrast validation

### Premium Features (License Required)
- **Product Discounts**: Set custom discount percentages on bundle quantities
- **Per-Product Colors**: Override global colors for individual products (4 customizable colors)
- **Priority Support**: Direct access to expert support team

[Get Premium License →](https://codemoksha.com)

## API Integration

The plugin integrates with the Code Moksha licensing API for premium license validation:

- **Endpoint**: `https://codemoksha.com/api/license/validate`
- **Validation Method**: POST with JSON body
- **Cache Duration**: 12 hours (WordPress transients)
- **Cron Schedule**: Daily license validity check
- **Security**: HTTPS-only, nonce verification, capability checks

For API implementation details, see [includes/sample-api-endpoint.php](includes/sample-api-endpoint.php).

## Developer Notes

### Action Hooks
The plugin uses standard WordPress and WooCommerce hooks:
- `plugins_loaded` - Initialize plugin
- `before_woocommerce_init` - Declare HPOS compatibility
- `admin_enqueue_scripts` - Load admin assets
- `wp_enqueue_scripts` - Load frontend assets
- `woocommerce_before_add_to_cart_button` - Display bundle options
- `woocommerce_before_calculate_totals` - Apply bundle discounts

### Filter Hooks
- `woocommerce_product_data_tabs` - Add Bundle Quantities tab
- `woocommerce_add_cart_item_data` - Add bundle data to cart
- `woocommerce_cart_item_price` - Modify cart item price display

### Shortcode
`[kund_bundle_options]` - Display bundle options anywhere on the product page

### Database Storage
- **Plugin Settings**: `wp_options` table, key: `kund_bundle_quantity_settings`
- **License Data**: `wp_options` table, key: `kbq_license_data`
- **Device ID**: `wp_options` table, key: `kbq_device_id`
- **Product Meta**:
  - `_enable_bundle_quantity` - Enable/disable bundles for product
  - `_bundle_options` - Array of bundle configurations
  - `_kund_bundle_custom_colors_enabled` - Enable custom colors for product
  - `_kund_bundle_custom_colors` - Array of custom colors for product

### CSS Variables
The plugin generates CSS custom properties for theming:
- `--kbq-selected-border`
- `--kbq-selected-bg`
- `--kbq-default-border`
- `--kbq-button-bg`
- `--kbq-button-text`
- `--kbq-saving-badge`
- `--kbq-price-text`
- `--kbq-secondary-text`
- `--kbq-muted-text`

## Support

For support and documentation:
- **Plugin Website**: [codemoksha.com](https://codemoksha.com)
- **Documentation**: [codemoksha.com/docs](https://codemoksha.com/docs)
- **Support Portal**: [codemoksha.com/support](https://codemoksha.com/support)
- **Author**: Code Moksha
- **Author Website**: [codemoksha.com](https://codemoksha.com)

## License

This plugin is licensed under the GPLv2 or later.

---
