# Multilingual / Localization Module

## Overview

The Localization module enables Brand Admins to translate and adapt campaign content (ads, posts, proposals) for different markets and languages. It uses AI-powered translation with cultural adaptation notes and includes caching to optimize costs.

## Features

- **AI-Powered Translation**: Automatic translation using OpenAI GPT models
- **Cultural Adaptation**: AI provides cultural notes for each translation
- **Multiple Locales**: Support for 25+ languages and regional variants
- **Tone Control**: Choose between formal, friendly, or neutral tones
- **Translation Cache**: Automatic caching to avoid duplicate API calls
- **Approval Workflow**: Review and approve translations before use
- **Manual Editing**: Edit AI translations for perfect accuracy
- **Audit Trail**: Complete history of all localization actions
- **Export Functionality**: Export translations in JSON format
- **Role-Based Access**: Only brand_admin and approved agencies can localize

## Architecture

### Database Schema

#### `localized_contents` Table
Stores all localized content with approval status and metadata.

**Key Fields:**
- `brand_id`: Brand owning the content
- `content_type`: Type of content (ad, post, proposal, campaign)
- `content_id`: ID of the original content
- `locale_code`: Target language (e.g., 'es-ES', 'fr-FR')
- `source_text`: Original text
- `localized_text`: Translated text
- `cultural_notes`: AI-generated cultural adaptation notes
- `tone`: Translation tone (formal, friendly, neutral)
- `status`: pending, generated, approved, rejected, edited
- `ai_job_id`: Reference to AI translation job

#### `localization_cache` Table
Caches translations to reduce API costs.

**Key Fields:**
- `source_text_hash`: Hash for quick lookup
- `source_locale`: Source language
- `target_locale`: Target language
- `tone`: Translation tone
- `translated_text`: Cached translation
- `usage_count`: Number of times used

#### `localization_audit_logs` Table
Complete audit trail of all actions.

**Key Fields:**
- `localized_content_id`: Reference to localized content
- `user_id`: User who performed action
- `action`: created, approved, rejected, edited, exported, attached
- `old_value`: Previous value (for edits)
- `new_value`: New value (for edits)

## Usage

### 1. Request Translation

**Via UI:**
1. Navigate to Brand Dashboard → Localization
2. Click "Request Translation"
3. Fill in the form:
   - Content Type (ad, post, proposal, campaign)
   - Content ID
   - Source Text
   - Target Languages (select multiple)
   - Tone (formal, friendly, neutral)
   - Optional: Additional Context
4. Submit request

**Via API:**
```php
POST /brand/localization
Content-Type: application/json

{
    "brand_id": 1,
    "content_type": "post",
    "content_id": 123,
    "source_text": "Check out our new product!",
    "target_locales": ["es-ES", "fr-FR", "de-DE"],
    "tone": "friendly",
    "context": "Social media post for product launch"
}
```

**Response:**
```json
{
    "success": true,
    "message": "Localization request processed successfully",
    "data": [
        {
            "locale": "es-ES",
            "status": "generated",
            "localized_content": {
                "id": 1,
                "locale_code": "es-ES",
                "localized_text": "¡Echa un vistazo a nuestro nuevo producto!",
                "cultural_notes": "Spanish translation uses informal 'tú' form...",
                "status": "generated"
            }
        }
    ]
}
```

### 2. Review Translations

The localization panel shows side-by-side comparison:
- **Original**: Source text
- **Localized**: Translated text
- **Notes**: Cultural adaptation notes

### 3. Approve Translation

**Via UI:**
Click "Approve" button on the translation card

**Via API:**
```php
POST /brand/localization/{id}/approve
```

### 4. Edit Translation

**Via UI:**
Click "Edit" button to manually adjust the translation

**Via API:**
```php
PUT /brand/localization/{id}
Content-Type: application/json

{
    "localized_text": "Updated translation text",
    "notes": "Manual correction for better accuracy"
}
```

### 5. Export Translation

**Via UI:**
Click "Export" button to download as JSON

**Via API:**
```php
GET /brand/localization/{id}/export
```

**Response:**
```json
{
    "success": true,
    "data": {
        "locale_code": "es-ES",
        "locale_name": "Spanish (Spain)",
        "source_text": "Check out our new product!",
        "localized_text": "¡Echa un vistazo a nuestro nuevo producto!",
        "cultural_notes": "Spanish translation uses informal 'tú' form...",
        "tone": "friendly",
        "status": "approved",
        "created_at": "2025-09-30T14:55:00Z",
        "approved_at": "2025-09-30T15:00:00Z"
    }
}
```

## Supported Languages

The module supports 25+ languages including:

- **English**: en, en-US, en-GB
- **Spanish**: es, es-ES, es-MX
- **French**: fr, fr-FR
- **German**: de, de-DE
- **Italian**: it, it-IT
- **Portuguese**: pt, pt-BR, pt-PT
- **Japanese**: ja, ja-JP
- **Chinese**: zh, zh-CN, zh-TW
- **Korean**: ko, ko-KR
- **Arabic**: ar, ar-SA
- **Hindi**: hi, hi-IN

## Translation Tones

### Formal
- Professional terminology
- Respectful address forms
- Suitable for: Corporate communications, legal content, official announcements

### Friendly
- Casual, warm language
- Conversational style
- Suitable for: Social media, marketing campaigns, community engagement

### Neutral
- Balanced language
- Neither too formal nor too casual
- Suitable for: General content, product descriptions, informational posts

## Caching System

The module automatically caches translations to reduce API costs:

1. **Cache Lookup**: Before calling AI API, checks if identical translation exists
2. **Cache Hit**: Returns cached translation, increments usage count
3. **Cache Miss**: Calls AI API, stores result in cache
4. **Cache Key**: Hash of (source_text + source_locale + target_locale + tone)

**Benefits:**
- Reduces API costs for repeated translations
- Faster response times
- Tracks popular translations via usage_count

## Security & Access Control

### Role-Based Access

**Brand Admin:**
- Full access to their brand's localizations
- Can request, approve, edit, and delete translations

**Agency (Approved):**
- Can request and edit translations for assigned brands
- Can approve if granted approval permissions
- Cannot delete translations

**Other Roles:**
- No access to localization features

### Policy Implementation

```php
// LocalizedContentPolicy.php

public function view(User $user, LocalizedContent $localization): bool
{
    // Brand admin can view their own brand's content
    if ($user->role === 'brand_admin') {
        return $user->brand_id === $localization->brand_id;
    }
    
    // Agency can view if they have access to the brand
    if ($user->role === 'agency') {
        return $this->hasAgencyAccess($user, $localization->brand_id);
    }
    
    return false;
}
```

## Audit Trail

All actions are logged in `localization_audit_logs`:

**Logged Actions:**
- `created`: Localization request created
- `approved`: Translation approved
- `rejected`: Translation rejected
- `edited`: Manual edit performed
- `exported`: Translation exported
- `attached`: Translation attached to scheduled post

**Audit Log Entry:**
```php
[
    'localized_content_id' => 1,
    'user_id' => 5,
    'action' => 'approved',
    'old_value' => 'generated',
    'new_value' => 'approved',
    'notes' => 'Localization approved by John Doe',
    'ip_address' => '192.168.1.1',
    'user_agent' => 'Mozilla/5.0...',
    'created_at' => '2025-09-30T15:00:00Z'
]
```

## API Endpoints

### Localization Management

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/brand/localization` | List localizations |
| POST | `/brand/localization` | Request new translation |
| GET | `/brand/localization/{id}` | View specific localization |
| PUT | `/brand/localization/{id}` | Edit localization |
| DELETE | `/brand/localization/{id}` | Delete localization |

### Actions

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/brand/localization/{id}/approve` | Approve translation |
| POST | `/brand/localization/{id}/reject` | Reject translation |
| GET | `/brand/localization/{id}/export` | Export translation |

### Utilities

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/brand/localization/content/localizations` | Get all localizations for content |
| GET | `/brand/localization/stats/{brand}` | Get localization statistics |
| GET | `/brand/localization/supported-locales` | Get supported languages |
| GET | `/brand/localization/supported-tones` | Get supported tones |

## Configuration

### Environment Variables

Add to `.env`:

```env
# OpenAI Configuration
OPENAI_API_KEY=your_api_key_here
OPENAI_API_URL=https://api.openai.com/v1/chat/completions
OPENAI_MODEL=gpt-4
```

### Service Configuration

Add to `config/services.php`:

```php
'openai' => [
    'api_key' => env('OPENAI_API_KEY'),
    'api_url' => env('OPENAI_API_URL', 'https://api.openai.com/v1/chat/completions'),
    'model' => env('OPENAI_MODEL', 'gpt-4'),
],
```

## Testing

Run the localization tests:

```bash
php artisan test --filter LocalizationTest
```

**Test Coverage:**
- ✅ Brand admin can access localization index
- ✅ Brand admin can request localization
- ✅ Localization request validates required fields
- ✅ Brand admin can approve localization
- ✅ Brand admin can reject localization
- ✅ Brand admin can edit localization
- ✅ Brand admin can export localization
- ✅ Brand admin can view localization stats
- ✅ Localization uses cache for duplicate requests
- ✅ Unauthorized user cannot access localization
- ✅ Brand admin cannot access other brands' localizations
- ✅ Can get supported locales
- ✅ Can get supported tones
- ✅ Can delete localization

## Best Practices

### 1. Provide Context
Always provide context when requesting translations to improve accuracy:
```php
'context' => 'Social media post for product launch targeting millennials'
```

### 2. Review AI Translations
Always review AI-generated translations before approval, especially for:
- Legal content
- Brand-critical messaging
- Cultural-sensitive content

### 3. Use Appropriate Tone
Choose the right tone for your content:
- **Formal**: Legal documents, corporate communications
- **Friendly**: Social media, marketing campaigns
- **Neutral**: Product descriptions, general content

### 4. Leverage Caching
The system automatically caches translations. For frequently used phrases:
- Create a library of pre-approved translations
- Reuse common phrases across campaigns

### 5. Monitor Costs
Track AI API usage through:
- Localization statistics dashboard
- Cache hit rate monitoring
- Monthly usage reports

## Troubleshooting

### Translation Quality Issues

**Problem**: AI translation is not accurate
**Solution**: 
- Provide more context in the request
- Try a different tone setting
- Manually edit the translation
- Consider using a professional translator for critical content

### Cache Not Working

**Problem**: Same translation being generated multiple times
**Solution**:
- Verify source text is identical (including whitespace)
- Check tone setting matches
- Review cache table for entries

### Permission Denied

**Problem**: User cannot access localization features
**Solution**:
- Verify user has `brand_admin` or `agency` role
- Check brand_id matches
- For agencies, verify approval status in `brand_agency` table

## Future Enhancements

Planned features for future releases:

1. **Batch Translation**: Translate multiple content items at once
2. **Translation Memory**: Learn from approved translations
3. **Glossary Support**: Brand-specific terminology management
4. **Quality Scoring**: AI confidence scores for translations
5. **Professional Review**: Integration with human translation services
6. **Version Control**: Track translation versions over time
7. **A/B Testing**: Test different translations for effectiveness

## Support

For issues or questions:
- Check the troubleshooting section above
- Review audit logs for action history
- Contact development team with error details

## License

This module is part of the AI Business Market platform.
Copyright © 2025. All rights reserved.