# Language Preference System

## Overview

The Language Preference System automatically learns user language preferences based on their viewing behavior and enables targeted promotional content.

## Architecture

### Database Schema

#### Users Table Extensions
```sql
-- User language preference fields
preferred_language VARCHAR(5) DEFAULT 'en'      -- Primary language (en, in, es, pt, etc.)
language_confidence TINYINT DEFAULT 0           -- Confidence level (0-100)
language_stats JSON                             -- Language viewing statistics
language_updated_at TIMESTAMP                   -- Last preference update
```

#### Watch History Extensions
```sql
-- Language tracking in watch history
language VARCHAR(5) DEFAULT 'en'               -- Language of watched content
```

### Services

#### LanguagePreferenceService
- **Purpose**: Learn and manage user language preferences
- **Features**:
  - Automatic preference detection from viewing patterns
  - Confidence scoring (0-100%)
  - Email campaign targeting
  - Language analytics and insights

#### LanguageBasedEmailService
- **Purpose**: Send targeted promotional emails based on language preference
- **Features**:
  - Multi-language campaign support
  - User segmentation by language confidence
  - Drama recommendations by language
  - A/B testing capabilities

## How It Works

### 1. Language Learning
```php
// Every time a user watches an episode, language is tracked
WatchHistoryService::trackEpisodeView([
    'book_id' => '41000121386',
    'language' => 'in',  // Bahasa Indonesia
    // ... other data
]);

// Language preference is automatically updated
LanguagePreferenceService::updateLanguagePreference($userId, 'in');
```

### 2. Confidence Calculation
- **Dominance Factor**: Percentage of sessions in preferred language
- **Volume Factor**: Total number of viewing sessions
- **Minimum Threshold**: 3+ sessions required for learning
- **High Confidence**: 70%+ confidence for email targeting

### 3. Email Targeting
```php
// Get users for language-specific campaigns
$indonesianUsers = $languageService->getUsersByLanguage('in', 70); // 70% confidence
$emailService->sendLanguageTargetedPromotion('new_series', [
    'in' => $indonesianContent,
    'en' => $englishContent,
]);
```

## Usage Examples

### Check User Language Preference
```php
$user = Auth::user();
$preferredLang = $user->getPreferredLanguage(); // 'in', 'en', etc.
$hasStrongPreference = $user->hasStrongLanguagePreference(); // true/false
$emailLang = $user->getEmailLanguage(); // Language for email campaigns
```

### Get Language Analytics
```php
$service = new LanguagePreferenceService();
$insights = $service->getLanguageInsights();

// Results:
[
    'total_users_with_preference' => 1250,
    'high_confidence_users' => 890,
    'language_distribution' => [
        'in' => ['users' => 450, 'avg_confidence' => 85.2],
        'en' => ['users' => 320, 'avg_confidence' => 78.1],
        'es' => ['users' => 120, 'avg_confidence' => 72.5],
    ],
    'multilingual_users' => 45
]
```

### Artisan Commands
```bash
# Analyze current language preferences
php artisan drama:analyze-language-preferences

# Update all user preferences based on viewing history
php artisan drama:analyze-language-preferences --update

# Show email targeting opportunities
php artisan drama:analyze-language-preferences --min-sessions=5
```

## Email Campaign Integration

### Language-Based Segmentation
```php
$emailService = new LanguageBasedEmailService();

// Create segments for targeted campaigns
$segments = $emailService->createLanguageSegments([
    'min_confidence' => 70,
    'min_users_per_segment' => 25
]);

// Send multi-language promotional campaign
$results = $emailService->sendLanguageTargetedPromotion('holiday_sale', [
    'in' => [
        'subject' => 'Promo Spesial Drama Cina!',
        'content' => '...',
        'dramas' => $indonesianPopularDramas
    ],
    'en' => [
        'subject' => 'Special Chinese Drama Promotion!',
        'content' => '...',
        'dramas' => $englishPopularDramas
    ]
]);
```

### Personalized Recommendations
```php
// Get drama recommendations based on user's language preference
$recommendations = $emailService->getDramaRecommendationsForUser($userId);

// Results include:
[
    'primary_language' => 'in',
    'confidence' => 85,
    'suggested_dramas' => [...], // Indonesian language dramas
    'fallback_dramas' => [...], // English fallback dramas
]
```

## Business Benefits

### 1. **Improved Email Open Rates**
- Send promotional emails in user's preferred language
- Higher engagement and conversion rates
- Reduced unsubscribe rates

### 2. **Better Content Curation**
- Recommend dramas in preferred language
- Personalized homepage experience
- Improved user retention

### 3. **Marketing Analytics**
- Understand audience language distribution
- Plan content acquisition by language demand
- Optimize advertising spend by language segments

### 4. **Automated Localization**
- No manual language selection required
- Seamless user experience
- Scales automatically with user base growth

## Data Privacy & Performance

### Privacy Considerations
- Language preference is inferred from viewing behavior
- No explicit personal data collection
- Users can opt-out of personalized content

### Performance Optimizations
- Language preferences cached for 1 hour
- Batch processing for preference updates
- Efficient database indexes on language fields
- Analytics data cached for 30 minutes

## Configuration

Add to your `.env` file:
```env
# Language preference settings
LANGUAGE_LEARNING_MIN_SESSIONS=3
LANGUAGE_CONFIDENCE_THRESHOLD=70
LANGUAGE_PREFERENCE_CACHE_TTL=3600

# Email campaign settings  
EMAIL_LANGUAGE_TARGETING_ENABLED=true
EMAIL_MIN_CONFIDENCE_FOR_TARGETING=70
```

## Future Enhancements

1. **Real-time Language Detection**: Use drama metadata to detect content language
2. **Multi-language Support**: Support users with multiple strong language preferences
3. **Geographic Correlation**: Combine with IP geolocation for better accuracy
4. **A/B Testing**: Test different confidence thresholds for optimal targeting
5. **Machine Learning**: Use ML models for more sophisticated preference prediction