<?php

/*
 *	User override functions for sabreScheduler module
 *
 */

require_once('sabreScheduler.customers.inc');


define('SCH_USER_ROLES_ADMIN', 3);
define('SCH_USER_ROLES_MANAGER', 6);



/*		sabreScheduler_user_login()
 *   
 *    Overloads drupal hook_user_login()
 *
 *		Fires after user is logged in
*/

// function sabreScheduler_user_login(&$edit, $account) {
// 	$_GET['destination'] = 'user/home';
// }



/*		sabreScheduler_user_logout()
 *   
 *    Overloads drupal hook_user_logout()
 *
 *		Fires after user is being logged out		
*/
function sabreScheduler_user_logout($account) {
	
	// clear user-specific search keys and results caches
	$ex_key_cache_name = _get_scheduler_cache_name(SCH_EXCEPTIONS_SEARCH_KEY);
	$ex_results_cache_name = _get_scheduler_cache_name(SCH_EXCEPTIONS_SEARCH_RESULTS);

	cache_clear_all($ex_key_cache_name, 'cache', TRUE); 
	cache_clear_all($ex_results_cache_name, 'cache', TRUE); 
}




/*
 *		user_form_user_admin_account_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Removes the user blocking component on the admin/people page, its unnecessary for our needs
 */
function sabreScheduler_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
	drupal_add_js('(function($) {
										Drupal.behaviors.schUserList = {
											attach: function(context, settings) {
												$("tr th:last-child", context).text("Admin");
											}
										}
									}(jQuery));', 'inline');
	
	// managers can administer user accounts but not the 'administrator' user accounts
	// filter out any users that are 'administrators'
	
	if ( user_access('administer sabreScheduler') == False ) {
		// get the list of role_ids and names. Roles can be renamed and we are searching for the role name
		// in order to suppress the user list for non-administrator scheduling managers.
		// do not display administrators or other manager accounts.  Managers can see their own accounts
		// administrator is always role_id = 3
		$roles = user_roles($members_only = True);
		$admin_id = 3;
		$mgr_id = 6;  // this should always be the case
		
		global $user;
	
		foreach ( $form['accounts']['#options'] as $id => $user_account ) {
		
			$found_admin = strpos($user_account['roles'], $roles[$admin_id]);
			$found_mgr = strpos($user_account['roles'], $roles[$mgr_id]);
			if ( ($found_admin !== False) || (($found_mgr !== False) && ($id != $user->uid) ) ) {
				// this account is an admin - remove from the user list display
				unset($form['accounts']['#options'][$id]);
			}
		}
	}
}






/*
 *		sabreScheduler_form_user_admin_permissions_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional javascript to alter the form in the browser
 */
function sabreScheduler_form_user_admin_permissions_alter(&$form, &$form_state, $form_id) {
	drupal_add_js('(function($) {
										Drupal.behaviors.schUserPerms = {
											attach: function(context, settings) {
												$("#page-title", context).text("User Permissions");
											}
										}
									}(jQuery));', 'inline');
}

/*
 *		sabreScheduler_form_user_admin_roles_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional javascript to alter the form in the browser
 */
function sabreScheduler_form_user_admin_roles_alter(&$form, &$form_state, $form_id) {
	drupal_add_js('(function($) {
										Drupal.behaviors.schUserRoles = {
											attach: function(context, settings) {
												$("#page-title", context).text("User Roles");
											}
										}
									}(jQuery));', 'inline');
}

/*
 *		sabreScheduler_form_user_admin_role_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional javascript to alter the form in the browser
 */
function sabreScheduler_form_user_admin_role_alter(&$form, &$form_state, $form_id) {
	$role_id = arg(5);
	
	switch ($role_id) {
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
			$form['actions']['delete'] = array();
	}
  
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url('admin/people/permissions/roles') . 
                            '"; return false;'),
	);
  /*
	$form['actions']['cancel'] = array(
		'#markup' => l(t('Cancel'), 'admin/people/permissions/roles'),
	);*/
}




/*
 *		sabreScheduler_form_user_login_block_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 *    Alters the user login block form
 *    
 */
function sabreScheduler_form_user_login_block_alter(&$form, &$form_state) {
	_user_login_alter($form, $form_state);
}

/*
 *		sabreScheduler_form_user_login_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 *    Alters the user login regular form
 *    
 */
function sabreScheduler_form_user_login_form_alter(&$form, &$form_state) {
	_user_login_alter($form, $form_state);
}


/*
 *		_user_login_alter()
 *
 *		Called by:
 * 			sabreScheduler_form_user_login_block_alter()
 *			sabreScheduler_form_user_login_alter()
 * 		Adds additional validation check for customer-users to validate that the customer is "Active"
 */
function _user_login_alter(&$form, &$form_state) {
	//echo "_user_login_alter<br />";
	// add custom validation function call
	// make sure 'user_login_final_validate() gets called last
	foreach($form['#validate'] as $key => $value) {
		if ( $value == 'user_login_final_validate' ) {
			$form['#validate'][$key] = 'sabreScheduler_customer_validate';
		}
	}
	$form['#validate'][] = 'user_login_final_validate';

}


/*
 *		customer_validate()
 *
 *		Checks if user is linked to a customer
 * 		Adds additional validation check for customer-users to validate that the customer is "Active"
 *		If customer is inactive, then all user accounts linked to that customer automatically handled as "Blocked"
 *	  but they keep their original status in the event the customer becomes active at a later date.
 *    
 */

function sabreScheduler_customer_validate($form, $form_state) {
	//$user_id = $form_state['uid'];
	//Test Message:
	//drupal_set_message( "user_id = " . $user_id);
	
	// check if user is linked to a customer.  If so, check if customer is ACTIVE
	// if customer is inactive, return form_set_error()
	
	/*
	if ( _user_is_inactive_customer($user_id) ) {
		$site_mail = variable_get('site_mail', '');
		$msg = 'This user account is inactive.  If this is incorrect, please contact the ';
		if ( strlen($site_mail) > 0 ) {
			$msg .= '<a href=mailto:' . $site_mail . '>Scheduler Administrator</a>';
		}
		else {
			$msg = 'Scheduler Administrator.';
		}
		form_set_error('name',  $msg);
	}
	*/
}




/*
 *		sabreScheduler_user_cancel_methods_alter()
 *
 * 		overrides:  hook_user_cancel_methods_alter()
 * 		Allows us to turn off cancellation options that do not apply to our QMS app
 *    and to optionally prevent the deletion of a user that has links to 
 *    QMS records elsewhere in the DB.  If the user has links, then the delete option
 *    won't appear, only cancellation will be allowed.
 */

function sabreScheduler_user_cancel_methods_alter(&$methods) {
	
	// always remove these --- not applicable to our needs
	unset($methods['user_cancel_block_unpublish']);
	unset($methods['user_cancel_reassign']);
	
	// grab the user id from the URL, because of Drupal's hook structure
	// only way we can access the user_id from this function
	//$user_id = arg(1);  
	
	// if user is linked to discrepancies, engineering logs, shift logs, etc.
	// don't allow the option of deleting.
	
	/*
	$sql = 'SELECT tech_user_id FROM {qms_discrepancy_log} q WHERE tech_user_id = :uid LIMIT 1';
	$results = db_query($sql, array(':uid' => $user_id));
	if ( $results->rowcount() > 0 ) {
		unset($methods['user_cancel_delete']);
		return;
	}
	
	$sql = 'SELECT tech_user_id FROM {qms_engineering} q WHERE tech_user_id = :uid LIMIT 1';
	$results = db_query($sql, array(':uid' => $user_id));
	if ( $results->rowcount() > 0 ) {
		unset($methods['user_cancel_delete']);
		return;
	}

	$sql = 'SELECT user_id FROM {qms_discrepancy_files} q WHERE user_id = :uid LIMIT 1';
	$results = db_query($sql, array(':uid' => $user_id));
	if ( $results->rowcount() > 0 ) {
		unset($methods['user_cancel_delete']);
		return;
	}
	
	$sql = 'SELECT employee_user_id FROM {qms_shift_log} q WHERE employee_user_id = :uid LIMIT 1';
	$results = db_query($sql, array(':uid' => $user_id));
	if ( $results->rowcount() > 0 ) {
		unset($methods['user_cancel_delete']);
		return;
	}

	$sql = 'SELECT employee_user_id FROM {qms_punch_clock} q WHERE employee_user_id = :uid LIMIT 1';
	$results = db_query($sql, array(':uid' => $user_id));
	if ( $results->rowcount() > 0 ) {
		unset($methods['user_cancel_delete']);
		return;
	}
	*/
	
	return $methods;
}


/*
 *		sabreScheduler_user_delete($account)
 *
 * 		overrides:  hook_user_delete($account);
 *		allows us to do additional tasks for a user eligible for deletion
 * 		for our purposes, we will also delete the user from the Employees table
 */

function sabreScheduler_user_delete($account) {
	db_delete('sch_users')
			->condition('user_id', $account->uid)
			->execute();
}


/*
 * 	_add_scheduler_user_form_elements()
 *
 * 	Add additional form elements to handle fields for adding/updating
 */

function _add_scheduler_user_form_elements(&$form, &$form_state, $form_id) {
	
	$roles = user_roles($members_only = True);
	
	$acct_user = (object) NULL;
  $acct_user_id = 0;
	$sch_user = (object) NULL;
	
//	$bAdmin = user_access('administer sabreScheduler');
//	$bMgr = user_access('view manage menu');
	
	if ( isset($form_state['user']) ) {
		$acct_user = $form_state['user'];
		$acct_user_id = $acct_user->uid;
	}
	
	if ( $acct_user_id > 0 ) {		//editing existing user info
		$sch_user = _get_scheduler_user($acct_user_id);
	}	
	
	if ( user_access('administer sabreScheduler') == False ) {
		// remove 'administrator' role from checkbox list	
		// get the list of roles, since 'administrator can be renamed and we are searching for the role name
		// in order to suppress the user list for non-administrator scheduling managers.
		// administrator is always role_id = 3
	
		$key = array_search($roles[SCH_USER_ROLES_ADMIN], $form['account']['roles']['#options']);
		if ( $key !== False ) {
			unset($form['account']['roles']['#options'][$key]);
		}
	
		if ( user_access('administer users') == True) {
      // allows for managing basic users only
      // cannot manage admins or managers (only admins can do that)
			global $user;
		
			// remove the 'manager' role option if the currently logged in user is editing anything but their own account
			if ( $acct_user_id != $user->uid ) {
				$key = array_search($roles[SCH_USER_ROLES_MANAGER], $form['account']['roles']['#options']);
				if ( $key !== False ) {
					unset($form['account']['roles']['#options'][$key]);
				}
			}
		}
	}
	
	if ( $acct_user_id ) {
		$form['timestamp'] = array(
			'#markup' => _st_format_record_timestamp_table($sch_user),
			'#weight' => -35,
		);
	}
			
	$form['first_name'] = array(
		'#type' => 'textfield',
		'#title' => t('First Name'),
		'#weight' => -30,
		'#maxlength' => 50,
		'#size' => 50,
		'#default_value' => (($acct_user_id > 0) ? $sch_user->first_name : ''),
	);
	
	$form['last_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Last Name'),
		'#weight' => -29,
		'#maxlength' => 50,
		'#size' => 50,
		'#required' => True,
		'#default_value' => (($acct_user_id > 0) ? $sch_user->last_name : ''),
	);
	
	$dest_link = ($acct_user_id ? 'user/' . $acct_user_id . '/edit' : 'admin/people/create');
	
	$form['customer'] = array(
		'#type' => 'select',
		'#title' => t('Company Affiliation'),
		'#options' => _get_customer_select_list($active_only = True),
		'#default_value' => (($acct_user_id > 0) ? $sch_user->customer_id : 0) ,
		'#required' => False,
		'#weight' => -29,
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'sch-user-customer-select'),
		'#prefix' => '<div class="sch-affiliation">',
		'#suffix' => '<span class="sch-user-add-customer">' . 
									l(t('Add Customer'), 'customer/add', array('query' => array('destination' => $dest_link))) . 
									'</span></div><br class="clearBoth" />',
	);
  
  $simulator_list = new SimulatorList();
  
  $form['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Link to Simulator'),
		'#options' => $simulator_list->getActive(),
		'#default_value' => (($acct_user_id > 0) ? $sch_user->simulator_id : 0) ,
		'#required' => False,
		'#weight' => -29,
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'sch-simulator-select'),
		'#prefix' => '<div class="sch-simulator">',
		'#suffix' => '<span class="sch-user-add-simulator">' . 
									l(t('Add Simulator'), 'simulator/add', 
                       array('query' => array('destination' => $dest_link))) . 
									'</span></div><br class="clearBoth" />',
	);
  
  //------------------------------
		
	$destination = drupal_get_destination();
	if( !strlen($destination['destination']) ||
			$destination['destination'] == current_path()) {
		$destination['destination'] = 'admin/people';
	}
	/*	
	$form['actions']['cancel'] = array(
		'#markup' => l(t('Cancel'), $destination['destination']),
	);
   * */
   
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url($destination['destination']) . 
                            '"; return false;'),
	);
	
	
	$form['#validate'][] = 'sabreScheduler_validate_user';
	
	
	
	// adds a custom submit handler to the form to save the employee data
	// gets called after all the other user handling functions have completed
	$form['#submit'][] = 'store_scheduler_user_form_data_handler';
	
	return $form;
}

/*
 * 	sabreScheduler_validate_user()
 *
 * 	Validates the additional employee user form elements
 */
function sabreScheduler_validate_user($form, $form_state) {
	if ( trim($form_state['values']['last_name']) == '') {
		form_set_error('last_name', t('Last name is a required field for User Accounts.'));
	}
}

/*
 * 	store_scheduler_user_form_data_handler()
 *
 * 	Handles storing the additional user fields in sch_users
 */
function store_scheduler_user_form_data_handler(&$form, &$form_state) {
	
	$user_data = $form_state['user'];  // user being created
	$sch_user = new stdClass();
	global $user;										// logged in admin or manager user
	
	
	$sch_user->first_name = $user_data->first_name;
	$sch_user->last_name = $user_data->last_name;
	$sch_user->customer_id = (int)$user_data->customer;
  $sch_user->simulator_id = (int)$user_data->simulator;
	
	$sch_user->full_name = $sch_user->last_name;
	if ( $sch_user->first_name <> '' ) {
		$sch_user->full_name .= ', ' . $sch_user->first_name;
	}
	
	$sch_user->user_id = $user_data->uid;
	
	// find out if the scheduler user record exists
	// there may be some cases of a user record without an employee record
	// typically won't happen, but we need to allow for it
	
	$sql = 'SELECT user_id FROM {sch_users} WHERE user_id = :uid';
	$results = db_query($sql, array(':uid' => $sch_user->user_id));
	
	if ( $results->rowCount() > 0 ) {
		$sch_user->updated_date = REQUEST_TIME;
		$sch_user->updated_by_user = $user->uid;
		
		// the user record exists, store the updated data by key
		if ( False == drupal_write_record('sch_users', $sch_user, 'user_id')) {
			$msg = "Oops!  Something went wrong updating the Scheduler user record.";
			drupal_set_message(t($msg));
		}
	}
	else {
		$sch_user->created_date = REQUEST_TIME;
		$sch_user->created_by_user = $user->uid;
		
		// the user record doesn't exist, store new
		if ( False == drupal_write_record('sch_users', $sch_user)) {
			$msg = "Oops!  Something went wrong saving the new user record.";
			drupal_set_message(t($msg));
		}
	}
	
	$destination = drupal_get_destination();
	if( !strlen($destination['destination']) ||
			$destination['destination'] == current_path()) {
		$destination['destination'] = 'admin/people';
	}
		
	drupal_goto($destination['destination']);
}


/*
 *		_get_scheduler_user($user_id)
 *
 *		Retrieves and returns the requested sch_users record
 */
function _get_scheduler_user($user_id) {

	try {
		
		$sch_user = (object) Null;
		
		if ( $user_id ) {

			$sql = 'SELECT first_name, last_name, full_name, customer_id, simulator_id, 
			 							 created_date, created_by_user, updated_date, updated_by_user 
							FROM {sch_users} WHERE user_id = :uid';
			$results = db_query($sql, array(':uid' => $user_id));

			if ( $results->rowCount() ) {
			  $sch_user = $results->fetchObject();
			}
			else {
				$sch_user = _get_empty_scheduler_user_record();
			}
		}
		else {
			$sch_user = _get_empty_scheduler_user_record();
		}
		return $sch_user;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_scheduler_user() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}

/*
 *		_get_empty_schedule_user_record
 */
function _get_empty_scheduler_user_record() {
	$sch_user = new StdClass();
	$sch_user->first_name = '';
	$sch_user->last_name = '';
	$sch_user->customer_id = 0;
  $sch_user->simulator_id = 0;
	$sch_user->created_date = 0;
	$sch_user->created_by_user = 0;
	$sch_user->updated_date = 0;
	$sch_user->updated_by_user = 0;
	return $sch_user;
}


/*
 * --------------------------------------------------------------------
 * -------- ALTER USER PROFILE & USER REGISTER FORMS --------------------------
 * --------------------------------------------------------------------
 * 

 */



/*
 *		sabreScheduler_form_user_register_form_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional record fields to the user registration form (create user)
 */
function sabreScheduler_form_user_register_form_alter(&$form, &$form_state, $form_id) {
		drupal_add_js('(function($) {
											Drupal.behaviors.schUserAdd = {
												attach: function(context, settings) {
													$("#page-title", context).text("Create User Account");
												}
											}
										}(jQuery));', 'inline');
    
    
    // Alter Email Handling
    
    $form['account']['mail']['#required'] = False;	
    $form['account']['mail']['#description'] = 
        t('A valid e-mail address is required for manager and administrator accounts only.') .  
        '<br />' .  
        t('The e-mail address is not made public and will only be used for system notifications.');
    
    /*
    for($i=0; $i<count($form['#validate']); $i++) {
      if ($form['#validate'][$i] == 'user_register_validate') {        
        $form['#validate'][$i]= 'sabreScheduler_user_register_validate';
        break;
      }
    }  
     * 
     */
    
    // this has to be the first item in the validation list
    // additional email validation, must come first
    array_unshift($form['#validate'], 'sabreScheduler_user_email_validate');
		
    // Add additional form elements
		_add_scheduler_user_form_elements($form, $form_state, $form_id);

}

/*
 *		sabreScheduler_form_user_profile_form_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional record fields to the user profile form (edit user)
 */
function sabreScheduler_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
		
		$user = (object) Null;
		$user = $form['#user'];
		$user_id = $user->uid;
    
    $form['account']['mail']['#required'] = False;	
    $form['account']['mail']['#description'] = 
        t('A valid e-mail address is required for manager and administrator accounts only.') .  
        '<br />' .  
        t('The e-mail address is not made public and will only be used for system notifications.');
    
    // this has to be the first item in the validation list
    // additional email validation, must come first
    array_unshift($form['#validate'], 'sabreScheduler_user_email_validate');
    
    /*
    for($i=0; $i<count($form['#validate']); $i++) {
      if ($form['#validate'][$i] == 'user_profile_form_validate') {        
        $form['#validate'][$i]= 'sabreScheduler_user_email_validate';
        break;
      }
    }   */        
				
		_add_scheduler_user_form_elements($form, $form_state, $form_id);
}



/*
 *	_get_user_simulator_id()  
 *
 *	get the simulator_id linked to the current user
 */
function _get_user_simulator_id() 
{
	try {
		
		$simulator_id = 0;
    global $user;
		
    $sql = "SELECT simulator_id FROM {sch_users} 
            WHERE user_id = :uid";
    $simulator_id = (int)db_query($sql, array(':uid' => $user->uid))
                            ->fetchField();

    return $simulator_id;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_user_simulator_id() ' . $e->getMessage(), 
              array(), WATCHDOG_ERROR);
	} 
}



/*
 * --------------------------------------------------------------------
 * -------- CUSTOM EMAIL VALIDATION HANDLING --------------------------
 * --------------------------------------------------------------------
 * 
 * Require and do standard email validation for Managers and Admins
 * 
 * Do NOT require emails for regular users (students or instructors)
 */

/*
 *    _random_num()
 * 
 *    generate random num to create complete unique email account
 */
/*
function _random_num($n=5) {
  return rand(0, pow(10, $n));
}*/

/*
function sabreScheduler_user_register_validate(&$form, &$form_state) 
{
  
  $roles = user_roles($members_only = True);

  
  if ($form_state['values']['mail'] == null) {
    
    $is_admin = ( 1 == (int)$form_state['values']['roles'][SCH_USER_ROLES_ADMIN]);
   
    $is_mgr = ( 1 == (int)$form_state['values']['roles'][SCH_USER_ROLES_MANAGER]);
    if ( $is_mgr || $is_admin ) {
      // this is an admin or a manager - require an email
      drupal_set_message(t('E-mail is required for administrator and manager accounts.'), 'error');
      return;
    }
    else {
      
      $nomail = 'no-email-' . REQUEST_TIME . '@nowhere.com';
      
      //$form['account']['mail']['#default_value'] = $nomail;
      $form['account']['mail']['#value'] = $nomail;
      $form['account']['mail']['#needs_validation'] = 0;
      $form_state['values']['mail'] = $nomail;
    }
  
  }
  
  // call the original validation -- 
  // NOT NECESSARY, this isn't replaced, just called before anything else
  //user_register_validate($form, $form_state);
   
}
 * */



          	          	
function sabreScheduler_user_email_validate(&$form, &$form_state) 
{
  $roles = user_roles($members_only = True);

  
  if ($form_state['values']['mail'] == null) {
    
    $is_admin = 
      ( SCH_USER_ROLES_ADMIN == (int)$form_state['values']['roles'][SCH_USER_ROLES_ADMIN]);
   
    $is_mgr = 
      ( SCH_USER_ROLES_MANAGER == (int)$form_state['values']['roles'][SCH_USER_ROLES_MANAGER]);
    
    if ( $is_mgr || $is_admin ) {
      // this is an admin or a manager - require an email
      drupal_set_message(t('E-mail is required for administrator and manager accounts.'), 'error');
    }
    else {
      
      $nomail = 'no-email-' . REQUEST_TIME . '@nowhere.com';
      
      //$form['account']['mail']['#default_value'] = $nomail;
      $form['account']['mail']['#value'] = $nomail;
      $form['account']['mail']['#needs_validation'] = 0;
      $form_state['values']['mail'] = $nomail;
    }
  
  }
  
  // call the original validation -- 
  // NOT NECESSARY, this isn't replaced, just called before anything else
  
  //user_profile_form_validate($form, $form_state);
   
}


