<?php

/**
 * Implements hook_privatemsg_name_lookup().
 */
function privatemsg_realname_privatemsg_name_lookup($string) {

  // First, check the unique version.
  if (preg_match('/\[user:(.+)\]/', $string, $match)) {
    $account = user_load_multiple(array(), array(variable_get('privatemsg_realname_unique_identifier', 'name') => trim($match[1])));
    $account = reset($account);
    if ($account && $account->uid) {
      $account->type = 'user';
      $account->recipient = $account->uid;
      return array($account);
    }
  }

  // Then try to look it up with the real name.
  $result = db_query('SELECT r.uid FROM {realname} r WHERE r.realname = :realname', array(':realname' => $string));
  $accounts = array();
  foreach ($result as $row) {
    if ($account = user_load($row->uid)) {
      $account->type = 'user';
      $account->recipient = $account->uid;
      $accounts[] = $account;
    }
  }
  return $accounts;
}

/**
 * Implements hook_theme().
 */
function privatemsg_realname_theme() {
  return array(
    'privatemsg_realname_username'  => array(
      'variables' => array('recipient' => NULL, 'options' => array()),
    ),
  );
}

/**
 * Implements hook_query_privatemsg_autocomplete_alter().
 */
function privatemsg_realname_query_privatemsg_autocomplete_alter(SelectQueryInterface $query) {
  $search = $query->getMetaData('arg_1');
  $names = $query->getMetaData('arg_2');

  // LEFT JOIN realname table, some users might not have a realname stored in
  // there.
  $alias = $query->leftJoin('realname', 'r', '%alias.uid = u.uid');

  // Either select users where the profile field name and value matches or the username.
  // This does replace the default where.

  $conditions = &$query->conditions();
  foreach ($conditions as $key => $condition) {
    // Figure out which is the condition that checks the username.
    if (isset($condition['field']) && is_string($condition['field']) && $condition['field'] == 'u.name') {
      // Update existing condition.
      if (variable_get('privatemsg_realname_search_username', TRUE)) {
        $condition['field'] = db_or()
          ->condition('r.realname', $search . '%', 'LIKE')
          ->condition('u.name', $search . '%', 'LIKE');
        //$condition['operator'] = NULL;
        $condition['value'] = array();
      }
      else {
        $condition['field'] = 'r.realname';
      }
      $conditions[$key] = $condition;
    }
  }

  if (!empty($names)) {
    // Exclude already existing realnames, but explicitly allow NULL.
    // r.realname is left joined and can be NULL => NULL NOT IN (...) => NOT (NULL) => NULL.
    $query->condition(db_or()
      ->condition($alias . '.realname', $names, 'NOT IN')
      ->isNull($alias . '.realname')
    );
  }
}

/**
 * Implements hook_privatemsg_recipient_info_alter().
 */
function privatemsg_realname_privatemsg_recipient_type_info_alter(&$recipients) {
  // Override format callback.
  $recipients['user']['format'] = 'privatemsg_realname_username';
}

/**
 * Used to theme and display user recipients.
 *
 * Wrapper for theme_username() with a few additional options.
 */
function theme_privatemsg_realname_username($variables) {
  $recipient = $variables['recipient'];
  $options = $variables['options'];
  if (!isset($recipient->uid)) {
    $recipient->uid = $recipient->recipient;
  }
  if (!empty($options['plain'])) {
    $name = strip_tags(format_username($recipient));
    if (!empty($options['unique'])) {
      $identifier = variable_get('privatemsg_realname_unique_identifier', 'name');
      $name .= ' [user: ' . $recipient->$identifier . ']';
    }
    return $name;
  }
  else {
    return theme('username', array('account' => $recipient));
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function privatemsg_realname_form_privatemsg_admin_settings_alter(&$form, &$form_state) {
  $form['realname'] = array(
    '#type' => 'fieldset',
    '#title' => t('Realname integration'),
    '#collapsed' => TRUE,
    '#collapsible' => TRUE,
    '#weight' => 25,
    '#group' => 'settings',
  );

  $form['realname']['privatemsg_realname_unique_identifier'] = array(
    '#type' => 'radios',
    '#title' => t('Field to use as a unique identifier'),
    '#description' => t('Real names are often not unique. Choose which field should be used as a unique identifier when sending private messages.'),
    '#default_value' => variable_get('privatemsg_realname_unique_identifier', 'name'),
    '#options' => array(
      'name' => t('Username'),
      'uid' => t('UID'),
      'mail' => t('E-mail'),
    ),
  );

  $form['realname']['privatemsg_realname_search_username'] = array(
    '#type' => 'checkbox',
    '#title' => t('Search usernames for autocomplete suggestions'),
    '#default_value' => variable_get('privatemsg_realname_search_username', TRUE),
  );
}
