# Competitor Insights Module

## Overview

The Competitor Insights module allows Brand Admins to monitor competitor brands' social media performance, analyze their strategies, and receive AI-powered recommendations for improving their own social media presence.

## Features

### 1. Competitor Management
- Add competitor brands with their social media handles
- Track multiple competitors across different platforms (Instagram, Facebook, Twitter, TikTok, LinkedIn)
- Enable/disable competitor tracking
- Update competitor information

### 2. Data Collection
- Automated data fetching from competitor social accounts (respects platform rules - public data only)
- Scheduled sync every 6 hours via cron job
- Manual sync option available
- Stores posts, engagement metrics, and performance data

### 3. Performance Analysis
- Comparative metrics dashboard (competitor vs your brand)
- Engagement rate analysis
- Posting frequency tracking
- Content strategy insights
- Sentiment analysis
- Topic and hashtag performance

### 4. AI-Powered Insights
- Automated generation of actionable recommendations
- Executive summaries of competitor performance
- Content strategy suggestions
- Optimal posting time recommendations
- 2-3 prioritized recommendations per insight

### 5. Alert System
- Real-time alerts for performance spikes
- Viral post detection
- Posting frequency changes
- Engagement rate spikes
- Configurable severity levels (low, medium, high, critical)

## Database Schema

### Tables

#### `competitor_brands`
Stores competitor brand information and social handles.

#### `competitor_posts`
Stores individual posts from competitors with metrics and analysis.

#### `competitor_insights`
Stores generated insights and comparative analysis.

#### `competitor_alerts`
Stores alerts for significant competitor activities.

## API Endpoints

### Competitor Management

```
GET    /brand/competitor-insights                    - Dashboard
GET    /brand/competitor-insights/competitors        - List competitors
POST   /brand/competitor-insights/competitors        - Add competitor
PUT    /brand/competitor-insights/competitors/{id}   - Update competitor
DELETE /brand/competitor-insights/competitors/{id}   - Delete competitor
```

### Insights

```
GET    /brand/competitor-insights/competitors/{id}         - View insights
GET    /brand/competitor-insights/competitors/{id}/data    - Get insights data (JSON)
POST   /brand/competitor-insights/competitors/{id}/sync    - Manual sync
GET    /brand/competitor-insights/competitors/{id}/export  - Export insights
GET    /brand/competitor-insights/compare                  - Compare multiple competitors
```

### Alerts

```
GET    /brand/competitor-insights/alerts              - List alerts
POST   /brand/competitor-insights/alerts/{id}/read    - Mark as read
POST   /brand/competitor-insights/alerts/{id}/dismiss - Dismiss alert
POST   /brand/competitor-insights/alerts/bulk-read    - Bulk mark as read
```

## Usage

### Adding a Competitor

```php
POST /brand/competitor-insights/competitors

{
    "name": "Competitor Brand Name",
    "description": "Optional description",
    "industry": "Technology",
    "social_handles": {
        "instagram": "@competitor_handle",
        "facebook": "competitor_page",
        "twitter": "@competitor"
    }
}
```

### Generating Insights

Insights are automatically generated when viewing a competitor's page. You can also trigger manual generation:

```php
// In your code
use App\Services\CompetitorAnalysisService;
use App\Services\CompetitorAIInsightsService;

$analysisService = app(CompetitorAnalysisService::class);
$aiService = app(CompetitorAIInsightsService::class);

$insight = $analysisService->generateInsights(
    $brand,
    $competitor,
    $startDate,
    $endDate
);

$recommendations = $aiService->generateRecommendations($insight);
$summary = $aiService->generateSummary($insight);
```

### Syncing Competitor Data

#### Manual Sync
```bash
php artisan competitors:sync --competitor=1
```

#### Sync All Competitors
```bash
php artisan competitors:sync
```

#### Scheduled Sync
The system automatically syncs competitor data every 6 hours via Laravel's task scheduler.

## Security

### Access Control
- Only users with `brand_admin` role can access competitor insights
- Users can only view competitors associated with their brand
- All operations are protected by Laravel policies

### Data Privacy
- Only publicly available data is collected
- Respects platform terms of service
- No private or restricted data is accessed
- Competitor data is stored separately from brand private data

## Configuration

### Environment Variables

Add to your `.env` file:

```env
# OpenAI API for AI-powered insights
OPENAI_API_KEY=your_openai_api_key

# Social Media API Keys (for data fetching)
INSTAGRAM_API_KEY=your_instagram_key
FACEBOOK_API_KEY=your_facebook_key
TWITTER_API_KEY=your_twitter_key
# ... other platform keys
```

### Scheduled Tasks

The competitor sync is scheduled in `app/Console/Kernel.php`:

```php
$schedule->command('competitors:sync')->everySixHours();
```

You can adjust the frequency as needed.

## Services

### CompetitorDataFetchService
Handles fetching data from social media platforms.

### CompetitorAnalysisService
Performs comparative analysis and generates insights.

### CompetitorAIInsightsService
Uses AI to generate recommendations and summaries.

### CompetitorAlertService
Monitors for performance spikes and generates alerts.

## Models

### CompetitorBrand
Represents a competitor brand being tracked.

### CompetitorPost
Individual posts from competitors.

### CompetitorInsight
Generated insights and analysis.

### CompetitorAlert
Alerts for significant competitor activities.

## Frontend Integration

The module includes views for:
- Dashboard with competitor overview
- Competitor management interface
- Detailed insights view with charts
- Alert notifications
- Comparison dashboard

## Best Practices

1. **Regular Monitoring**: Check insights weekly to stay updated on competitor strategies
2. **Act on Recommendations**: Implement AI-generated recommendations systematically
3. **Alert Response**: Set up notifications for critical alerts
4. **Data Quality**: Ensure competitor social handles are accurate
5. **Privacy Compliance**: Only track publicly available information

## Troubleshooting

### Data Not Syncing
- Check API credentials in `.env`
- Verify competitor social handles are correct
- Check Laravel logs for errors: `storage/logs/laravel.log`

### Missing Insights
- Ensure competitor has sufficient post data (minimum 10 posts recommended)
- Check date range - insights require data within the specified period
- Verify AI service is configured correctly

### Alerts Not Generating
- Ensure competitor has historical data for comparison
- Check alert thresholds in `CompetitorAlertService`
- Verify cron job is running

## Future Enhancements

- Real-time data streaming
- Advanced sentiment analysis
- Competitor content recommendations
- Automated reporting
- Multi-brand comparison
- Export to PDF/Excel
- Integration with more social platforms

## Support

For issues or questions, please refer to:
- Laravel documentation: https://laravel.com/docs
- Project repository issues
- Internal development team

## License

This module is part of the AI Business Market platform and follows the same license terms.