<?php	


/**
 * Implements hook_permission().
 */
function materio_user_permission() {
  return array(
    'view own user profile' =>  array(
      'title' => t('view own user profile'),
      'description' => t('view own user profile'),
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function materio_user_menu_alter(&$items) {
  $items['user/%user']['access callback'] = 'user_access';
  $items['user/%user']['access arguments'] = array('view own user profile');
}


/**
 * Implements hook_block_info().
 */
function materio_user_block_info() {
  $blocks['user_register'] = array(
    'info' => t('Register block'),
    'cache' => DRUPAL_NO_CACHE
  );
  $blocks['old_database_link'] = array(
    'info' => t('Old data base link'),
    'cache' => DRUPAL_NO_CACHE
  );
  $blocks['front_link'] = array(
    'info' => t('Front page link'),
    'cache' => DRUPAL_NO_CACHE
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function materio_user_block_view($delta = '') {
  global $user, $language;
  $block = array();
  switch ($delta) {
    case 'user_register':
      if(isset($user->roles[1])){
        $block['subject'] = '';//drupal_is_front_page() ? t('Your projects will born from here') : t('Create your materiO\' account');
        $block['content'] = '<h3>'. t('Login') . '</h3>';
        $block['content'] .= drupal_render(drupal_get_form('user_login'));
        $block['content'] .= '<h3>'. t('or create your materiO\' account') . '</h3>';
        $block['content'] .= drupal_render(drupal_get_form('user_register_form'));
        
        
        // $block['content'] .= l(t('Pricing'), 'node/11187', array('attributes' => array('class' => 'pricing'),));
      }
      break;
    case 'old_database_link':
      if( (isset($user->roles[6]) || isset($user->roles[8])) && $user->created < strtotime('01-12-2012') ){
        // dsm($user, 'user');
        $block['subject'] = '';
        
        $path = 'http://base.materio.com';
        
        if($language->language == 'fr')
          $path .= '/index_fr.html';

        $block['content'] = l(t('Old database'), $path);
      }
      break;
    case 'front_link':
      $block['subject'] = '';
      $block['content'] = l('<i class="icon-home"></i>'.t('home'), '<front>', array('html'=>true));
      break;
  }
  return $block;
}


/**
 * Implements hook_form_alter().
 */
function materio_user_form_alter(&$form, &$form_state, $form_id) {
  // dsm($form_id);
  if( $form_id == "user_register_form" && !user_access('administer users') ){
    // dsm($form);
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#title'] = t('Password');
    
    $form['actions']['#type'] = "container";
    $form['actions']['submit']['#value'] = t('Join');

    // $form['termsofservices'] = array(
    //   '#type' => 'checkbox',
    //   '#title' => t('I accept') .' '. l(t('the materiO terms of services'), 'node/11183'),
    //   '#required' => true,
    // );

    $form['#submit'][] = "materio_user_user_register_form_submit";

  }
  if($form_id == "user_login" ){
    // dsm($form);
    
    $form['actions']['#type'] = "container";
    // $form['actions']['submit']['#value'] = t('Join');

    if( $_GET['q'] == 'node/11187' ){
      $form['#submit'][] = "materio_user_user_login_form_submit";  
    }

  }

  if( $form_id == "webform_client_form_11186" ){
    // dsm($form, '$form');
    $form['#validate'][] = "materio_user_webform_client_111186_validate";
  }
}

function materio_user_user_register_form_submit($form, &$form_state){
  // dsm($form, 'form');
  // dsm($form_state, 'form_state');
  // dsm($_REQUEST, '$_REQUEST');
  // dsm($_GET, '$_GET');

  unset($_REQUEST['destination'], $_REQUEST['edit']['destination']);

  $form_state['redirect'] = array(
    'node/11187',
    array(
      'fragment' => $_GET['q'] == 'node/11187' ? 'content-bottom' : '', // if we register from the membership page, then go directly to the form
    )
  );
  
  // $frontlink = l('continue with basic', '<front>');
  // // drupal_get_messages('status');
  // drupal_set_message(t('Welcome, you just join materiO\'! now you can choose the membership that\'s right for you, or !link', array('!link'=>$frontlink)));
}

function materio_user_user_login_form_submit($form, &$form_state){
  unset($_REQUEST['destination'], $_REQUEST['edit']['destination']);

  $form_state['redirect'] = array(
    'node/11187',
    array(
      'fragment' => 'content-bottom', // if we login from the membership page, then go directly to the form
    )
  );
}

function materio_user_webform_client_111186_validate($form, &$form_state){
  // dsm($form, 'form');
  // dsm($form_state, 'form_state');
  $values = $form_state['values']['submitted'];
  if ($values['membership_options'] == 3) {
    foreach ($values['collaborators'] as $coll_key => $coll) {
      foreach ($coll as $field_key => $field_value) {
        if($field_value == ''){
          $human_field_name = $form['submitted']['collaborators'][$coll_key]['#title'] . " : " . $form['submitted']['collaborators'][$coll_key][$field_key]['#title'];
          $field_name = 'submitted][collaborators]['.$coll_key.']['.$field_key;
          // dsm($field_name, 'field_name');

          form_set_error($field_name, t('You must provide a value for the !name field.', array('!name'=>$human_field_name)));      
        }
      }
    }
    

  } 

}
/**
 * Implements hook_help().
 */
function materio_user_help($path, $arg) {
  // dsm($path, 'path');
  // dsm($arg, 'arg');
  switch ($path) {
    case 'node/%':
      if($arg[1] == 11187 ){
        global $user;
        // dsm($user, 'user');
        
        if(isset($user->roles[1])){ // anonyme
          $message = t('Please create an account and join materio, then we\'ll provide you the membership form.');
          $content = '<p>' . $message . '</p>';
          return $content;
        }else if(isset($user->roles[2])){ // authentificated user (not utilisateur)
          $content = '<h2>' . t('Welcome, you just joined materiO\' !') . '</h2>';
          $frontlink = l(t('continue with basic'), '<front>');
          $message = t('Now you can choose the membership that\'s right for you, or !link', array('!link'=>$frontlink));
          $content .= '<p>' . $message . '</p>';
          return $content;
        }
      }
  }
}


/**
 * Implements hook_block_view_alter().
 */
function materio_user_block_view_alter(&$data, $block) {
  if( $block->module == "user" && $block->delta == 'login' && isset($data['subject']) ){
    // dsm($block, 'block');
    // dsm($data, 'data');
    $data['subject'] = '<i class="icon-user"></i>' . $data['subject'];
  }
}


/**
 * Define constants
 */
define('MATERIO_USER_CONFIRMED_USER_ROLE', 'Utilisateur'); // add role name here

/**
 * Implement hook_user
 */
function __materio_user_user_update(&$edit, $account, $category){
  // This is only fired when a user confirms their email address, logintoboggan style
  if (isset($account->logintoboggan_email_validated) && $account->logintoboggan_email_validated == TRUE) {    
    $confirmed_rid = materio_user_get_role_by_name(MATERIO_USER_CONFIRMED_USER_ROLE);    
    $roles = $account->roles + array($confirmed_rid => MATERIO_USER_CONFIRMED_USER_ROLE);
    
    // we have to do this to stop an infinite loop, and also to allow lower weighted modules to possibly do something here
    $user = $account;
    unset($user->logintoboggan_email_validated);
    
    user_save($user, array('roles' => $roles));

    drupal_go_to('user/'.$user->uid.'/edit');

  }
}

/**
 * Returns a role ID based on role name
 *
 * @param $name
 *  name of role to return
 * @return
 *  (int) Role ID
 */
function materio_user_get_role_by_name($name) {
  return array_search($name, user_roles());
} 

