# Ad Manager Module Documentation

## Overview

The Ad Manager module enables Brand Admins to create, manage, and optimize advertising campaigns with AI-generated ad copy variants and comprehensive A/B testing capabilities.

## Features

### 1. AI-Powered Ad Copy Generation
- Generate 2-5 ad copy variants automatically using AI
- Multiple creative approaches (benefit-focused, emotional, urgency, social proof, problem-solution)
- Predicted performance metrics for each variant
- Customizable tone and style options

### 2. A/B Testing Dashboard
- Real-time performance metrics tracking
- Visual comparison of variant performance
- Interactive charts and graphs
- Winner identification and promotion

### 3. Variant Management
- Launch/pause individual or multiple variants
- Duplicate successful variants
- Promote winning variants
- Regenerate new variants on demand

### 4. Performance Analytics
- Click-through rate (CTR) tracking
- Conversion rate monitoring
- Cost per click (CPC) analysis
- Return on ad spend (ROAS) calculation
- Platform-specific metrics

### 5. Export Capabilities
- CSV export of A/B test results
- Comprehensive performance data
- Historical metrics tracking

## Database Schema

### Tables

#### `ads`
- `id`: Primary key
- `campaign_id`: Foreign key to campaigns table
- `brand_id`: Foreign key to brands table
- `name`: Ad name
- `product_info`: Product/service description
- `audience`: Target audience description
- `tone`: Ad tone/style
- `budget`: Ad budget
- `currency`: Currency code (USD, EUR, etc.)
- `status`: Ad status (draft, active, paused, completed)
- `timestamps`: created_at, updated_at, deleted_at

#### `ad_variants`
- `id`: Primary key
- `ad_id`: Foreign key to ads table
- `headline`: Ad headline (max 60 chars)
- `body`: Ad body copy (max 150 chars)
- `cta`: Call-to-action text
- `predicted_metrics`: JSON field with AI predictions
- `is_active`: Boolean flag
- `is_winner`: Boolean flag
- `timestamps`: created_at, updated_at

#### `ad_performance_metrics`
- `id`: Primary key
- `ad_variant_id`: Foreign key to ad_variants table
- `platform`: Platform name (facebook, instagram, etc.)
- `impressions`: Number of impressions
- `clicks`: Number of clicks
- `conversions`: Number of conversions
- `spend`: Amount spent
- `ctr`: Click-through rate
- `conversion_rate`: Conversion rate
- `cpc`: Cost per click
- `cpm`: Cost per thousand impressions
- `roas`: Return on ad spend
- `last_synced_at`: Last sync timestamp
- `timestamps`: created_at, updated_at

## API Endpoints

### Web Routes (Brand Admin)

```php
GET    /brand/ads                          // List all ads
GET    /brand/ads/create                   // Show create form
POST   /brand/ads                          // Store new ad
GET    /brand/ads/{ad}                     // Show ad details
GET    /brand/ads/{ad}/edit                // Show edit form
PUT    /brand/ads/{ad}                     // Update ad
DELETE /brand/ads/{ad}                     // Delete ad

// A/B Testing
GET    /brand/ads/{ad}/ab-test             // A/B test dashboard
POST   /brand/ads/{ad}/launch-variants     // Launch variants
POST   /brand/ads/{ad}/pause-variants      // Pause variants
POST   /brand/ads/{ad}/regenerate-variants // Regenerate variants

// Variant Management
POST   /brand/ads/variants/{variant}/duplicate  // Duplicate variant
POST   /brand/ads/variants/{variant}/promote    // Promote as winner

// Export & Metrics
GET    /brand/ads/{ad}/export              // Export results (CSV)
GET    /brand/ads/{ad}/metrics             // Get real-time metrics (JSON)
```

## Usage Guide

### Creating a New Ad

1. Navigate to Ad Manager
2. Click "Create New Ad"
3. Fill in required information:
   - Select campaign
   - Enter ad name
   - Describe product/service
   - Define target audience
   - Choose tone/style
   - Set budget (optional)
   - Select number of variants (2-5)
4. Click "Generate Ad Variants"
5. AI generates multiple variants with different approaches

### Managing Variants

1. View generated variants on ad details page
2. Review predicted performance metrics
3. Select variants to launch
4. Click "Launch Selected" to activate
5. Monitor performance in real-time

### A/B Testing

1. Navigate to A/B Test Dashboard
2. View comparative performance metrics
3. Analyze charts and graphs
4. Identify best-performing variant
5. Promote winner when ready

### Exporting Results

1. Go to A/B Test Dashboard
2. Click "Export Results"
3. Download CSV file with complete metrics

## AI Service Configuration

### OpenAI Integration

Add to `.env`:
```env
OPENAI_API_KEY=your_api_key_here
```

Add to `config/services.php`:
```php
'openai' => [
    'api_key' => env('OPENAI_API_KEY'),
],
```

### Fallback Mechanism

If AI service is unavailable, the system automatically falls back to template-based generation to ensure continuity.

## Security Features

### Authorization
- Policy-based access control
- Brand-level data isolation
- Role-based permissions (brand_admin, superadmin)

### Validation
- Form Request validation classes
- Input sanitization
- CSRF protection
- SQL injection prevention

### Data Protection
- Encrypted sensitive tokens
- Secure API key storage
- Audit logging

## Performance Optimization

### Caching Strategy
- Cache AI-generated variants
- Cache performance metrics (30-second intervals)
- Cache campaign data

### Database Optimization
- Indexed foreign keys
- Optimized queries with eager loading
- Soft deletes for data retention

### Real-time Updates
- JavaScript polling (30-second intervals)
- Efficient API endpoints
- Minimal data transfer

## Testing

### Running Migrations

```bash
php artisan migrate
```

### Seeding Test Data

```bash
php artisan db:seed --class=AdManagerSeeder
```

### Running Tests

```bash
php artisan test --filter=AdManager
```

## Troubleshooting

### Common Issues

**Issue**: AI variants not generating
- **Solution**: Check OpenAI API key configuration
- **Fallback**: System uses template-based generation

**Issue**: Metrics not updating
- **Solution**: Check JavaScript console for errors
- **Action**: Verify API endpoint accessibility

**Issue**: Unauthorized access
- **Solution**: Verify user has brand_admin role
- **Action**: Check brand association

## Future Enhancements

### Planned Features
1. Multi-platform ad deployment (Facebook, Google, Instagram)
2. Advanced AI models (GPT-4, Claude)
3. Automated budget optimization
4. Predictive analytics
5. Integration with ad platforms APIs
6. Automated winner promotion
7. Schedule-based variant rotation
8. Advanced audience segmentation

### API Integrations
- Facebook Ads API
- Google Ads API
- Instagram Ads API
- Twitter Ads API
- LinkedIn Ads API

## Support

For issues or questions:
- Check documentation
- Review error logs
- Contact development team

## Version History

### v1.0.0 (Current)
- Initial release
- AI-powered variant generation
- A/B testing dashboard
- Performance metrics tracking
- Export functionality
- Real-time updates

## License

Proprietary - All rights reserved