<?php
/**
 * @file
 * Code for the Groups Directory feature.
 */

include_once 'groups_directory.features.inc';

/**
 * Implements hook_block_info()
 */
function groups_directory_block_info() {
  $blocks['groups_directory_filter'] = array(
    'info' => t('Filter Groups'),
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['groups_directory_list'] = array(
    'info' => t('Groups directory list'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function groups_directory_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'groups_directory_filter':
      $block['content'] = drupal_get_form('groups_directory_filter_form');
      $block['subject'] = t('Filter Groups');
      break;
    case 'groups_directory_list':
      $element = groups_directory_list();
      $block['content'] = render($element);
      $block['subject'] = t('Groups');
      break;
  }
  return $block;
}

/**
 * Clean array helper, defaults to check_plain filter.
 *
 * @return array         Filtered array values.
 */
function _groups_directory_clean_array($array, $filter = 'check_plain') {
  $clean = array();
  foreach ($array as $key => $val) {
    if (is_array($val)) {
      $clean[$filter($key)] = _groups_directory_clean_array($val, $filter);
    }
    else {
      $clean[$filter($key)] = $filter($val);
    }
  }
  return $clean;
}

/**
 * Get query parameters using a check_plain filter on values.
 */
function _groups_directory_get_query_parameters() {
  $query_params = drupal_get_query_parameters();
  return _groups_directory_clean_array($query_params);
}

/**
 * Groups directory list callback.
 */
function groups_directory_list() {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'group')
    ->propertyCondition('status', NODE_PUBLISHED);
  $query_params = _groups_directory_get_query_parameters();
  // filter status
  if (isset($query_params['status'])) {
    $status_official = in_array('official', $query_params['status']);
    $status_new = in_array('new', $query_params['status']);
    if (($status_official) && (!$status_new)) {
      // show official groups only
      $query->fieldCondition('field_group_status', 'value', '1', '=');
    }
    if (($status_new) && (!$status_official)) {
      // show new groups only
      $query->fieldCondition('field_group_status', 'value', '1', '!=');
    }
  }
  // filter by continent
  if (isset($query_params['c'])) {
    $query->fieldCondition('field_group_location', 'continent', (array)$query_params['c']);
  }

  // order by title
  $query->fieldOrderBy('field_group_status', 'value', 'DESC');
  $query->propertyOrderBy('title', 'ASC');

  $result = $query->execute();
  if (isset($result['node'])) {
    $nids = array_keys($result['node']);
    $entities = entity_load('node', $nids);
    $contents = entity_view('node', $entities, 'teaser');
  } else {
    $contents = array(
      '#type' => 'markup',
      '#markup' => '<div class="results-empty">' . t('No results found.') . '</div>',
    );
  }
  return $contents;
}

/**
 * Groups filter form.
 */
function groups_directory_filter_form($form, &$form_state) {
  module_load_include('inc', 'field_group_location', 'field_group_lookup');
  $form['continents'] = array(
    '#type' => 'checkboxes',
    '#title' => t('By continent'),
    '#options' => _continent_get_predefined_list(),
  );
  $form['status'] = array(
    '#type' => 'checkboxes',
    '#title' => 'By status',
    '#options' => array(
      'official' => 'Official group',
      'new' => 'New group',
    ),
  );
  $form['submit_search'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#submit' => array('groups_directory_filter_form_submit'),
  );
  $form['submit_clear'] = array(
    '#type' => 'submit',
    '#value' => t('Clear filters'),
    '#submit' => array('groups_directory_filter_form_clear_filters'),
  );
  $query_params = _groups_directory_get_query_parameters();
  // set defaults for continents
  $continents = isset($query_params['c']) ? $query_params['c'] : NULL;
  if ((isset($continents)) && ((array)$continents == $continents)) {
    $form['continents']['#default_value'] = $continents;
  }
  // set defaults for status
  $status = isset($query_params['status']) ? $query_params['status'] : NULL;
  if ((isset($status)) && ((array)$status == $status)) {
    $form['status']['#default_value'] = $status;
  }
  return $form;
}

/**
 * Groups filter submit callback.
 *
 * @see groups_directory_filter_form
 */
function groups_directory_filter_form_submit($form, &$form_state) {
  $filter = array();
  $continents = array_filter($form_state['values']['continents']);
  foreach ($continents as $value) {
    $filter[] = 'c[]='.$value;
  }
  $status = array_filter($form_state['values']['status']);
  foreach ($status as $value) {
    $filter[] = 'status[]='.$value;
  }
  $url_params = implode('&', $filter);
  $path=$GLOBALS['base_url'].strtok($_SERVER["REQUEST_URI"],'?');
  if (!empty($url_params)) {
    $path .= '?'.$url_params;
  }
  drupal_goto($path);
}

/**
 * Groups filter clear filters callback.
 *
 * @see groups_directory_filter_form
 */
function groups_directory_filter_form_clear_filters($form, &$form_state) {
  $path=$GLOBALS['base_url'].strtok($_SERVER["REQUEST_URI"],'?');
  drupal_goto($path);
}