# MonsterInsights Gutenberg Integration - Technical Documentation

## Overview

The `monsterinsights/includes/gutenberg/` directory contains the server-side PHP implementations that support MonsterInsights Gutenberg blocks. This code handles block registration, asset loading, data fetching from Google Analytics, and server-side rendering of dynamic blocks.

The server-side architecture is designed to follow WordPress core standards and complement the JavaScript-based block implementations found in the `monsterinsights-gutenberg-app` directory.

## Related Documentation

This documentation covers the server-side PHP implementation of Gutenberg blocks. For related documentation:

* **[Gutenberg App](../../../monsterinsights-gutenberg-app/Internal-Readme.md)** - JavaScript implementation of block editing experience
* **[Core Plugin Architecture](../../../monsterinsights/Internal-Readme.md)** - Overall plugin architecture and technical details

## Architecture

### Core Components

The Gutenberg integration consists of several key components:

1. **Block Registration & Asset Loading**: Handled by `register-scripts.php`
2. **Dynamic Block Rendering**: Implemented in block-specific PHP classes
3. **Data Retrieval**: Server-side logic to fetch analytics data from Google Analytics
4. **Templates**: Reusable templates for consistent block rendering
5. **Editor Enhancements**: Tools like the Headline Analyzer that enhance the editing experience

### File Structure

- **gutenberg.php**: Main entry point that loads submodules
- **register-scripts.php**: Registers and enqueues necessary assets
- **monsterinsights-stats-block.php**: Handles the Site Insights block implementation
- **headline-tool/**: Headline Analyzer functionality
- **site-insights/**: Templates and rendering for analytics data blocks

## Block Registration & Asset Loading

The `register-scripts.php` file manages the registration and loading of assets for Gutenberg blocks:

```php
function monsterinsights_gutenberg_editor_assets() {
    // Only load if WordPress version supports Gutenberg
    if ( ! monsterinsights_load_gutenberg_app() ) {
        return;
    }
    
    // Register editor scripts with appropriate dependencies
    wp_enqueue_script(
        'monsterinsights-gutenberg-editor-js',
        $plugins_js_url,
        $js_dependencies,
        monsterinsights_get_asset_version(),
        true
    );
    
    // Register editor styles
    wp_enqueue_style(
        'monsterinsights-gutenberg-editor-css',
        $plugins_css_url,
        array(),
        monsterinsights_get_asset_version()
    );
    
    // Localize script for editor with necessary data
    wp_localize_script(
        'monsterinsights-gutenberg-editor-js',
        'monsterinsights_gutenberg_tool_vars',
        [/* data for blocks */]
    );
}
```

Key features of the asset loading system:
- Conditional loading based on WordPress version compatibility
- Support for multiple product variations (Lite/Pro)
- Dynamic filter hooks to allow customization of asset URLs
- Proper dependency management for WordPress core scripts
- Context-aware loading (e.g., avoids loading in widget editor)

## Dynamic Block Rendering

MonsterInsights blocks are implemented as dynamic blocks, which means:
1. The block UI is defined in JavaScript (in the `monsterinsights-gutenberg-app`)
2. The block content is rendered on the server using PHP
3. The rendered HTML is returned to the client

This approach provides several benefits:
- Access to server-side data (Google Analytics data)
- Consistent rendering between editor and frontend
- Better performance for data-heavy blocks
- Reduced JavaScript bundle size

### Site Insights Block

The `MonsterInsights_Site_Insights_Block` class (in `monsterinsights-stats-block.php`) handles the rendering of analytics data blocks:

```php
public function block_output( $attributes, $block ) {
    $type = $attributes['type'];
    $metric = $attributes['metric'];
    
    // Load necessary assets for block rendering
    $this->load_assets();
    
    // Fetch analytics data
    $data = $this->get_data();
    
    // Determine which template to use based on block attributes
    $template_file = MONSTERINSIGHTS_PLUGIN_DIR . 'includes/gutenberg/site-insights/templates/' . $type . '/class-' . $type . '-' . $metric;
    
    // Load base template classes
    require_once MONSTERINSIGHTS_PLUGIN_DIR . '/includes/gutenberg/site-insights/templates/class-site-insights-metric-template.php';
    
    // Instantiate specific template class
    $class_name = 'MonsterInsights_SiteInsights_Template_' . ucfirst( $type ) . '_' . ucfirst( $metric );
    $template = new $class_name( $attributes, $data );
    
    // Render block output
    return sprintf( '<div %1$s>%2$s</div>', $block_attributes, $template->output() );
}
```

## Template System

The Site Insights blocks use a template system to ensure consistent rendering and separation of concerns:

### Base Template Classes

1. **MonsterInsights_SiteInsights_Metric_Template**: Abstract base class for all metrics
   - Defines required methods: `get_options()` and `output()`
   - Handles common functionality for all blocks
   - Provides utility methods for color handling, data formatting, etc.

2. **MonsterInsights_SiteInsights_DuoScorecard_Template**: Extends the base template for dual metric scorecard displays

### Specialized Templates

Each specific metric and display type has its own template class:
- **Graph Templates**: For time-series data visualization
- **Scorecard Templates**: For key metric displays
- **Comparison Templates**: For showing metrics with comparisons to previous periods

The template approach allows for:
- Consistent styling and behavior
- Easy addition of new metrics and visualization types
- Clean separation between data and presentation
- Reuse of common components

## Headline Analyzer Tool

The Headline Analyzer tool enhances the editor experience by providing real-time feedback on post titles:

```php
namespace MonsterInsightsHeadlineToolPlugin;

class MonsterInsightsHeadlineToolPlugin {
    function init() {
        add_action( 'wp_ajax_monsterinsights_gutenberg_headline_analyzer_get_results', array( $this, 'get_result' ) );
    }
    
    function get_result() {
        // Check nonce for security
        if ( check_ajax_referer( 'monsterinsights_gutenberg_headline_nonce', false, false ) === false ) {
            wp_send_json_error();
        }
        
        // Analyze headline
        $result = $this->get_headline_scores();
        
        // Return analysis result as JSON
        wp_send_json_success([
            'result'   => $result,
            'analysed' => !$result->err,
            'sentence' => ucwords( wp_unslash( $q ) ),
            'score'    => $result->score 
        ]);
    }
    
    // Analysis methods...
}
```

The Headline Analyzer:
- Provides an AJAX endpoint for real-time analysis
- Evaluates headlines based on multiple factors:
  - Length (character count)
  - Word count
  - Emotional words
  - Power words
  - Common/uncommon word balance
- Returns a comprehensive analysis with suggestions for improvement

## Data Retrieval

Analytics data for blocks is retrieved through the MonsterInsights reporting system:

```php
private function get_data() {
    // Check authentication status
    $site_auth = MonsterInsights()->auth->get_viewname();
    $ms_auth   = is_multisite() && MonsterInsights()->auth->get_network_viewname();
    if ( ! $site_auth && ! $ms_auth ) {
        return false;
    }
    
    // Load reporting classes
    require_once MONSTERINSIGHTS_PLUGIN_DIR . 'includes/admin/reports/abstract-report.php';
    require_once MONSTERINSIGHTS_PLUGIN_DIR . 'includes/admin/reports/site-insights.php';
    
    // Initialize report class
    $report = new MonsterInsights_Report_Site_Insights();
    
    // Fetch data for last 30 days
    $data = $report->get_data([
        'start' => date( 'Y-m-d', strtotime( '-31 days' ) ),
        'end' => date( 'Y-m-d', strtotime( '-1 days' ) ),
    ]);
    
    return $data['data'];
}
```

Key aspects of data retrieval:
- Uses the same reporting system as the MonsterInsights dashboard
- Abstracts Google Analytics API complexity
- Handles authentication and error states
- Provides standardized data format for all blocks

## Asset Management

Frontend and editor assets are managed systematically:

```php
public function register_frontend_scripts() {
    $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
    
    // Register third-party dependencies
    wp_register_script( 'apexcharts', plugins_url( 'assets/js/frontend/apexcharts.min.js', MONSTERINSIGHTS_PLUGIN_FILE ), [], monsterinsights_get_asset_version(), true );
    
    // Register block script with dependencies
    wp_register_script( 'monsterinsights-block-scripts', $scripts_url, array( 'apexcharts', 'jquery' ), monsterinsights_get_asset_version(), true );
    
    // Register block styles
    wp_register_style( 'monsterinsights-editor-frontend-style', $style_url, array(), monsterinsights_get_asset_version() );
    
    // Optimize script loading
    $use_async = apply_filters( 'monsterinsights_frontend_gtag_script_async', true );
    if ( $use_async ) {
        wp_script_add_data( 'apexcharts', 'strategy', 'async' );
        wp_script_add_data( 'monsterinsights-block-scripts', 'strategy', 'defer' );
    }
}
```

Asset management features:
- Conditional loading of minified/non-minified assets based on SCRIPT_DEBUG
- Support for script optimization (async/defer loading)
- Registration of third-party dependencies
- Filter hooks for customization
- Only loads assets when blocks are used (not on all pages)

## Block Types

The MonsterInsights Gutenberg integration includes several block types:

1. **Site Insights Blocks**:
   - Scorecards: Display key metrics in compact form
   - Graphs: Show time-series data visualizations
   - Comparison Cards: Show metrics with period-over-period comparison

2. **Popular Posts Blocks**:
   - Inline Popular Posts: For embedding within content
   - Widget Popular Posts: For sidebar/widget areas
   - Products Popular Posts: For WooCommerce integration

## Multi-Brand Support

The server-side Gutenberg integration supports both MonsterInsights and ExactMetrics branding through:

1. **Text Domain Differentiation**:
   ```php
   $textdomain = monsterinsights_is_pro_version() ? 'google-analytics-premium' : 'google-analytics-for-wordpress';
   ```

2. **Asset Path Variation**:
   ```php
   $version_path = monsterinsights_is_pro_version() ? 'pro' : 'lite';
   ```

3. **Feature Availability Checks**:
   ```php
   'is_headline_analyzer_enabled' => apply_filters( 'monsterinsights_headline_analyzer_enabled', true ) && 'true' !== monsterinsights_get_option( 'disable_headline_analyzer' ),
   ```

## Integration with REST API

Blocks leverage the MonsterInsights REST API endpoints for data retrieval:

1. **Data Endpoints**: Custom REST endpoints provide analytics data to blocks
2. **Authentication**: Properly secured with nonce verification
3. **Error Handling**: Consistent error reporting for failed requests

## Development Workflow

When developing new blocks or enhancing existing ones:

1. **JavaScript Implementation**: Create the block UI in the `monsterinsights-gutenberg-app`
2. **Block Registration**: Register scripts and styles in `register-scripts.php`
3. **Server-Side Rendering**: Implement a PHP class for dynamic rendering
4. **Template Creation**: Create templates for the block display
5. **Asset Registration**: Add any necessary CSS/JS assets

## Extensibility

The server-side implementation provides several extension points:

1. **Filters for Asset URLs**:
   ```php
   $plugins_js_url = apply_filters(
       'monsterinsights_editor_scripts_url',
       plugins_url( $plugins_js_path, MONSTERINSIGHTS_PLUGIN_FILE )
   );
   ```

2. **Filters for Block Variables**:
   ```php
   apply_filters( 'monsterinsights_gutenberg_tool_vars', array(/* ... */) )
   ```

3. **Post Type Support**:
   ```php
   apply_filters( 'monsterinsights_headline_analyzer_post_types', array( 'post' ) )
   ```

4. **Feature Toggles**:
   ```php
   apply_filters( 'monsterinsights_headline_analyzer_enabled', true )
   ```

## Performance Considerations

The server-side implementation includes several optimizations:

1. **Conditional Asset Loading**: Only loads assets when blocks are used
2. **Async/Defer Script Loading**: Improves page load performance
3. **Minified Assets**: Reduces file size in production
4. **Caching**: The reporting system implements caching for API requests
5. **Optimized Rendering**: Templates are designed for efficient rendering

## Browser Support

The server-side implementation ensures compatibility with a wide range of browsers by:
1. Providing polyfills where necessary
2. Using standard HTML output
3. Implementing progressive enhancement

## Testing

When testing block functionality:
1. Verify correct rendering in both editor and frontend
2. Test with both authenticated and non-authenticated GA accounts
3. Check behavior with cached and non-cached data
4. Verify compatibility with other blocks and content

## Troubleshooting

Common issues:
1. **Block Not Rendering**: Check authentication status with Google Analytics
2. **Missing Assets**: Verify filters aren't modifying asset URLs unexpectedly
3. **Data Discrepancies**: Clear MonsterInsights cache and verify reporting API
4. **Block Editor Errors**: Check browser console for JavaScript errors 