# Financial Insights Module

## Overview

The Financial Insights module provides Brand Admins with comprehensive tools to track campaign ROI, budget usage, and revenue impact. It includes AI-powered analysis, budget scenario planning, and detailed financial reporting with data encryption and role-based access control.

## Features

### 1. Campaign Financial Tracking
- Track spend data (ad spend, influencer payments, production costs)
- Monitor performance metrics (clicks, conversions, revenue)
- Automatic calculation of ROI, cost-per-conversion, and other KPIs
- Period-based financial data aggregation

### 2. AI-Powered Analysis
- Automated ROI analysis and trend detection
- Actionable insights with priority levels
- Budget reallocation recommendations
- Channel performance optimization suggestions
- At least 2 actionable insights per report

### 3. Budget Scenario Planning
- Conservative, Balanced, and Aggressive scenarios
- Projected ROI and revenue calculations
- Risk assessment for each scenario
- Channel allocation recommendations
- Scenario comparison and application

### 4. Financial Reports
- Campaign-level reports
- Brand-level consolidated reports
- Spend vs revenue trend analysis
- Channel performance breakdown
- Export to PDF/Excel with watermarks

### 5. Security & Compliance
- Financial data encrypted at rest
- Role-based access control (Brand/Admin only)
- Comprehensive audit logging
- Data export tracking
- AI disclaimer on all reports

## Database Schema

### Tables

#### `campaign_financials`
Stores financial and performance data for campaigns.

**Key Fields:**
- `campaign_id`, `brand_id`
- Spend data: `ad_spend`, `influencer_payments`, `production_costs`, `other_costs`
- Performance: `clicks`, `impressions`, `conversions`, `avg_order_value`
- Calculated metrics: `roi_percentage`, `breakeven_days`, `cost_per_click`
- Period tracking: `period_start`, `period_end`

#### `financial_reports`
Stores generated financial reports with AI analysis.

**Key Fields:**
- `report_type`: 'campaign' or 'brand_consolidated'
- Aggregated metrics: `total_spend`, `total_revenue`, `net_profit`, `roi_percentage`
- AI analysis: `recommendations_text`, `actionable_insights`, `trend_analysis`
- Status tracking: `ai_status`, `ai_processed_at`

#### `budget_scenarios`
Stores budget allocation scenarios with projections.

**Key Fields:**
- `scenario_type`: 'conservative', 'balanced', 'aggressive'
- Budget allocation: `total_budget`, `channel_allocation`, `campaign_allocation`
- Projections: `projected_revenue`, `projected_roi`, `projected_conversions`
- AI recommendations: `ai_recommendations`, `risk_assessment`
- Status: `is_applied`, `applied_at`

#### `financial_audit_logs`
Tracks all access and modifications to financial data.

**Key Fields:**
- `auditable_type`, `auditable_id` (polymorphic)
- `action`: 'created', 'updated', 'deleted', 'viewed', 'exported', 'scenario_applied'
- Change tracking: `old_values`, `new_values`
- Request metadata: `ip_address`, `user_agent`

## API Endpoints

### Dashboard
```
GET /brand/financial-insights
```
Returns complete dashboard data including overview, trends, insights, and scenarios.

**Query Parameters:**
- `start_date` (optional): Period start date
- `end_date` (optional): Period end date

**Response:**
```json
{
  "overview": {
    "total_spend": 50000.00,
    "total_revenue": 75000.00,
    "net_profit": 25000.00,
    "roi_percentage": 50.00,
    "roi_status": "excellent"
  },
  "insights": [...],
  "scenarios": [...],
  "trends": {...}
}
```

### Update Campaign Financials
```
POST /brand/financial-insights/campaigns/{campaign}/financials
```

**Request Body:**
```json
{
  "spend_data": {
    "ad_spend": 5000,
    "influencer_payments": 3000,
    "production_costs": 1000,
    "other_costs": 500
  },
  "performance_data": {
    "clicks": 10000,
    "impressions": 50000,
    "conversions": 200,
    "avg_order_value": 75
  },
  "period_start": "2024-01-01",
  "period_end": "2024-01-31"
}
```

### Generate Reports
```
POST /brand/financial-insights/campaigns/{campaign}/report
POST /brand/financial-insights/brand/report
```

**Request Body:**
```json
{
  "period_start": "2024-01-01",
  "period_end": "2024-01-31",
  "run_ai_analysis": true
}
```

### Budget Scenarios
```
POST /brand/financial-insights/reports/{report}/scenarios
GET /brand/financial-insights/scenarios
POST /brand/financial-insights/scenarios/{scenario}/apply
```

### Export Reports
```
GET /brand/financial-insights/reports/{report}/export/pdf
GET /brand/financial-insights/reports/{report}/export/excel
```

### Chart Data
```
GET /brand/financial-insights/roi-trends
GET /brand/financial-insights/spend-vs-revenue
GET /brand/financial-insights/channel-performance
```

## Usage Examples

### 1. Update Campaign Financial Data

```php
use App\Services\FinancialInsightsService;

$service = app(FinancialInsightsService::class);

$financial = $service->updateCampaignFinancials(
    $campaign,
    [
        'ad_spend' => 5000,
        'influencer_payments' => 3000,
        'production_costs' => 1000,
        'other_costs' => 500,
    ],
    [
        'clicks' => 10000,
        'impressions' => 50000,
        'conversions' => 200,
        'avg_order_value' => 75,
    ],
    Carbon::parse('2024-01-01'),
    Carbon::parse('2024-01-31')
);
```

### 2. Generate Financial Report with AI Analysis

```php
$report = $service->generateCampaignReport(
    $campaign,
    Carbon::parse('2024-01-01'),
    Carbon::parse('2024-01-31'),
    runAIAnalysis: true
);

// Access AI insights
$insights = $report->actionable_insights;
$recommendations = $report->recommendations_text;
```

### 3. Generate Budget Scenarios

```php
$scenarios = $service->generateScenarios($report, totalBudget: 50000);

// Returns array with 3 scenarios:
// - conservative: Low risk, stable returns
// - balanced: Moderate risk, good growth
// - aggressive: High risk, maximum growth
```

### 4. Apply Budget Scenario

```php
$success = $service->applyScenario($scenario);

// Automatically deactivates other scenarios
// Logs the action in audit trail
```

### 5. Get Dashboard Data

```php
$dashboardData = $service->getDashboardData(
    $brand,
    Carbon::now()->subDays(30),
    Carbon::now()
);

// Returns complete dashboard with:
// - Overview metrics
// - Financial report
// - Campaign reports
// - Budget scenarios
// - Trends
// - Top campaigns
// - AI insights
```

## AI Analysis

### How It Works

1. **Data Collection**: Aggregates financial data from specified period
2. **AI Processing**: Sends data to OpenAI GPT-4 for analysis
3. **Insight Extraction**: Parses AI response into actionable insights
4. **Recommendation Generation**: Creates specific, measurable recommendations
5. **Trend Analysis**: Calculates performance trends and projections

### Insight Types

- **Opportunity**: High-potential actions (e.g., scale high-performing channels)
- **Warning**: Issues requiring attention (e.g., low conversion rates)
- **Recommendation**: General optimization suggestions

### Priority Levels

- **High**: Immediate action recommended, significant impact potential
- **Medium**: Important but not urgent, moderate impact
- **Low**: Nice-to-have optimizations, minor impact

### Example Insights

```json
{
  "type": "opportunity",
  "priority": "high",
  "title": "Scale High-Performing Channel",
  "description": "Shift 10-15% more budget to Instagram for potential +12% ROI improvement",
  "expected_impact": "+12% ROI",
  "action": "increase_budget",
  "channel": "instagram"
}
```

## Budget Scenarios

### Conservative Scenario
- **Risk Level**: Low
- **Target ROI**: 15%
- **Allocation**: Focus on proven channels (Instagram 40%, Facebook 30%, Google Ads 20%)
- **Best For**: Risk-averse brands, stable growth

### Balanced Scenario
- **Risk Level**: Medium
- **Target ROI**: 25%
- **Allocation**: Mix of proven and growth channels (Instagram 35%, TikTok 25%, YouTube 20%)
- **Best For**: Most brands, sustainable growth

### Aggressive Scenario
- **Risk Level**: High
- **Target ROI**: 40%
- **Allocation**: Focus on high-growth channels (TikTok 40%, Instagram Reels 30%, YouTube Shorts 20%)
- **Best For**: Growth-focused brands, willing to take risks

## Security Features

### Data Encryption
- All financial data encrypted at rest using Laravel's encryption
- Sensitive fields automatically encrypted in database
- Secure transmission over HTTPS

### Access Control
- Role-based permissions (Brand/Admin only)
- Policy-based authorization for all operations
- Campaign ownership verification

### Audit Logging
- All financial data access logged
- Change tracking with old/new values
- Export tracking with format and filename
- IP address and user agent recording

### Data Export Security
- PDF exports include watermark
- Excel exports include disclaimer sheet
- Export count and timestamp tracking
- Audit log entry for each export

## Performance Considerations

### Optimization Tips

1. **Use Eager Loading**
```php
$report = FinancialReport::with(['campaign', 'budgetScenarios'])->find($id);
```

2. **Cache Dashboard Data**
```php
Cache::remember("dashboard.{$brandId}", 3600, function() use ($brand) {
    return $service->getDashboardData($brand);
});
```

3. **Batch Financial Updates**
```php
// Update multiple campaigns at once
foreach ($campaigns as $campaign) {
    $service->updateCampaignFinancials(...);
}
```

4. **Async AI Processing**
```php
// Queue AI analysis for large reports
dispatch(new ProcessFinancialReport($report));
```

## Testing

### Run Tests
```bash
php artisan test --filter FinancialInsightsTest
```

### Test Coverage

- ✅ Dashboard access and authorization
- ✅ Financial data updates and calculations
- ✅ Report generation (campaign and brand-level)
- ✅ Budget scenario creation and application
- ✅ Period comparison
- ✅ Export functionality
- ✅ Chart data endpoints
- ✅ Audit logging
- ✅ ROI calculations
- ✅ Policy enforcement

### Factory Usage

```php
// Create profitable campaign
$financial = CampaignFinancial::factory()->profitable()->create();

// Create breakeven campaign
$financial = CampaignFinancial::factory()->breakeven()->create();

// Create unprofitable campaign
$financial = CampaignFinancial::factory()->unprofitable()->create();
```

## Troubleshooting

### AI Analysis Fails

**Problem**: Report shows `ai_status: 'failed'`

**Solutions:**
1. Check OpenAI API key in `.env`
2. Verify API quota and billing
3. Check `ai_error` field for details
4. Fallback to rule-based analysis automatically applied

### Metrics Not Calculating

**Problem**: ROI or other metrics show as null

**Solutions:**
1. Ensure all required fields have values
2. Check for division by zero (e.g., zero clicks)
3. Verify period dates are valid
4. Review model's `calculateMetrics()` method

### Export Not Working

**Problem**: PDF/Excel export fails

**Solutions:**
1. Check DomPDF installation: `composer require barryvdh/laravel-dompdf`
2. Check Excel package: `composer require maatwebsite/excel`
3. Verify storage permissions
4. Check export view exists

## Best Practices

### 1. Regular Data Updates
- Update financial data weekly or bi-weekly
- Run AI analysis monthly for insights
- Generate consolidated reports quarterly

### 2. Budget Scenario Planning
- Review scenarios before major campaigns
- Test different allocations
- Apply scenarios gradually

### 3. Monitoring
- Track ROI trends weekly
- Monitor channel performance
- Review AI insights regularly

### 4. Data Quality
- Validate input data before submission
- Reconcile with actual spend regularly
- Audit financial records monthly

## Disclaimer

**Important**: All AI-generated insights and projections are estimates based on historical data. Actual results may vary significantly. This information is not financial advice. Brands should consult with financial professionals before making significant budget allocation decisions.

## Support

For issues or questions:
- Check logs: `storage/logs/laravel.log`
- Review audit logs: `financial_audit_logs` table
- Contact development team

## Changelog

### Version 1.0.0 (2024-01-30)
- Initial release
- Campaign financial tracking
- AI-powered analysis
- Budget scenario planning
- Financial reports with export
- Comprehensive security features
- Full test coverage