<?php
/**
 * Implementation of hook_menu().
 */

function ets_ui_element_info_alter(&$type) {

  // Remove client-side password validation for password confirmation.
  // (This is not recommended.)
  foreach ($type['password_confirm']['#process'] as $index => $processor) {
    if ($processor === 'user_form_process_password_confirm') {
      unset($type['password_confirm']['#process'][$index]);
    }
  }
}

function ets_ui_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['actions']['submit']['#value'] = t('Register');
  }
}

function ets_form_registration_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'event_registration_form_validate';  
}

// validation for registration
function event_registration_form_validate(&$form, &$form_state){
  if ($form_state['registration']->type=='registration_labs_2016' || $form_state['registration']->type=='registration_labs_2016_tech' ) {
    $error_messages='';

    // lab su cui ci si vuole prenotare
    $host_entity_reg_now = node_load($form['#entity']->entity_id);
    $nome_lab_now= $host_entity_reg_now->title;
    $eta_minima_lab_now= $host_entity_reg_now->field_eta_minima_klab['und'][0]['value'];
    $eta_massima_lab_now= $host_entity_reg_now->field_eta_massima_klab['und'][0]['value'];

    if ($host_entity_reg_now->field_giorno_klab['und'][0]['value']) {
      $gg_hh_inizio_string_now=$host_entity_reg_now->field_giorno_klab['und'][0]['value'];
    }else{
      $gg_hh_inizio_string_now='';
    }

    if ($host_entity_reg_now->field_giorno_klab['und'][0]['value2']) {
      $gg_hh_fine_string_now=$host_entity_reg_now->field_giorno_klab['und'][0]['value2'];
    }else{
      $gg_hh_fine_string_now='';
    } 

    // Get registrations for current user
    global $user;
    $query_reg_log = new EntityFieldQuery();
    $reg_for_logged_user = $query_reg_log
      ->entityCondition('entity_type', 'registration')
      ->propertyCondition('user_uid', $user->uid)
      ->propertyCondition('type', array('registration_labs_2016','registration_labs_2016_tech'),'IN')
      ->execute();

    if (!empty($reg_for_logged_user)) {
      $reg_data_for_logged_user = registration_load_multiple(
          array_keys($reg_for_logged_user['registration'])
        );

      $cerimonia_prenotata=false;
      $reg_lab_gia_prenotati_nomi = array();
      $reg_lab_gia_prenotati_orari_inizio = array();
      $reg_lab_gia_prenotati_orari_fine = array();
      foreach ($reg_data_for_logged_user as $reg_data) {
        $host_entity_reg = node_load($reg_data->entity_id);
        $nome_lab= $host_entity_reg->title;
        array_push($reg_lab_gia_prenotati_nomi, $nome_lab);

        if ($host_entity_reg->field_giorno_klab['und'][0]['value']) {
          $gg_hh_inizio_string=$host_entity_reg->field_giorno_klab['und'][0]['value'];
          //$gg_hh_inizio = date_parse($gg_hh_inizio_string);
        }else{
          $gg_hh_inizio_string='';
        }
        array_push($reg_lab_gia_prenotati_orari_inizio, $gg_hh_inizio_string);

        if ($host_entity_reg->field_giorno_klab['und'][0]['value2']) {
          $gg_hh_fine_string=$host_entity_reg->field_giorno_klab['und'][0]['value2'];
          //$gg_hh_fine = date_parse($gg_hh_fine_string);
        }else{
          $gg_hh_fine_string='';
        }  
        array_push($reg_lab_gia_prenotati_orari_fine, $gg_hh_fine_string);

        $reg_state_user=$reg_data->state; // complete or waitlist

        watchdog("ETS debug", "host_entity_reg: <pre>".print_r($host_entity_reg->nid,true)."</pre>", array(), WATCHDOG_NOTICE);
        if ($host_entity_reg->nid=='374') {
          $cerimonia_prenotata=true;
        }
      }
      $reg_number=count($reg_data_for_logged_user);
       watchdog("ETS debug", "host_entity_reg_now: <pre>".print_r($host_entity_reg_now->nid,true)."</pre>", array(), WATCHDOG_NOTICE);
      if ($host_entity_reg_now->nid=='374' || $cerimonia_prenotata) {
        $reg_number=$reg_number-1;
      }

      // VINCOLI PRENOTAZIONI
      // 1) no lab contemporanei (stesso giorno, stesso ora) 
      $i=0;
      $voleviii=false;
      for ($i=0; $i < count($reg_lab_gia_prenotati_orari_inizio) ; $i++) { 
        $inizio_lab_pr= strtotime($reg_lab_gia_prenotati_orari_inizio[$i]);
        $fine_lab_pr= strtotime($reg_lab_gia_prenotati_orari_fine[$i]);
        $inizio_lab_now= strtotime($gg_hh_inizio_string_now);
        $fine_lab_now= strtotime($gg_hh_fine_string_now);

        if ($inizio_lab_now < $fine_lab_pr && $fine_lab_now > $inizio_lab_pr) {
          $voleviii=true;
        }
        if ($host_entity_reg_now->nid==367) {
          // Lab cantarelli 3 gg
          $inizio_lab_due=strtotime('2016-10-27 17:00:00');
          $fine_lab_due=strtotime('2016-10-27 19:00:00');
          $inizio_lab_tre=strtotime('2016-10-28 16:00:00');
          $fine_lab_tre=strtotime('2016-10-28 18:00:00');

          if ($inizio_lab_due <= $fine_lab_pr && $fine_lab_due > $inizio_lab_pr) {
            $voleviii=true;
          }
          if ($inizio_lab_tre <= $fine_lab_pr && $fine_lab_tre > $inizio_lab_pr) {
            $voleviii=true;
          }
        }
      }
      if ($voleviii) {
        $error_messages .= "<p>Questo laboratorio si svolge contemporaneamente ad un'altro che hai già prenotato.</p>";
      }

      // 2) max 3 lab a persona $reg_number
      if ($reg_number>=3) {
        $error_messages .= "<p>Il numero massimo di laboratori a cui è possibile prenotarsi è tre.</p>";
      }
      // 3) max 1 lab per tipo $reg_lab_gia_prenotati
      if (in_array($nome_lab_now, $reg_lab_gia_prenotati_nomi)) {
        $error_messages .= "<p>Non puoi prenotarti per più di una volta allo stesso laboratorio.</p>";
      }
    }

    // 4) età compresa tra quelle permesse
    $account_data = user_load($user->uid);
    $dob = field_get_items('user', $account_data, 'field_dob');
    $dob=$dob[0]['value'];
    if ($dob) { 
      $bday = new DateTime($dob);
      $today = new DateTime(date('Y-m-d', time())); // for testing purposes
      $diff = $today->diff($bday);
      $age=$diff->y;
      //printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);

      if ($age>$eta_massima_lab_now || $age<$eta_minima_lab_now) {
        if ($eta_massima_lab_now==99) {
          $error_messages .= "<p>Il laboratorio è riservato ai maggiori di anni ".$eta_minima_lab_now .".</p>";
        }else{
          $error_messages .= "<p>Il laboratorio è riservato ai maggiori di anni ".$eta_minima_lab_now ." e minori di anni ".$eta_massima_lab_now.".</p>";
        }
      }
    }
    if (strlen($error_messages)>0) {
      form_set_error('form',$error_messages);
      
    }
  }
}

/* COMPLETE YOUR DATA - Additional step fill user data before registration */

function ets_ui_menu() {
  $items = array();
  $items['ets/add-user-data'] = array(
    'title'            => t('Completa il tuo profilo'),
    'page callback'    => 'ets_ui_add_user_data_before_registration',
    'page arguments'   => array(3),
    'access arguments' => array('perform experiments'),
    'type'             => MENU_CALLBACK,
  );
  return $items;
}

function ets_ui_add_user_data_before_registration() {
  
  $html='<div class="strict_mode_message">Completa il tuo profilo per procedere alla registrazione.<br></div>';

  module_load_include('inc', 'user', 'user.pages');

  global $user;  
  $user = user_load($user->uid);

  $form = drupal_get_form('user_profile_form', $user, 'account', 'add_data_mode','add_data_mode'); 

  $html=$html.drupal_render($form);

  return $html;
}

function ets_ui_form_user_profile_form_alter(&$form, &$form_state, $form_id){
  
  global $user;
  $node = node_load(arg(2));

  //modifies the form_user_profile in case we called it to fill empty fields in strict mode
  if(isset($form_state['build_info']['args'][3]) && $form_state['build_info']['args'][3] = 'add_data_mode'){

   // add a class to the form to do some styling
   $form['#attributes']['class'][] = 'strict_mode_form';

   //rename submit button
   $form['actions']['submit']['#value'] = t("Aggiorna il profilo e procedi alla registrazione");
   $form['#submit'][] = 'ets_ui_user_profile_form_submit';
   
   // let's hide some unwanted fields
   $form['actions']['cancel']['#access']=FALSE;
   $form['account']['#access']=FALSE;
   $form['username']['#access']=FALSE;
   $form['picture']['#access']=FALSE;   
   //$form['field_fullname']['#access']=FALSE;   
   $form['ckeditor']['#access']=FALSE;   
   
   $lang = $form['field_fullname']['#language'];
   $form['field_fullname']['#access']=TRUE;
   $form['field_fullname'][$lang]['#required']=TRUE;

   $lang = $form['field_language_sp']['#language'];
   $form['field_language_sp']['#suffix']=t('Scorri per scegliere ulteriori linguaggi');       
   $form['field_language_sp']['#access']=FALSE;
   $form['field_language_sp'][$lang]['#required']=TRUE;
   $form['field_language_sp'][$lang]['#default_value'] = array('Italian');

   array_unshift($form['#validate'], 'ets_ui_date_strict_validate');
   $lang = $form['field_dob']['#language'];
   $form['field_dob']['#access']=TRUE;
   $form['field_dob'][$lang]['#required']=TRUE;

   $lang = $form['field_education']['#language'];
   $form['field_education']['#access']=TRUE;
   $form['field_education'][$lang]['#required']=TRUE;

   $lang = $form['field_sex']['#language'];
   $form['field_sex']['#access']=TRUE;
   $form['field_sex'][$lang]['#required']=TRUE;    
  }
}

// *After* regular submit for authenticated user
function ets_ui_user_profile_form_submit($form, &$form_state) {
  drupal_goto('node/'.arg(2).'/register');
}

/*This is called by ets_form_alter in ets.module in case we are on strict mode user_profile_form*/
function ets_ui_hide_field_user_profile_form($form_element, &$form_state) {
  // hide some fields
  $form_element['locations']['#access']=FALSE;
  $form_element['locale']['#access']=FALSE;
  $form_element['timezone']['#access']=FALSE;
  $form_element['overlay_control']['#access']=FALSE;

  return $form_element;
}


function ets_ui_date_strict_validate ($form, &$form_state) {
  $lang = $form['field_dob']['#language'];
  $dob = $form_state['values']['field_dob'][$lang];
  foreach ($dob[0] as $key => $value) {
    if ($key=='value' && empty($value)){ 
      form_set_error('field_dob', t('Date of birth is required'));
    }
  }
}
/* END --- COMPLETE YOUR DATA */


/* BLOCK LOGIN KREYON DAY THEME */
function ets_ui_block_info() {
  $blocks['ets_ui_login'] = array(
    'info'  => 'Kreyon Day: User Menu',
    'cache' => DRUPAL_NO_CACHE,
  );  

  $blocks['ets_ui_hellobar'] = array(
    'info'  => 'Kreyon Day: Hellobar',
    'cache' => DRUPAL_NO_CACHE,
  );  

  return $blocks;
}

function ets_ui_block_view($delta) {
  $block = array();
  switch ($delta) {
    case 'ets_ui_login':
      $block = ets_ui_block_login();
      break;
    case 'ets_ui_hellobar':
      $block = ets_ui_block_hellobar();
      break;

  }
  return $block;
}

/* Block shows the "Login" and "Facebook connect" buttons only */
function ets_ui_block_login() {
  global $user;

  if ($user->uid==0) {
    return;
  }
  $destination = drupal_get_destination();

  /*$block['content'] = "<div class='login-button clearfix'><a href='http://www.kreyon.net/{$lang_name}/user?destination={$destination['destination']}' class='btn btn-success pull-right'>Login</a></div>";*/

  $block['content'] = "<div class='logout_profile_kday'>Benvenuto ".$user->name."! &nbsp;&nbsp;<a href='/it/user' class='user_menu_link_kday' target='blank'>Il tuo profilo</a> | <a href='/it/user/logout?destination=gestione-prenotazioni-2017' class='user_menu_link_kday'>Logout</a></div>";

  return $block;
}

function ets_ui_block_hellobar() {
  global $user;

  if ($user->uid==0) {
    return;
  }
  $destination = drupal_get_destination();

  /*$block['content'] = "<div class='login-button clearfix'><a href='http://www.kreyon.net/{$lang_name}/user?destination={$destination['destination']}' class='btn btn-success pull-right'>Login</a></div>";*/

  $block['content'] = "<div class='logout_profile_kday'>Benvenuto ".$user->name."!</div>";

  return $block;
}
/* END --- BLOCK LOGIN KREYON DAY THEME */