<?php
/**
 * @file
 * Code for the Group pages feature.
 */

include_once 'groups_pages.features.inc';

/**
 * Implements hook_preprocess_field()
 *
 * Override markup of organic group subscribtion field.
 *
 * @see http://drupal.stackexchange.com/questions/28105/how-to-change-og-subscribe-to-group-link-text
 */
function groups_pages_preprocess_field(&$variables) {
  if (($variables['element']['#field_name'] == 'group_group') &&
      ($variables['element']['#formatter'] == 'og_group_subscribe')) {
    // determine login status from element class
    $item = $variables['items'][0];
    $class = isset($item['#options']['attributes']) ? $item['#options']['attributes']['class'] : NULL;
    $class = isset($item['#attributes']['class']) ? $item['#attributes']['class'] : $class;
    $class = is_array($class) ? reset($class) : $class;
    switch ($class) {
      case 'group subscribe':
        $variables['items'][0]['#title'] = t('Join us!');
        $variables['items'][0]['#options']['attributes']['class'][] = 'btn';
        $variables['items'][0]['#options']['attributes']['class'][] = 'btn-default';
        $variables['items'][0]['#prefix'] = '<p>'.t('Join to our user group, participate on local events, contribute to our community, and stay informed about latest news.').'</p>';
        // redirect to custom login page when user not logged in
        if ($variables['items'][0]['#href'] == 'user/login') {
          $variables['items'][0]['#href'] = 'login';
          if (isset($variables['items'][0]['#options']['query']['destination'])) {
            unset($variables['items'][0]['#options']['query']['destination']);
          }
        }
        break;
      case 'group unsubscribe':
        $variables['items'][0]['#title'] = 'x '.$variables['items'][0]['#title'];
        $variables['items'][0]['#prefix'] = '<p>'.t('You are an active member of this group.').'</p>';
        break;
    }
  }
}

/**
 * Implements hook_views_pre_render()
 */
function groups_pages_views_pre_render(&$view) {
  // override commons_contributor_groups view
  if ($view->name == 'commons_contributors_group') {
    // remove admin user (uid=1) from group member list
    $i = count($view->result) - 1;
    while ($i > -1) {
      if ($view->result[$i]->uid == 1) {
        unset($view->result[$i]);
      }
      $i--;
    }
  }
}

/**
 * Implements hook_preprocess_views_view_list().
 */
function groups_pages_preprocess_views_view_list(&$variables, $hook) {
  // Change the Contributors title in group contributors list to Members
  if ($variables['view']->name == 'commons_contributors_group' && !empty($variables['title']) && $variables['title'] == t('Contributors')) {
    $variables['title'] = t('Members');
  }
}