# Brand Reputation Score System

## Overview

The Reputation Score system provides AI-driven reputation monitoring and management for brands. It quantifies public sentiment, compliance risk, and trust signals across social platforms and earned media into a comprehensive 0-100 score with actionable insights.

## Features

### Core Capabilities

1. **Composite Reputation Score (0-100)**
   - Overall brand reputation quantified into a single score
   - Grade system (A-F) for easy interpretation
   - Trend tracking with historical comparisons

2. **Five Sub-Scores**
   - **Sentiment Score**: Social engagement + review ratings sentiment
   - **Responsiveness Score**: Average response time to comments/support
   - **Trust Score**: Verified mentions and reputable outlet coverage
   - **Compliance Score**: Flagged content and legal/regulatory issues
   - **Growth Score**: Trajectory vs previous period

3. **Driver Analysis**
   - Identifies specific events/content driving score changes
   - Links to source posts, articles, reviews, complaints
   - Categorizes by type (positive/negative/neutral)
   - Impact scoring for prioritization

4. **AI-Powered Insights**
   - 3-bullet human-readable explanations for score changes
   - Automated reasoning for recommendations
   - Context-aware analysis

5. **Actionable Recommendations**
   - Prioritized action items (high/medium/low)
   - Estimated impact and effort levels
   - Status tracking (pending/in progress/completed/dismissed)
   - Assignment capabilities

6. **Manual Overrides**
   - Mark negative drivers as "resolved"
   - Automatic score recalculation
   - Full audit trail of all changes

7. **Alert System**
   - Threshold-based alerts (e.g., >10% drop in 7 days)
   - Configurable notifications
   - Alert dismissal with audit logging

## Database Schema

### Tables

#### `reputation_scores`
Stores calculated reputation scores for brands.

**Key Fields:**
- `score`: Overall reputation score (0-100)
- `sentiment_score`, `responsiveness_score`, `trust_score`, `compliance_score`, `growth_score`: Sub-scores
- `timeframe`: Period analyzed (7/30/90 days)
- `ai_explanation`: AI-generated insights
- `alert_triggered`: Whether score drop triggered alert
- `status`: Calculation status (calculating/completed/failed)

#### `reputation_drivers`
Individual events/content that influenced the score.

**Key Fields:**
- `type`: positive/negative/neutral
- `category`: social_engagement, review, press_mention, complaint, etc.
- `source_type`, `source_url`: Link to original content
- `impact_score`: How much this affected overall score
- `is_resolved`: Manual override flag
- `resolution_note`: Explanation of resolution

#### `reputation_recommendations`
AI-generated action items for improvement.

**Key Fields:**
- `title`, `description`: Recommendation details
- `priority`: high/medium/low
- `estimated_impact`: Potential score increase
- `effort_level`: low/medium/high
- `status`: pending/in_progress/completed/dismissed

#### `reputation_audit_logs`
Complete audit trail of all actions.

**Key Fields:**
- `action`: Type of action performed
- `before_state`, `after_state`: Change tracking
- `user_id`: Who performed the action

## API Endpoints

### Brand Admin Routes

```php
GET    /brand/reputation                          # Dashboard
POST   /brand/reputation/calculate                # Calculate new score
GET    /brand/reputation/{score}                  # Score details
POST   /brand/reputation/drivers/{driver}/resolve # Resolve driver
PUT    /brand/reputation/recommendations/{rec}    # Update recommendation
GET    /brand/reputation/history                  # Score history (JSON)
GET    /brand/reputation/audit-log                # Audit log
GET    /brand/reputation/alerts                   # View alerts
POST   /brand/reputation/alerts/{score}/dismiss   # Dismiss alert
```

## Usage Examples

### Calculate Reputation Score

```php
use App\Services\ReputationScoreService;

$service = app(ReputationScoreService::class);

// Calculate score for 30-day period
$score = $service->calculateScore($brand, '30', [
    'social_engagement' => [...],
    'reviews' => [...],
    // Optional: provide aggregated data
]);

// Access results
echo $score->score; // 75.5
echo $score->grade; // B
echo $score->status_label; // good
```

### Resolve a Negative Driver

```php
$driver = ReputationDriver::find($id);
$driver->markAsResolved($user, 'Issue addressed with customer');

// Automatically recalculates score
$service->recalculateScore($driver->reputationScore);
```

### Query Scores

```php
// Get latest score for brand
$latestScore = ReputationScore::latestForBrand($brandId)
    ->byTimeframe('30')
    ->first();

// Get scores with alerts
$alerts = ReputationScore::withAlerts()
    ->where('brand_id', $brandId)
    ->get();

// Get high-impact drivers
$drivers = ReputationDriver::where('reputation_score_id', $scoreId)
    ->highImpact()
    ->orderByImpact()
    ->get();
```

## Score Calculation Logic

### Overall Score Formula

```
Overall Score = (Sentiment × 0.30) + (Responsiveness × 0.20) + 
                (Trust × 0.20) + (Compliance × 0.20) + (Growth × 0.10)
```

### Sub-Score Calculations

**Sentiment Score:**
- Weighted average of social engagement, reviews, press mentions
- Converts -1 to +1 sentiment to 0-100 scale

**Responsiveness Score:**
- Based on average response time
- < 1 hour = 100, 1-4 hours = 80-100, 4-24 hours = 50-80, > 24 hours = 0-50

**Trust Score:**
- Verification ratio × 70 + reputable outlets × 5 (max 30)

**Compliance Score:**
- Starts at 100, deducts for flagged content (-5 each), legal issues (-15 each), complaints (-2 each, max -30)

**Growth Score:**
- Compares current vs previous period engagement
- -50% = 0, 0% = 50, +50% = 100

### Alert Thresholds

- **High Priority**: Score drop ≥ 10% in timeframe
- Triggers notification to configured admins
- Logged in audit trail

## Security & Privacy

### Data Handling
- Uses only publicly available data + brand-provided logs
- Never exposes private PII from users
- All calculations audited

### Access Control
- Brand admins can only view/manage their own reputation
- Platform admins have full access
- Policy-based authorization via [`ReputationScorePolicy`](../app/Policies/ReputationScorePolicy.php)

### Audit Trail
- Every action logged with user, IP, timestamp
- Before/after state tracking for changes
- Immutable log records

## AI Integration

### AI Explanation Generation

The system uses AI to generate human-readable explanations:

```php
$explanation = $this->aiService->generateText($prompt, [
    'max_tokens' => 200,
    'temperature' => 0.7,
]);
```

**Fallback**: If AI fails, generates rule-based explanation.

### Recommendation Generation

AI analyzes score components to suggest:
- Priority level based on impact
- Estimated effort and timeline
- Specific actionable steps

## Configuration

### Timeframes
- 7 days: Short-term trends
- 30 days: Standard monthly view (default)
- 90 days: Quarterly analysis

### Weights (Customizable)
Edit in [`ReputationScoreService`](../app/Services/ReputationScoreService.php):

```php
protected $weights = [
    'sentiment' => 0.30,
    'responsiveness' => 0.20,
    'trust' => 0.20,
    'compliance' => 0.20,
    'growth' => 0.10,
];
```

## Data Source Integration

### Placeholder Methods

The service includes placeholder methods for data aggregation:

```php
protected function getSocialEngagement(Brand $brand, Carbon $start, Carbon $end): array
protected function getReviews(Brand $brand, Carbon $start, Carbon $end): array
protected function getPressMentions(Brand $brand, Carbon $start, Carbon $end): array
protected function getInfluencerMentions(Brand $brand, Carbon $start, Carbon $end): array
protected function getComplaints(Brand $brand, Carbon $start, Carbon $end): array
protected function getResponseTimes(Brand $brand, Carbon $start, Carbon $end): array
protected function getLegalRegulatory(Brand $brand, Carbon $start, Carbon $end): array
```

**TODO**: Integrate with actual data sources (social media APIs, review platforms, media monitoring services, support systems).

## UI Components

### Dashboard View
- Overall score with grade and trend
- Sub-score breakdown
- Top positive/negative drivers
- Prioritized recommendations
- Historical chart

### Driver Details
- Source content preview
- Impact analysis
- Resolution workflow
- Link to original source

### Recommendations Panel
- Priority-based sorting
- Status tracking
- Assignment capabilities
- Impact/effort indicators

## Testing

Run tests:

```bash
php artisan test --filter ReputationScoreTest
```

### Test Coverage
- Score calculation accuracy
- Driver resolution workflow
- Recommendation updates
- Access control policies
- Alert triggering
- Audit logging

## Maintenance

### Scheduled Tasks

Add to [`app/Console/Kernel.php`](../app/Console/Kernel.php):

```php
// Calculate daily reputation scores
$schedule->call(function () {
    Brand::chunk(100, function ($brands) {
        foreach ($brands as $brand) {
            app(ReputationScoreService::class)->calculateScore($brand, '30');
        }
    });
})->daily();
```

### Performance Optimization

- Scores cached for 1 hour
- Batch driver insertion (max 100 per score)
- Indexed queries for fast retrieval
- Pagination for large datasets

## Troubleshooting

### Score Not Calculating
1. Check `reputation_scores.status` field
2. Review `calculation_metadata` for errors
3. Check audit logs for failure details

### Missing Drivers
- Verify data source integration
- Check aggregation method return values
- Review driver creation logic

### Alerts Not Triggering
- Verify threshold configuration
- Check `alert_triggered` field
- Review notification system integration

## Future Enhancements

- [ ] PDF/Excel export functionality
- [ ] Real-time score updates via WebSockets
- [ ] Competitor benchmarking
- [ ] Sentiment analysis API integration
- [ ] Custom alert thresholds per brand
- [ ] Multi-language support for insights
- [ ] Mobile app integration

## Support

For issues or questions:
- Review audit logs: `/brand/reputation/audit-log`
- Check Laravel logs: `storage/logs/laravel.log`
- Contact platform support

## Disclaimer

**Important**: This reputation score is an AI-derived signal based on publicly available data. It should be used as one input among many for decision-making. Always include human review and judgment when taking action based on reputation scores.