# MonsterInsights Reports - Technical Documentation

## Overview

The MonsterInsights reporting system provides a flexible and extensible framework for creating and managing Google Analytics reports in WordPress. The system is built with a base abstract class that handles common functionality and individual report classes that implement specific report types.

## Directory Structure

```
includes/admin/reports/
├── abstract-report.php       # Base report class with shared functionality
├── overview.php             # Overview report implementation
├── site-insights.php       # Site insights report
├── site-summary.php        # Site summary report
└── index.php               # Security file
```

## Core Components

### 1. Abstract Report Class (`abstract-report.php`)

The `MonsterInsights_Report` class provides the foundation for all reports with:

#### Key Properties
```php
public $title;        // Report title
public $class;        // Report class name
public $name;         // Report identifier
public $version;      // Report version
public $source;       // Report data source
public $start_date;   // Report start date
public $end_date;     // Report end date
```

#### Core Functionality

1. **Report Generation**
   ```php
   public function show_report($args = array())
   ```
   - Handles permissions checking
   - Validates authentication
   - Processes report requirements
   - Manages error states
   - Renders report HTML

2. **Data Management**
   ```php
   public function get_data($args = array())
   ```
   - Validates date ranges
   - Handles caching
   - Processes API responses
   - Manages error states

3. **Cache Control**
   ```php
   public function delete_cache($where = 'site')
   ```
   - Manages report data caching
   - Supports site and network cache

### 2. Report Implementations

#### Overview Report (`overview.php`)
```php
class MonsterInsights_Report_Overview extends MonsterInsights_Report
```
- Provides site overview statistics
- Handles country data formatting
- Manages URL escaping
- Processes bounce rate formatting
- Generates GA report links

#### Site Insights Report (`site-insights.php`)
- Provides detailed site analytics
- Processes custom metrics
- Handles comparative data

#### Site Summary Report (`site-summary.php`)
- Generates site performance summaries
- Processes key metrics
- Handles data aggregation

## Development Guidelines

### 1. Creating New Reports

1. **Extend Base Class**
   ```php
   class MonsterInsights_Report_Custom extends MonsterInsights_Report {
       public $name = 'custom';
       public $version = '1.0.0';
       public $level = 'lite';
   }
   ```

2. **Implement Required Methods**
   ```php
   public function prepare_report_data($data) {
       // Process report specific data
       return $data;
   }
   ```

3. **Add Custom Functionality**
   - Implement report-specific data processing
   - Add custom error handling
   - Implement custom caching if needed

### 2. Data Processing

1. **Date Range Handling**
   ```php
   protected function is_valid_date_range($start, $end)
   protected function is_valid_date($date)
   ```

2. **Cache Management**
   - Use transients for temporary storage
   - Implement cache invalidation
   - Handle multisite caching

3. **Error Handling**
   - Validate input data
   - Process API errors
   - Handle permission errors

## Security Considerations

1. **Permission Checks**
   ```php
   if (!current_user_can('monsterinsights_view_dashboard')) {
       return error_message;
   }
   ```

2. **Data Sanitization**
   - Sanitize all input data
   - Escape output data
   - Validate date ranges

3. **API Security**
   - Handle authentication errors
   - Validate API responses
   - Secure sensitive data

## Caching System

1. **Cache Implementation**
   - Uses WordPress transients
   - Supports network-wide caching
   - Implements cache invalidation

2. **Cache Duration**
   - 15 minutes for same-day data
   - 24 hours for historical data
   - Configurable via filters

## API Architecture

### Overview

The reporting system interacts with two distinct server infrastructures:

1. **Store API** (monsterinsights.com)
   - Handles license management
   - Processes purchases
   - Manages user accounts
   - Provides plugin updates

2. **Relay API** (app.monsterinsights.com / app.exactmetrics.com)
   - Acts as intermediary between client sites and Google Analytics API
   - Implements intelligent caching system with dynamic expiration
   - Manages API quotas and rate limiting
   - Stores site-license associations
   - Handles authentication tokens
   - Provides standardized report endpoints under `/v2/analytics/reports/`

### Report Endpoint Structure

Relay API report endpoints follow this structure:
```php
// Relay API Side
class ReportName extends BaseReport {
    public function index(Request $request, Response $response, array $args = []) {
        // 1. Initialize and track
        $this->track_report_call();
        
        // 2. Get auth data
        $auth = $storage['client']->auth;
        
        // 3. Fetch & process data
        $data = $this->service->fetch([
            'property_id' => $site->property_id,
            'current_range' => $this->get_current_range(),
            'previous_range' => $this->get_previous_range()
        ]);
        
        // 4. Cache & return
        $this->save_to_cache($data);
        return $response->withJson([
            'data' => $data,
            'status' => 200
        ]);
    }
}

// WordPress Plugin Side
class MonsterInsights_Report_Custom extends MonsterInsights_Report {
    public function get_data($args = array()) {
        // Make request to Relay API endpoint
        $response = wp_remote_get(
            'app.monsterinsights.com/v2/analytics/reports/report-name/',
            array('headers' => $this->get_auth_headers())
        );
        
        // Process & cache response
        return $this->process_response($response);
    }
}
```

### Caching Architecture

The system implements a two-layer caching strategy:

1. **Relay API Caching**
   - Primary caching layer
   - Dynamic cache duration based on report type
   - Implements quota management
   - Handles cache invalidation for real-time data
   ```php
   // Example cache duration logic in Relay
   $expiration = date('Y-m-d') === $end 
       ? (15 * MINUTE_IN_SECONDS) 
       : (strtotime('Tomorrow 12:05am', $current_timestamp) - $current_timestamp);
   ```

2. **WordPress Plugin Caching**
   - Secondary caching layer
   - Uses WordPress transients
   - Reduces API calls to Relay
   - Configurable via filters
   ```php
   $cache_key = 'monsterinsights_report_' . $this->name . '_' . $start . '_' . $end;
   set_transient($cache_key, $data, $expiration);
   ```

### Error Handling & Fallbacks

1. **Relay API Errors**
   - Standardized error responses
   - HTTP status code mapping
   - Quota exceeded handling
   - Authentication failures

2. **WordPress Plugin Handling**
   - Graceful degradation
   - User-friendly error messages
   - Automatic retry logic
   - Fallback to cached data

### Security Implementation

1. **Authentication Flow**
   ```php
   // WordPress side
   private function get_auth_headers() {
       return array(
           'Authorization' => 'Bearer ' . $this->get_auth_token(),
           'X-MonsterInsights-Site' => $this->get_site_token()
       );
   }
   ```

2. **License Validation**
   - Store API validates license status
   - Relay API enforces access levels
   - WordPress plugin checks local license state

3. **Data Protection**
   - Encrypted communication
   - Sanitized data transfer
   - Protected authentication tokens

## Integration Points

1. **WordPress Integration**
   - Hooks into admin menu
   - Integrates with capabilities system
   - Supports multisite

2. **Google Analytics Integration**
   - Handled through Relay API middleware
   - Never connects directly to GA API
   - Respects API quotas and rate limits
   - Implements intelligent caching

3. **MonsterInsights Integration**
   - License validation through Store API
   - Report data through Relay API
   - Coordinated authentication flow
   - Managed API access

4. **API Integration**
   - Store API for license management
   - Relay API for analytics data
   - Coordinated error handling
   - Fallback mechanisms

## Troubleshooting

### Common Issues

1. **Data Not Loading**
   - Check authentication status
   - Verify API credentials
   - Review cache status

2. **Permission Errors**
   - Verify user capabilities
   - Check role settings
   - Review authentication

3. **API Issues**
   - Check API quotas
   - Verify endpoint status
   - Review error logs

4. **API Communication Issues**
   - **Store API Problems**
     - Check license status
     - Verify site registration
     - Review connection logs
   
   - **Relay API Problems**
     - Check authentication status
     - Verify cache status
     - Review quota usage
     - Check API response logs

## Future Considerations

1. **Performance Optimization**
   - Implement better caching
   - Optimize API calls
   - Improve data processing

2. **Feature Enhancements**
   - Add more report types
   - Enhance data visualization
   - Improve export options

3. **API Evolution**
   - Support new GA4 features
   - Enhance API integration
   - Improve error handling

## Additional Resources

- [Google Analytics 4 API Documentation](https://developers.google.com/analytics/devguides/reporting/data/v1)
- [MonsterInsights Developer Documentation](https://developers.monsterinsights.com/)
- [WordPress Plugin Development](https://developer.wordpress.org/plugins/) 