# Performance Forecasting Module

## Overview

The Performance Forecasting module enables Brand Admins to predict campaign outcomes using AI-powered analytics. It analyzes historical performance data to generate forecasts with confidence intervals, ROI estimates, and actionable insights.

## Features

- **AI-Powered Predictions**: Uses statistical models and trend analysis to forecast future performance
- **Multiple Scenarios**: Compare conservative, balanced, and aggressive forecast strategies
- **Confidence Intervals**: 95% confidence bands for all predictions
- **ROI Estimation**: Predict return on investment based on historical data
- **Actionable Insights**: AI-generated recommendations for campaign optimization
- **Visual Analytics**: Interactive charts showing predicted vs actual performance
- **Export Functionality**: Download forecast data in JSON format

## Architecture

### Components

1. **Database Layer**
   - Migration: `2025_09_30_143029_create_performance_forecasts_table.php`
   - Model: [`PerformanceForecast`](../app/Models/PerformanceForecast.php)
   - Factory: [`PerformanceForecastFactory`](../database/factories/PerformanceForecastFactory.php)

2. **Service Layer**
   - Service: [`PerformanceForecastService`](../app/Services/PerformanceForecastService.php)
   - Job: [`ProcessPerformanceForecast`](../app/Jobs/ProcessPerformanceForecast.php)

3. **Controller Layer**
   - Controller: [`PerformanceForecastController`](../app/Http/Controllers/Brand/PerformanceForecastController.php)
   - Policy: [`PerformanceForecastPolicy`](../app/Policies/PerformanceForecastPolicy.php)

4. **View Layer**
   - Index: [`resources/views/brand/forecasts/index.blade.php`](../resources/views/brand/forecasts/index.blade.php)
   - Create: [`resources/views/brand/forecasts/create.blade.php`](../resources/views/brand/forecasts/create.blade.php)
   - Show: [`resources/views/brand/forecasts/show.blade.php`](../resources/views/brand/forecasts/show.blade.php)

## Usage

### Creating a Forecast

1. Navigate to **Brand Dashboard** → **Forecasts**
2. Click **Create New Forecast**
3. Configure forecast parameters:
   - **Historical Data Period**: Select start and end dates for analysis
   - **Forecast Period**: Choose how many days ahead to predict (7-90 days)
   - **Scenario**: Select forecast strategy (conservative/balanced/aggressive)
   - **Campaigns** (optional): Filter by specific campaigns
   - **Social Accounts** (optional): Filter by specific social accounts
4. Click **Generate Forecast**
5. Wait for processing (typically 1-2 minutes)

### Viewing Forecast Results

Once completed, the forecast displays:

- **KPI Cards**: Predicted ROI, reach, conversions, and engagement rate
- **Charts**: 
  - Predicted vs Historical Performance (with confidence intervals)
  - Engagement Forecast
  - Conversions Forecast
- **AI Insights**: Actionable recommendations for optimization
- **Detailed Metrics**: Complete breakdown with confidence intervals

### Exporting Forecasts

1. Open a completed forecast
2. Click **Export** button
3. Download JSON file containing all forecast data

## API Endpoints

### Web Routes

```php
// Forecast management
GET    /brand/forecasts              - List all forecasts
GET    /brand/forecasts/create       - Show create form
POST   /brand/forecasts              - Create new forecast
GET    /brand/forecasts/{forecast}   - View forecast details
DELETE /brand/forecasts/{forecast}   - Delete forecast

// Forecast data endpoints
GET    /brand/forecasts/{forecast}/data       - Get forecast data (JSON)
GET    /brand/forecasts/{forecast}/status     - Get forecast status
GET    /brand/forecasts/{forecast}/comparison - Get historical vs predicted
GET    /brand/forecasts/{forecast}/export     - Export forecast data

// Scenario comparison
POST   /brand/forecasts/compare-scenarios     - Compare multiple scenarios
```

### Request Examples

#### Create Forecast

```bash
POST /brand/forecasts
Content-Type: application/json

{
  "start_date": "2025-08-01",
  "end_date": "2025-09-30",
  "forecast_days": 30,
  "scenario": "balanced",
  "campaign_ids": [1, 2],
  "social_account_ids": [5, 6]
}
```

#### Get Forecast Data

```bash
GET /brand/forecasts/1/data
```

Response:
```json
{
  "status": "completed",
  "predicted_timeseries": {
    "dates": ["2025-10-01", "2025-10-02", ...],
    "impressions": [1000, 1100, ...],
    "clicks": [50, 55, ...],
    "conversions": [5, 6, ...],
    "engagement": [100, 110, ...],
    "reach": [800, 900, ...]
  },
  "error_bands": {
    "impressions": {
      "lower": [900, 1000, ...],
      "upper": [1100, 1200, ...]
    }
  },
  "roi_estimates": {
    "roi": 15.5,
    "reach": 50000,
    "conversions": 500,
    "engagement_rate": 3.2
  },
  "insights": {
    "text": "Expected ROI of 15.5% indicates strong campaign performance.",
    "actionable": [...]
  }
}
```

## Forecast Scenarios

### Conservative (95% growth rate)
- Lower volatility predictions
- More cautious estimates
- Best for risk-averse planning

### Balanced (105% growth rate)
- Moderate growth assumptions
- Realistic predictions
- Recommended for most use cases

### Aggressive (115% growth rate)
- Higher growth expectations
- Optimistic projections
- Best for expansion planning

## Algorithm Details

### Data Collection

The system gathers historical metrics from:
- Social posts within the specified date range
- Campaign-specific data (if filtered)
- Social account performance (if filtered)

Metrics collected:
- Impressions (views)
- Clicks
- Conversions
- Engagement (likes + comments + shares)
- Reach

### Trend Analysis

Uses linear regression to calculate trends:
```
slope = (n * Σ(xy) - Σx * Σy) / (n * Σ(x²) - (Σx)²)
```

### Prediction Generation

For each forecast day:
```
predicted_value = last_value + (trend * day * growth_multiplier)
```

Where `growth_multiplier` depends on scenario:
- Conservative: 0.95
- Balanced: 1.05
- Aggressive: 1.15

### Confidence Intervals

95% confidence intervals calculated using:
```
error_margin = 1.96 * standard_deviation
lower_bound = predicted_value - error_margin
upper_bound = predicted_value + error_margin
```

### ROI Calculation

```
estimated_revenue = conversions * avg_conversion_value
roi = ((estimated_revenue - campaign_budget) / campaign_budget) * 100
```

## Security

### Authorization

- Only users with `brand_admin` role can access forecasts
- Brand admins can only view/manage forecasts for their own brand
- Policy checks enforce brand ownership on all operations

### Data Privacy

- Forecast data is encrypted at rest
- Campaign budgets are encrypted in database
- Access logs maintained for audit purposes

## Performance Optimization

### Batch Processing

- Forecasts are processed asynchronously via queue jobs
- Prevents blocking of user interface
- Allows for resource-intensive calculations

### Caching

- Forecast results are stored in database
- No need to recalculate on subsequent views
- Cache invalidation on data updates

### Rate Limiting

- Forecast creation is rate-limited per brand
- Prevents abuse and excessive resource usage

## Testing

Run the test suite:

```bash
php artisan test --filter PerformanceForecastTest
```

Test coverage includes:
- Authorization checks
- Forecast creation and validation
- Data retrieval and export
- Model relationships and scopes
- Policy enforcement
- Job processing

## Troubleshooting

### Forecast Stuck in Processing

**Symptom**: Forecast status remains "processing" for extended period

**Solution**:
1. Check queue worker is running: `php artisan queue:work`
2. Check logs: `storage/logs/laravel.log`
3. Restart queue worker if needed

### Insufficient Historical Data

**Symptom**: Forecast fails with "Insufficient historical data" error

**Solution**:
- Ensure at least 7 days of historical data exists
- Check that social accounts have synced data
- Verify campaigns have associated posts

### Inaccurate Predictions

**Symptom**: Forecast predictions seem unrealistic

**Solution**:
- Try different scenario (conservative vs aggressive)
- Ensure historical data is representative
- Check for data quality issues in social posts

## Future Enhancements

Planned improvements:
- Machine learning model integration
- Seasonal trend detection
- Multi-variate analysis
- Real-time forecast updates
- A/B test prediction
- Budget optimization recommendations
- Integration with external analytics platforms

## Support

For issues or questions:
- Check logs: `storage/logs/laravel.log`
- Review test cases: [`tests/Feature/PerformanceForecastTest.php`](../tests/Feature/PerformanceForecastTest.php)
- Contact development team

## Changelog

### Version 1.0.0 (2025-09-30)
- Initial release
- Basic forecasting functionality
- Three scenario types
- AI-generated insights
- Export functionality
- Comprehensive test coverage