<?php

namespace Drupal\visitors\Service;

use Drupal\visitors\VisitorsCampaignInterface;

/**
 * Campaign service for parsing marketing campaign parameters.
 *
 * Supports both mtm_* and utm_* parameters for comprehensive campaign tracking.
 */
class CampaignService implements VisitorsCampaignInterface {

  /**
   * {@inheritdoc}
   */
  public function parse(?string $query): ?array {
    if (empty($query)) {
      return NULL;
    }

    // Parse the query string into an array.
    parse_str($query, $params);

    $campaign_data = [];

    // Parse mtm_* parameters (Marketing URL Builder).
    $mtm_params = [
      'mtm_campaign' => 'campaign',
      'mtm_source' => 'source',
      'mtm_medium' => 'medium',
      'mtm_keyword' => 'keyword',
      'mtm_content' => 'content',
      'mtm_cid' => 'campaign_id',
      'mtm_group' => 'group',
      'mtm_placement' => 'placement',
    ];

    foreach ($mtm_params as $param => $key) {
      if (isset($params[$param]) && !empty($params[$param])) {
        $campaign_data[$key] = trim($params[$param]);
      }
    }

    // Parse utm_* parameters (Google Analytics).
    $utm_params = [
      'utm_campaign' => 'campaign',
      'utm_source' => 'source',
      'utm_medium' => 'medium',
      'utm_term' => 'keyword',
      'utm_content' => 'content',
      'utm_id' => 'campaign_id',
    ];

    foreach ($utm_params as $param => $key) {
      if (isset($params[$param]) && !empty($params[$param])) {
        // Only set if not already set by mtm_* parameters.
        if (!isset($campaign_data[$key])) {
          $campaign_data[$key] = trim($params[$param]);
        }
      }
    }

    // Return NULL if no campaign data was found.
    return empty($campaign_data) ? NULL : $campaign_data;
  }

}
