# Connected Products Feature Guide

## Overview

The Connected Products feature allows products to include other products automatically. This is particularly useful for sponsor packages that include delegate passes, or bundle deals that combine multiple items.

## Database Schema

### `product_attachments` Table

```sql
CREATE TABLE `product_attachments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent_product_id` int(11) NOT NULL COMMENT 'The main product (e.g., sponsor package)',
  `attached_product_id` int(11) NOT NULL COMMENT 'The included product (e.g., delegate pass)',
  `quantity` int(11) NOT NULL DEFAULT 1 COMMENT 'How many of the attached product are included',
  `is_active` tinyint(1) DEFAULT 1 COMMENT 'Whether this attachment is currently active',
  `display_order` int(11) DEFAULT 0 COMMENT 'Order for displaying attached products',
  `notes` text DEFAULT NULL COMMENT 'Optional notes about this attachment',
  `created_at` timestamp NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_attachment` (`parent_product_id`, `attached_product_id`),
  CONSTRAINT `fk_parent_product` FOREIGN KEY (`parent_product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_attached_product` FOREIGN KEY (`attached_product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE
);
```

## Usage Examples

### Example 1: Platinum Sponsor Package
- **Parent Product**: Platinum Sponsor ($10,000)
- **Attached Products**: 
  - 5× Delegate Passes
  - 1× Table-top Presentation

### Example 2: Gold Sponsor Package
- **Parent Product**: Gold Sponsor ($5,000)
- **Attached Products**:
  - 3× Delegate Passes

## Admin Interface

### Adding Connected Products

1. **Navigate to Product Catalog**: Go to `admin/product-catalog.php`
2. **Create/Edit Product**: Click "Add Product" or edit an existing product
3. **Attached Products Section**: Scroll down to the "Attached Products" section
4. **Add Attachments**: 
   - Click "+ Add Attached Product"
   - Select the product to include
   - Set the quantity
   - Add optional notes
5. **Save**: Click "Save Product"

### Managing Connected Products

- **View Attachments**: Product cards show included products in the "Includes" section
- **Edit Attachments**: Edit the parent product to modify attached products
- **Remove Attachments**: Use the "×" button next to each attached product

## API Endpoints

### Get Attached Products
```php
GET /admin/product_api.php?action=get_attached_products&product_id=123
```

**Response:**
```json
{
  "success": true,
  "attachments": [
    {
      "id": 1,
      "attached_product_id": 6,
      "quantity": 5,
      "product_name": "Delegates",
      "product_code": "dsdsd",
      "base_price": "100.00",
      "category_name": "Delegate Passes"
    }
  ]
}
```

## Backend Functions

### Core Functions

```php
// Save attached products for a parent product
saveAttachedProducts($parentProductId, $attachedProducts)

// Get attached products for a parent product
getAttachedProducts($parentProductId)
```

### Usage in Forms

The attached products data is serialized as JSON and sent with the product form:

```javascript
// Serialize attached products before form submission
document.getElementById('attachedProductsData').value = serializeAttachedProducts();
```

## Frontend JavaScript

### Key Functions

```javascript
// Add a new attached product row
addAttachedProduct()

// Update attached product data
updateAttachedProduct(index, field, value)

// Remove an attached product
removeAttachedProduct(index)

// Load attached products for editing
loadAttachedProducts(productId)

// Clear all attached products
clearAttachedProducts()

// Serialize data for form submission
serializeAttachedProducts()
```

## Database Migration

To add this feature to an existing system:

1. **Run Migration**: Execute `sql/add_attached_products.sql`
2. **Verify Tables**: Check that `product_attachments` table is created
3. **Test Functionality**: Create a test product with attachments

## Business Logic Integration

### Registration Process

When a customer purchases a product with attachments:

1. **Main Product**: Added to cart/registration
2. **Attached Products**: Automatically included (quantity × attachment quantity)
3. **Pricing**: Only the parent product price is charged
4. **Stock Management**: Both parent and attached product stock is decremented

### Inventory Management

- **Parent Product Stock**: Decremented when purchased
- **Attached Product Stock**: Decremented by (quantity × attachment_quantity)
- **Availability Check**: Both parent and attached products must be available

## Styling

The feature includes comprehensive CSS styling:

- **Form Styling**: Clean, responsive form layout for managing attachments
- **Product Cards**: Visual indicators showing included products
- **Mobile Responsive**: Optimized for mobile devices

## Security Considerations

- **Authentication**: Requires admin permissions to manage
- **Validation**: Prevents circular dependencies (product including itself)
- **Data Integrity**: Foreign key constraints ensure data consistency

## Troubleshooting

### Common Issues

1. **Products Not Showing**: Check that products are active and not deleted
2. **Attachments Not Saving**: Verify JSON serialization is working
3. **Display Issues**: Check CSS classes and responsive design

### Debug Steps

1. **Check Database**: Verify `product_attachments` table exists
2. **Check API**: Test API endpoints directly
3. **Check JavaScript**: Use browser console to debug form submission
4. **Check PHP**: Review error logs for backend issues

## Future Enhancements

Potential improvements:
- **Conditional Attachments**: Based on quantity or other criteria
- **Attachment Pricing**: Different pricing for attached products
- **Bulk Management**: Tools for managing multiple attachments
- **Reporting**: Analytics on attachment usage and effectiveness
