<?php

/**
 * Drupal Module: User Relationship Invites
 *
 * @author Jeff Smick <sprsquish [at] gmail [dot] com>
 * @author Jeff Warrington <jeff [at] qoolio [dot] org (Drupal 6 port)>
 * @author Chris Muktar <chrism2671 chris [at] wikijob [dot] co [dot] uk> Upgrade D7 to support Invite 4.x
 * Invite 4.x limitation - currently applies to all invite types.
 * @file
 *   Automatically create a relationship between inviter and invitee
 */

/**
 * Public API to grab the basic invite info
 *
 * @param $code
 *    string of the invite code
 *
 * @return
 *    object with the invite data including the inviter user object and relationship_type object
 */
function user_relationship_invites_get_invite($code) {
  if ($invite = db_query("SELECT * FROM {user_relationship_invites} WHERE invite_code = :code", array(':code' => $code))->fetchObject()) {
    $invite->inviter = user_load($invite->inviter_uid);
    $invite->relationship_type = user_relationships_type_load($invite->rtid);
  }

  return $invite;
}

/**
 * Implements hook_form_alter().
 */
function user_relationship_invites_form_invite_form_alter(&$form, $form_state) {
  global $user;
  $new_user = drupal_anonymous_user();
  // Allow all user relationships for this user. Permission checks will be done
  // later.
  $new_user->user_relationships_allow_all = TRUE;
  module_load_include('inc', 'user_relationships_ui', 'user_relationships_ui.forms');
  $form += user_relationships_ui_request_form($user, $new_user, isset($form_state['values']) ? $form_state['values'] : array());
  if (isset($form['rtid'])) {
    $form['ur_request'] = array(
      '#type' => 'checkbox',
      '#title' => t('Request relationship'),
      '#weight' => -1,
      '#default_value' => 1,
    );
    $form['rtid']['#weight'] = 0;
    // Only show rtid if ur_request is checked.
    $form['rtid']['#states'] = array(
      'visible' => array(
        ':input[name=ur_request]' => array('checked' => TRUE),
      ),
    );
    $form['#validate'][] = 'user_relationship_invites_invite_form_validate';
  }
}

/**
 * Custom form validation handler for the 'invite_form' form from Invite module
 * This custom handler acts to store the User Relationships relationship type ID
 * so that it can be used in the hook_invite implementation as it is not otherwise available.
 * Also, adds a relationship action link if the user already exists.
 */
function user_relationship_invites_invite_form_validate($form, &$form_state) {
  global $user;
  if (!empty($form_state['values']['rtid']) && $form_state['values']['ur_request']) {
    $user->rtid = $form_state['values']['rtid'];

    switch (_user_relationship_invites_version()) {
      case 2:
        $emails = _invite_get_emails($form_state['values']['email']);
        if ($failed_emails = _invite_filter_registered_emails($emails)) {
          foreach ($failed_emails as $email) {
            $account = user_load_by_mail($email);
            if ($actions = user_relationships_ui_actions_between($user, $account, array('add' => 1, 'requested' => 1, 'received' => 1))) {
              drupal_set_message(theme('item_list', array('items' => $actions)), 'error');
            }
          }
        }
        break;

      case 4:
        if ($form_state['invite']->type == 'invite_by_email') {
          $invitee = user_load_by_mail($form_state['values']['field_invitation_email_address']['und'][0]['value']);

          if ($invitee && $invitee->status == 1) {
            // This is an existing, non-blocked user, identified by email address. Create relationship request.
            user_relationships_request_relationship($user, $invitee, $form_state['values']['rtid'], FALSE);
          }
        }
        break;
    }
  }
  else {
    unset($form_state['values']['rtid']);
    unset($form_state['values']['requestor']);
    unset($form_state['values']['requestee']);
  }
}

/**
 * Implements hook_invite_send().
 */
function user_relationship_invites_invite_send($invite) {
  global $user;
  if (!empty($user->rtid)) {
    db_insert('user_relationship_invites')
      ->fields(array(
        'inviter_uid' => $invite->uid,
        'rtid' => $user->rtid,
        'invite_code' => $invite->reg_code,
      ))
      ->execute();
  }
}

/**
 * Implements hook_user().
 */
function user_relationship_invites_form_user_register_form_alter(&$form, &$form_state) {
  $session_var = (_user_relationship_invites_version() == 2)
    ? INVITE_SESSION
    : INVITE_SESSION_CODE;

  if (!empty($_SESSION[$session_var]) && ($code = $_SESSION[$session_var]) && ($invite = user_relationship_invites_get_invite($code)) && $invite->relationship_type) {

    $inviter = $invite->inviter;
    $relationship_type = $invite->relationship_type;

    // Approval is required so ask for it.
    if (!$relationship_type->is_oneway || $relationship_type->requires_approval) {
      $form['relationship_invite_approve'] = array(
        '#type' => 'radios',
        '#title' => t('Please confirm the @rel_name request from !name', array('!name' => theme('username', array('account' => $inviter))) + user_relationships_type_translations($relationship_type)),
        '#default_value' => 'approve',
        '#options' => array(
          'approve' => t('Yes'),
          'disapprove' => t('No'),
        ),
      );
    }
    // Otherwise force an approval.
    else {
      $form['relationship_invite_approve'] = array(
        '#type' => 'value',
        '#value' => 'approve',
      );
    }
    $form['invite_code'] = array(
      '#type' => 'value',
      '#value' => $code
    );
    $form['relationship_invite_requester'] = array(
      '#type' => 'value',
      '#value' => $inviter,
    );
    $form['relationship_type'] = array(
      '#type' => 'value',
      '#value' => $relationship_type,
    );
  }
}

function user_relationship_invites_user_insert(&$edit, $account, $category) {
  if (isset($edit['relationship_invite_approve'])) {

    db_delete('user_relationship_invites')
      ->condition('invite_code', $edit['invite_code'])
      ->execute();

    if (user_relationships_can_receive($account, $edit['relationship_type'])) {
      if ($edit['relationship_invite_approve'] == 'approve') {
        user_relationships_request_relationship($edit['relationship_invite_requester'], $account, $edit['relationship_type'], TRUE);
      }
    }
  }
}

/**
 * Get invite module version.
 *
 * @return integer
 *  - Version of invite module.
 */
function _user_relationship_invites_version() {
  $invite_module_info = system_get_info('module', 'invite');
  $version = substr($invite_module_info['version'], 4, 1);
  return $version;
}

/**
 * Implements hook_invite_accept().
 */
function user_relationship_invites_invite_accept($invite) {
  if ($ur_invite = user_relationship_invites_get_invite($invite->reg_code)) {
    db_delete('user_relationship_invites')
      ->condition('invite_code', $invite->reg_code)
      ->execute();
    $invitee = user_load($invite->invitee);
    if (user_relationships_can_receive($invitee, $ur_invite->relationship_type)) {
      user_relationships_request_relationship($invite->uid, $invitee, $ur_invite->relationship_type, TRUE);
    }
  }
}
