# Yii2 Magento Integration Module

## Overview
A comprehensive Yii2 module that integrates with Magento e-commerce platform via REST API, providing automatic product synchronization with token-based authentication.

## Module Structure
```
PortalPeople/magento/
├── Module.php                          # Main module class with configuration
├── components/
│   ├── MagentoClient.php              # API client with dual authentication
│   └── ProductSyncComponent.php       # Product synchronization logic
├── controllers/
│   └── ConfigController.php           # Web configuration interface
├── models/
│   ├── ConfigForm.php                 # Configuration form model
│   └── ProductEventHandler.php        # Event handling for automatic sync
└── views/
    └── config/
        └── index.php                  # Configuration management UI
```

## Features

### Authentication
- **Token Authentication** (Recommended): Uses Magento API access tokens
- **Credential Authentication** (Fallback): Username/password with automatic token generation
- Secure credential storage in configuration files

### Configuration Management
- Web-based configuration interface
- Real-time connection testing
- Form validation and error handling
- Configuration persistence to `backend/config/params-local.php`

### Product Synchronization
- Automatic sync when price fields are updated (price1, price2, price3)
- Configurable field mapping between local database and Magento
- Queue support for async processing
- Debug logging capabilities

### Event System
- Yii2 ActiveRecord event integration
- Automatic triggers on model updates
- Configurable price field monitoring

## Configuration

### File Location
Configuration is stored in: `backend/config/params-local.php`

### Configuration Structure
```php
'plugins' => [
    'magento' => [
        'enabled' => 1,
        'apiUrl' => 'https://your-magento-store.com',
        'authMethod' => 'token',
        'accessToken' => 'your-api-token',
        'storeCode' => 'default',
        'autoSync' => true,
        'debug' => false,
        'useQueue' => true,
        'timeout' => 30,
        'priceFields' => ['price1', 'price2', 'price3'],
        'fieldMapping' => [
            'sku' => 'sku',
            'name' => 'name',
            'price1' => 'price',
            'price2' => 'special_price'
        ]
    ]
]
```

## Usage

### Web Configuration
Access the configuration interface at: `/magento/config`

### Manual Testing
```php
// Test connection
$client = new MagentoClient();
$result = $client->testConnection();

// Sync product
$sync = new ProductSyncComponent();
$success = $sync->syncProduct($productSku, $priceData);
```

### Event-Driven Sync
The module automatically synchronizes products when price fields are updated:
```php
// This will trigger automatic Magento sync
$product = Product::findOne(['sku' => 'PROD-123']);
$product->price1 = 99.99;
$product->save(); // Automatically syncs to Magento
```

## API Endpoints

### Configuration Controller
- `GET /magento/config` - Configuration form
- `POST /magento/config/save` - Save configuration
- `POST /magento/config/test` - Test API connection
- `POST /magento/config/reset` - Reset to defaults

## Security Features
- HTTPS enforcement for API communications
- Secure token storage
- Input validation and sanitization
- Error handling with logging

## Requirements
- Yii2 Framework 2.0+
- PHP 7.4+
- Magento 2.x with REST API enabled
- Valid Magento API credentials or access token

## Installation Status
✅ Module structure created
✅ Authentication system implemented
✅ Web configuration interface
✅ Event handlers configured
✅ Configuration persistence fixed
✅ Namespace corrections applied
✅ Path aliases corrected

## Troubleshooting

### Configuration Not Saving
- Ensure `backend/config/params-local.php` is writable
- Check file permissions (should be 644 or 664)
- Verify the `@backend` alias is properly configured

### API Connection Issues
- Verify Magento API is enabled
- Check access token validity
- Ensure HTTPS is used for secure communication
- Test with curl or Postman first

### Sync Not Working
- Check if `autoSync` is enabled in configuration
- Verify price field names match configuration
- Check debug logs for error messages
- Ensure queue is processing if `useQueue` is enabled

## Next Steps
1. Test web configuration interface in browser
2. Verify automatic product synchronization
3. Set up console commands for bulk operations
4. Configure queue processing for production use

## Support
For issues and support, check:
- Application logs in `runtime/logs/`
- Debug output when enabled
- Magento API documentation
- Yii2 framework documentation

## Features

- **Automatic Price Sync**: Monitors configured price fields (price1, price2, price3) and updates Magento when they change
- **Real-time Events**: Uses Yii2 events to trigger immediate synchronization
- **Queue Support**: Optional asynchronous processing via Yii2 queue
- **Web Configuration**: Full web-based configuration interface
- **Connection Testing**: Built-in API connection testing
- **Field Mapping**: Configurable mapping between local and Magento fields
- **Debug Logging**: Comprehensive logging for troubleshooting

## Installation

1. **Copy Module Files**
   ```bash
   # Module files should be in: PortalPeople/magento/
   ```

2. **Configure Application**
   Add the module to your backend configuration (`backend/config/main.php`):
   ```php
   'modules' => [
       'magento' => [
           'class' => 'app\PortalPeople\magento\Module',
       ],
   ],
   ```

3. **Set Up Configuration**
   Navigate to `/magento/config` in your backend to configure the module via web interface.

## Configuration

### Web Interface
Access the configuration panel at: `/NGauge/magento/config`

### Manual Configuration
Add to your `params-local.php`:
```php
'magento' => [
    'apiUrl' => 'https://your-magento-site.com',
    'authMethod' => 'token',  // or 'credentials'
    'accessToken' => 'your-magento-api-access-token',  // if using token method
    // 'adminUsername' => 'your-admin-username',  // if using credentials method
    // 'adminPassword' => 'your-admin-password',  // if using credentials method
    'storeCode' => 'default',
    'autoSync' => true,
    'priceFields' => ['price1', 'price2', 'price3'],
    'useQueue' => true,
    'debug' => false,
    'timeout' => 30,
    'fieldMapping' => [
        'sku' => 'sku',
        'name' => 'name',
        'price1' => 'price',
        'price2' => 'special_price',
        'description' => 'description',
        'weight' => 'weight',
        'status' => 'status'
    ]
]
```

## How It Works

1. **Event Detection**: When a product is updated in your Yii2 application, the module detects changes to monitored fields
2. **Price Change Sync**: If `price1`, `price2`, or `price3` changes, the module immediately syncs to Magento
3. **Queue Processing**: If enabled, sync jobs are queued for asynchronous processing
4. **API Communication**: The module authenticates with Magento REST API and updates product data

## API Requirements

Your Magento installation must have:
- REST API enabled
- API Integration configured (recommended) OR Admin user with API permissions
- HTTPS recommended for security

### Getting API Access Token (Recommended Method)

1. **Login to Magento Admin**
2. **Navigate to System → Extensions → Integrations**
3. **Click "Add New Integration"**
4. **Fill in Integration Details:**
   - Name: "Yii2 Sync Integration"
   - Email: Your email
   - Endpoint URL: (leave blank)
   - Identity link URL: (leave blank)
5. **Go to API Tab and Select Resources:**
   - Select "Catalog" for product management
   - Select "Sales" if syncing orders
6. **Save and Activate Integration**
7. **Copy the Access Token** from the integration details

### Alternative: Username/Password Method

If you prefer using admin credentials:
- Ensure admin user has API role permissions
- Enable API access for the user account

## Usage Examples

### Test Connection
```php
$syncComponent = Yii::$app->magentoSync;
if ($syncComponent->testConnection()) {
    echo "Connected to Magento!";
}
```

### Manual Sync
```php
$product = Product::findOne(['sku' => 'PROD123']);
Yii::$app->magentoSync->syncProduct($product, 'update');
```

### Bulk Sync
```php
$products = Product::find()->where(['updated_at' => date('Y-m-d')])->all();
$results = Yii::$app->magentoSync->bulkSync($products);
```

## File Structure

```
PortalPeople/magento/
├── Module.php                      # Main module class
├── components/
│   ├── MagentoClient.php          # REST API client
│   └── ProductSyncComponent.php   # Sync logic
├── controllers/
│   └── ConfigController.php       # Web configuration
├── models/
│   └── ConfigForm.php             # Configuration form model
├── views/
│   └── config/
│       └── index.php              # Configuration interface
├── handlers/
│   └── ProductEventHandler.php    # Event handlers
└── jobs/
    └── ProductSyncJob.php         # Queue job
```

## Configuration Options

| Option | Description | Default |
|--------|-------------|---------|
| `apiUrl` | Magento base URL | Required |
| `authMethod` | Authentication method (token/credentials) | 'token' |
| `accessToken` | Magento API access token | Required for token method |
| `adminUsername` | Magento admin username | Required for credentials method |
| `adminPassword` | Magento admin password | Required for credentials method |
| `storeCode` | Magento store view code | 'default' |
| `autoSync` | Enable automatic sync | true |
| `priceFields` | Fields to monitor for changes | ['price1', 'price2', 'price3'] |
| `useQueue` | Use queue for async processing | true |
| `debug` | Enable debug logging | false |
| `timeout` | API request timeout (seconds) | 30 |

## Troubleshooting

### Connection Issues
1. Verify Magento URL is accessible
2. Check admin user has API permissions
3. Test with debug mode enabled
4. Check SSL certificate for HTTPS URLs

### Sync Issues
1. Enable debug logging
2. Check Magento logs for API errors
3. Verify field mapping configuration
4. Test with manual sync first

### Performance
- Enable queue processing for high-volume updates
- Adjust timeout settings for slow connections
- Monitor sync logs for bottlenecks

## Support

For issues and questions:
- Check debug logs in Yii2 log files
- Review Magento API documentation
- Test connection via configuration panel

## License

Copyright (c) 2025 Portal People (https://portalpeople.co.uk)