<?php

/**
 * @file
 *
 */

function incubator_analytics_incubator_settings_menu() {
  return array(
    'description' => 'Settings for connecting with Google Analytics.',
    'title' => 'Stats & analytics',
  );
}

function incubator_analytics_incubator_settings() {
  $form['googleanalytics_account'] = array(
    '#title' => t('Web Property ID'),
    '#type' => 'textfield',
    '#default_value' => variable_get('googleanalytics_account', 'UA-'),
    '#size' => 15,
    '#maxlength' => 20,
    '#required' => TRUE,
    '#description' => t('This ID is unique to each site you want to track separately, and is in the form of UA-xxxxxxx-yy. To get a Web Property ID, <a href="@analytics">register your site with Google Analytics</a>, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. <a href="@webpropertyid">Find more information in the documentation</a>.', array('@analytics' => 'http://www.google.com/analytics/', '@webpropertyid' => url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', array('fragment' => 'webProperty')))),
  );
  
  $form = system_settings_form($form);
  
  $form['actions']['reset_custom_vars'] = array(
    '#type' => 'submit',
    '#value' => t('Reset custom variables'),
  );
  $form['#submit'][] = 'incubator_analytics_settings_save';
  
  return $form;
}

function incubator_analytics_settings_save($form, $form_state) {
  if ($form_state['clicked_button']['#value'] == t('Reset custom variables')) {
    incubator_analytics_reset_custom_vars();
  }
}

function incubator_analytics_reset_custom_vars() {
  foreach (incubator_analytics_custom_google_vars() as $module => $vars_array) {
    if (module_exists($module)) {
      foreach ($vars_array as $name => $var) {
        incubator_analytics_set_custom_var($var);
      }
    }
  }
}

function incubator_analytics_custom_google_vars($module = NULL) {
  $variables['incubator_analytics'] = array(
    'analytics:role-names' => array(
      'name' => 'Roles', 
      'value' => '[current-user:role-names]',
      'scope' => 1,
    ),
  );
  $variables['hybridauth'] = array(
    'social:hybridauth' => array(
      'name' => 'Social',
      'value' => '[current-user:hybridauth:provider]',
      'scope' => 1,
    ),
  );
  $variables['incubator_social'] = array(
    'social:linktype' => array(
      'name' => 'LinkType',
      'value' => '[current-page:query:lnk]',
      'scope' => 3,
    ),
  );
  drupal_alter('incubator_analytics_custom_google_vars', $variables);
  return $variables;
}
