# Combo Items Implementation

## Overview
This implementation adds comprehensive combo item support to the POS inventory system. Combo items are products that consist of multiple individual components, allowing for complex inventory management and stock validation.

## Features Implemented

### 1. Database Schema
- **Updated `items` table**: Added `combo` as a new sell_type option
- **New `items_combo` table**: Stores relationships between combo items and their components
- **Migration scripts**: Automatically update all branch schemas
- **Template updates**: New branches automatically include combo support

### 2. Inventory Management (inventory.php)
- **Combo sell type**: New option in add/edit item forms
- **Component selection**: Dynamic UI for adding multiple components to combo items
- **Quantity specification**: Set required quantity for each component
- **Real-time validation**: Prevent circular dependencies and invalid combinations

### 3. Stock Management
#### Complex Stock Validation
- **Component availability**: Combo items show as out of stock if any component is unavailable
- **Conflict detection**: Validates when individual items and combo items compete for the same components
- **Real-time calculation**: Accurately calculates maximum available combo quantities

#### Example Scenario Handled:
```
Inventory: #21 Rice = 1 left
Cart:
- 1x #21 Rice (direct) ✓
- 1x Chicken Combo (needs 1x #21 Rice) ✓
Total demand for #21 Rice = 2, Available = 1 ❌

Result: System blocks the sale and shows detailed conflict information
```

### 4. POS Integration (items.php)
- **Smart stock status**: Combo items automatically show correct availability based on components
- **Pre-sale validation**: Cart validates all items before processing
- **Stock deduction**: Sales properly deduct from component items, not combo items
- **Visual indicators**: Clear stock status display for combo items

### 5. Transaction Processing (save_sale.php)
- **Component-based deduction**: Stock is deducted from individual components
- **Transaction safety**: All operations are wrapped in database transactions
- **Audit trail**: Proper logging of combo component stock movements

### 6. Void Operations (audit_helper.php)
- **Proper stock restoration**: When combo sales are voided, stock returns to components
- **Audit compliance**: Full audit trail maintained for all operations
- **Backward compatibility**: Regular items continue to work normally

## Database Structure

### items_combo Table
```sql
CREATE TABLE items_combo (
  combo_id INT AUTO_INCREMENT PRIMARY KEY,
  parent_item_id INT NOT NULL,           -- ID of the combo item
  component_item_id INT NOT NULL,        -- ID of the component item  
  quantity_required DECIMAL(10,3) NOT NULL, -- Qty needed per combo
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY unique_combo_component (parent_item_id, component_item_id)
);
```

## API Endpoints

### Inventory Handler (inventory_handler.php)
- `GET ?action=get_combo_components&item_id={id}` - Get components for editing
- `GET ?action=check_combo_availability&combo_id={id}&quantity={qty}` - Check availability
- `POST ?action=validate_cart_stock` - Validate entire cart for conflicts

### Component Management
- Create combo items with multiple components
- Edit existing combo components
- Delete combo items (cascades to components)

## Stock Helper Functions

### combo_stock_helper.php
- `getComboComponents($combo_item_id)` - Get all components for a combo
- `checkComboAvailability($combo_item_id, $quantity)` - Check if combo can be sold
- `validateCartStock($cart_items)` - Validate entire cart including conflicts
- `getItemStockStatus($item)` - Get display status (in_stock/low_stock/out_of_stock)

## User Interface

### Inventory Management
1. **Add Item**: Select "Combo" sell type to reveal component selection
2. **Add Components**: Click "Add Component" to add items with quantities
3. **Edit Combo**: Components load automatically when editing combo items
4. **Visual Feedback**: Clear indication of combo vs regular items

### POS Interface
1. **Stock Status**: Combo items show proper availability based on components
2. **Cart Validation**: Automatic conflict detection before checkout
3. **Error Messages**: Detailed breakdown of stock conflicts when they occur

## Technical Implementation Details

### Stock Status Calculation
```php
// For combo items
$availability = checkComboAvailability($item_id, 1);
if (!$availability['available']) return 'out_of_stock';

// For regular items  
if ($current_stock <= 0) return 'out_of_stock';
```

### Stock Deduction Logic
```php
// During sales - deduct from components, not combo item
if ($sell_type === 'combo') {
    foreach ($components as $component) {
        $qty_needed = $component['quantity_required'] * $sold_qty;
        updateItemStock($component_id, -$qty_needed, 'combo_sale', $sale_id);
    }
}
```

### Void Operations
```php
// During voids - restore to components, not combo item
if ($sell_type === 'combo') {
    foreach ($components as $component) {
        $qty_to_restore = $component['quantity_required'] * $voided_qty;
        updateItemStock($component_id, +$qty_to_restore, 'combo_void', $sale_id);
    }
}
```

## Migration and Setup

### Automatic Schema Updates
```bash
# Run the schema update script
php scripts/update_combo_schemas.php
```

### Features Include:
- Updates all existing branch schemas
- Adds combo sell_type to items tables
- Creates items_combo tables with proper foreign keys
- Maintains data integrity during migration

## Testing Scenarios

### 1. Basic Combo Creation
- Create combo item with 2+ components
- Verify component relationships stored correctly
- Edit combo and modify components

### 2. Stock Availability
- Set component stock levels
- Verify combo shows correct availability
- Test with one component out of stock

### 3. Complex Cart Validation
- Add individual items to cart
- Add combo items using same components
- Verify conflict detection works correctly

### 4. Sales Processing
- Process sale with combo items
- Verify stock deducted from components
- Check audit trail shows proper transactions

### 5. Void Operations
- Void sale containing combo items
- Verify stock restored to components
- Check audit trail accuracy

## Backward Compatibility

- All existing functionality remains unchanged
- Regular items work exactly as before
- Existing sales data unaffected
- Gradual adoption possible (can mix combo and regular items)

## Performance Considerations

- Component lookups cached during operations
- Batch stock validation for large carts
- Database indexes on combo relationships
- Efficient sorting with combo stock status

## Security Features

- Proper foreign key constraints prevent orphaned records
- Transaction-safe operations prevent partial updates
- Input validation on all combo operations
- Audit trail for all stock movements

## Future Enhancements

Potential improvements that could be added:
- Combo pricing rules (discount vs sum of components)
- Multi-level combos (combos containing other combos)
- Automatic combo suggestions based on sales patterns
- Bulk combo management tools
- Advanced reporting for combo performance

This implementation provides a solid foundation for combo item management while maintaining system integrity and performance. 