# Enhanced WooCommerce Sync Features

This document explains the new enhanced sync functionality that can be activated by setting `SYNC_STYLE=managemore` in your environment configuration.

## Overview

The enhanced sync provides comprehensive product synchronization with advanced features including dynamic selling price groups, enhanced meta data handling, and improved variation management.

## Environment Configuration

To enable enhanced sync, add this to your `.env` file:

```env
SYNC_STYLE=managemore
```

When this is set, the system will use the enhanced sync logic. When not set or set to any other value, it will use the standard sync logic.

## Enhanced Features

### 1. Dynamic Selling Price Groups

The enhanced sync automatically creates and manages multiple price groups for each product variation:

#### Price Groups Supported:
- **Silver** (Price Group ID: 1) - `wholesale_customer_wholesale_price`
- **Gold** (Price Group ID: 2) - `mm_price_2_wholesale_price`
- **Platinum** (Price Group ID: 3) - `mm_price_3_wholesale_price`
- **Lowest Price** (Price Group ID: 4) - `mm_product_lowest_price`
- **Diamond** (Price Group ID: 5) - `mm_price_4_wholesale_price`

#### Implementation:
```php
private function createDynamicPriceGroups($variation_id, $prices)
{
    $priceGroupData = [];
    
    // Silver price group (ID: 1)
    if (!empty($prices['silver']) && $prices['silver'] > 0) {
        $priceGroupData[] = [
            'price_group_id' => 1,
            'price_inc_tax' => $prices['silver'],
            'price_type' => 'fixed',
            'variation_id' => $variation_id,
        ];
    }
    
    // Additional price groups...
    
    // Create price group records
    foreach ($priceGroupData as $priceData) {
        VariationGroupPrice::updateOrCreate(
            [
                'variation_id' => $variation_id,
                'price_group_id' => $priceData['price_group_id']
            ],
            $priceData
        );
    }
}
```

### 2. Enhanced Meta Data Handling

The enhanced sync processes comprehensive meta data from WooCommerce:

#### Meta Fields Processed:
- **Product Basis**: `mm_product_basis_1` (ML), `mm_product_basis_2` (CT)
- **Pricing**: All wholesale price variations
- **Stock**: `_stock`, `_stock_status`, `_manage_stock`
- **Barcodes**: `mm_product_upc`
- **Tax Types**: `mm_indirect_tax_type`
- **Sales Data**: `total_sales`
- **Quantity Limits**: `max_quantity`, `max_quantity_var`

#### Implementation:
```php
// Extract meta data for enhanced sync
$meta_data = $woo_product['meta_data'] ?? [];
$meta_map = [];
foreach ($meta_data as $meta) {
    $meta_map[$meta['key']] = $meta['value'];
}

// Use meta data in product creation
$product_data = [
    'ml' => $meta_map['mm_product_basis_1'] ?? null,
    'ct' => $meta_map['mm_product_basis_2'] ?? null,
    'maxSaleLimit' => ($meta_map['max_quantity'] ?? 0) > 0 ? $meta_map['max_quantity'] : null,
    'top_selling' => $meta_map['total_sales'] ?? 0,
    // ... other fields
];
```

### 3. Advanced Category Management

Enhanced category handling with support for multiple categories:

#### Features:
- Multiple category support
- Custom sub-categories array
- Primary and sub-category assignment
- Category relationship management

#### Implementation:
```php
private function handleProductCategories($product, $categories, $business_id)
{
    $count = 0;
    $custom_sub_categories = [];
    
    foreach ($categories as $category_data) {
        $category = Category::firstOrCreate(
            ['slug' => $category_data['slug']],
            [
                'business_id' => $business_id,
                'name' => $category_data['name'],
                'category_type' => 'product',
                // ... other fields
            ]
        );
        
        $custom_sub_categories[] = $category->id;
        
        // Set primary and sub categories
        if ($count == 0) {
            $product->update(['category_id' => $category->id]);
        } else if ($count == 1) {
            $product->update(['sub_category_id' => $category->id]);
        }
        
        $count++;
    }
    
    // Update custom sub categories
    $product->update(['custom_sub_categories' => json_encode($custom_sub_categories)]);
}
```

### 4. Image Management

Automatic image download and storage:

#### Features:
- Product image download from WooCommerce
- Variation image handling
- Automatic file extension detection
- Storage in organized directory structure

#### Implementation:
```php
private function downloadAndStoreImage($image_url, $product_id, $is_variation = false)
{
    try {
        $response = Http::timeout(30)->get($image_url);
        if ($response->successful()) {
            $image_data = $response->body();
            $extension = 'jpg'; // Default extension
            
            // Try to determine extension from URL
            $url_parts = parse_url($image_url);
            if (isset($url_parts['path'])) {
                $path_parts = pathinfo($url_parts['path']);
                if (isset($path_parts['extension'])) {
                    $extension = strtolower($path_parts['extension']);
                }
            }
            
            $filename = 'product_' . $product_id . '_' . time() . '.' . $extension;
            $path = 'uploads/products/' . $filename;
            
            // Store the image
            Storage::disk('public')->put($path, $image_data);
            
            return $path;
        }
    } catch (\Exception $e) {
        Log::error('Failed to download image: ' . $e->getMessage());
    }
    
    return null;
}
```

### 5. Tax Type Mapping

Automatic tax type mapping based on meta data:

#### Tax Type Mappings:
- `14346` → Location ID: 1
- `14347` → Location ID: 6
- `14344` → Location ID: 2
- `14343` → Location ID: 5
- `14345` → Location ID: 3

#### Implementation:
```php
private function setProductTaxType($product_id, $tax_type)
{
    $locationTaxType = [];
    
    // Map tax types to location IDs
    switch ($tax_type) {
        case '14346':
            $locationTaxType = [1];
            break;
        case '14347':
            $locationTaxType = [6];
            break;
        // ... other mappings
    }
    
    if (!empty($locationTaxType)) {
        $locationTaxTypeString = '[' . implode(',', array_map(function($item) {
            return '"' . $item . '"';
        }, $locationTaxType)) . ']';
        
        DB::table('products')
            ->where('id', $product_id)
            ->update(['locationTaxType' => $locationTaxTypeString]);
    }
}
```

### 6. Enhanced Variation Management

Advanced variation handling with template support:

#### Features:
- Variation template creation
- Variation value templates
- Attribute-based variation naming
- Enhanced SKU management
- Barcode support for variations

#### Implementation:
```php
private function createEnhancedVariation($business_id, $product, $productVariation, $variation)
{
    // Extract meta data
    $meta_map = [];
    foreach ($variation['meta_data'] ?? [] as $meta) {
        $meta_map[$meta['key']] = $meta['value'];
    }
    
    // Handle attributes
    $variationName = 'Default';
    if (!empty($variation['attributes'])) {
        foreach ($variation['attributes'] as $attr_name => $attr_value) {
            if (in_array(strtolower($attr_name), ['size', 'color', 'style', 'flavor'])) {
                $variationName = $attr_value;
                break;
            }
        }
    }
    
    // Create variation template and value
    $variationTemplate = VariationTemplate::updateOrCreate(
        ['name' => 'Flavor'],
        ['business_id' => $business_id]
    );
    
    $variationTemplateValue = VariationValueTemplate::updateOrCreate(
        ['name' => $variationName],
        ['variation_template_id' => $variationTemplate->id]
    );
    
    // Create ERP variation with all enhanced data
    $erpVariation = Variation::updateOrCreate(
        ['sub_sku' => $var_sku],
        [
            'name' => $variationName,
            'product_id' => $pid,
            'product_variation_id' => $productVariation->id,
            'variation_value_id' => $variationTemplateValue->id,
            'default_purchase_price' => $costPrice,
            'dpp_inc_tax' => $costPrice,
            'profit_percent' => '0.0000',
            'default_sell_price' => $lowestPrice,
            'sell_price_inc_tax' => $lowestPrice,
            'var_barcode_no' => $var_barcode_no,
            'var_maxSaleLimit' => $max_quantity_var
        ]
    );
    
    // Create dynamic price groups
    $this->createDynamicPriceGroups($erpVariation->id, [
        'silver' => $silverPrice,
        'gold' => $goldPrice,
        'platinum' => $platinumPrice,
        'diamond' => $diamondPrice,
        'lowest' => $lowestPrice
    ]);
}
```

## Usage

### 1. Enable Enhanced Sync

Add to your `.env` file:
```env
SYNC_STYLE=managemore
```

### 2. Sync Products

Use the existing sync buttons in the WooCommerce interface:
- **"Sync All from WooCommerce"** - Syncs all products with enhanced features
- **"Sync Updated from WooCommerce"** - Syncs only updated products

### 3. Monitor Sync Progress

The system provides detailed progress information:
- Total products processed
- Products created
- Products updated
- Products skipped
- Real-time progress updates

## Benefits

### 1. Comprehensive Data Sync
- All meta data fields are processed
- Multiple price groups are created automatically
- Advanced category management
- Complete variation support

### 2. Dynamic Pricing
- Automatic price group creation
- Support for multiple customer tiers
- Flexible pricing structure
- Easy price management

### 3. Enhanced Product Management
- Better SKU management
- Barcode support
- Image handling
- Tax type mapping

### 4. Improved Performance
- Efficient data processing
- Optimized database operations
- Better error handling
- Comprehensive logging

## Database Tables Used

The enhanced sync uses the following database tables:
- `products` - Main product data
- `product_variations` - Product variation templates
- `variations` - Individual variations
- `variation_group_prices` - Dynamic price groups
- `variation_location_details` - Stock management
- `categories` - Category management
- `product_locations` - Location assignments

## Error Handling

The enhanced sync includes comprehensive error handling:
- Image download failures are logged but don't stop the sync
- Missing meta data is handled gracefully
- Database errors are caught and logged
- Individual product failures don't affect other products

## Monitoring

Monitor the sync process through:
- Application logs
- Sync progress messages
- Database records
- Error logs

The enhanced sync provides a robust, feature-rich solution for synchronizing WooCommerce products to your ERP system with advanced pricing and data management capabilities. 