<?php

/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Employee/User function handling
 *    Hooks into and customizes the native Drupal user handling forms and functions
*/

require_once('sabreQMS.utils.inc');


/*		sabreQMS_user_login()
 *   
 *    Overloads drupal hook_user_login()
 *
 *		Fires after user is logged in
*/
function sabreQMS_user_login(&$edit, $account) {
	if ( user_access('search view reports') ) {
		//$_GET['destination'] = 'reports/discrepancy_early_warning/first';
    $_GET['destination'] = 'reports/alerts';
	}
}



/*		sabreQMS_user_logout()
 *   
 *    Overloads drupal hook_user_logout()
 *
 *		Fires after user is being logged out		
*/
function sabreQMS_user_logout($account) {
	
	// clear user-specific search keys and results caches
	$dr_key_cache_name = 'QMS_discrepancy_search_key_' . $account->uid . '_' . $account->sid;
	$dr_results_cache_name = 'QMS_discrepancy_search_results_' . $account->uid . '_' . $account->sid;
	$dr_selected_cache_name = 'QMS_discrepancy_selected_' . $account->uid . '_' . $account->sid;
	$sl_key_cache_name = 'QMS_shiftlog_search_key_' . $account->uid . '_' . $account->sid;
	$sl_results_cache_name = 'QMS_shiftlog_search_results_' . $account->uid . '_' . $account->sid;
	$sl_selected_cache_name = 'QMS_shiftlog_selected_' . $account->uid . '_' . $account->sid;
	$eng_key_cache_name = 'QMS_engineering_search_key_' . $account->uid . '_' . $account->sid;
	$eng_results_cache_name = 'QMS_engineering_search_results_' . $account->uid . '_' . $account->sid;
	$eng_selected_cache_name = 'QMS_engineering_selected_' . $account->uid . '_' . $account->sid;
	$sd_key_cache_name = 'QMS_simulatordown_search_key_' . $account->uid . '_' . $account->sid;
	$sd_results_cache_name = 'QMS_simulatordown_search_results_' . $account->uid . '_' . $account->sid;
	
	
	cache_clear_all($dr_key_cache_name, 'cache', TRUE); 
	cache_clear_all($dr_results_cache_name, 'cache', TRUE); 
	cache_clear_all($dr_selected_cache_name, 'cache', TRUE); 
	cache_clear_all($sl_key_cache_name, 'cache', TRUE); 
	cache_clear_all($sl_results_cache_name, 'cache', TRUE); 
	cache_clear_all($sl_selected_cache_name, 'cache', TRUE); 
	cache_clear_all($eng_key_cache_name, 'cache', TRUE); 
	cache_clear_all($eng_results_cache_name, 'cache', TRUE); 
	cache_clear_all($eng_selected_cache_name, 'cache', TRUE); 
	cache_clear_all($sd_key_cache_name, 'cache', TRUE); 
	cache_clear_all($sd_results_cache_name, 'cache', TRUE); 

}



/*
 *		USER FORM ALTER FUNCTIONS
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Alter native drupal user(people) forms for our needs
 */


/*
 *		user_form_user_filter_form_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Removes the user filtering component on the admin/people page
 */
//function user_form_user_filter_form_alter(&$form, &$form_state, $form_id) {
	//drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.userlist.js');
	
	//$form['filters']['#access'] = False;		// hides + disables the filters
//}

/*
 *		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 sabreQMS_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.userlist.js');
	
	$form['cleanurls'] = array(
		'#type' => 'textfield',
		'#default_value' => variable_get('clean_url', 0),
		'#attributes' => array('class' => array('qms-hidden-field'), 'id' => 'qms-clean-url'),
	);
	
	
}

/*
 *		user_form_user_register_form_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional employee record fields to the user registration form (create user)
 */
function sabreQMS_form_user_register_form_alter(&$form, &$form_state, $form_id) {
		
		drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.user.js');
		
		$bEmployee = False;
		$bUser = False;
		$bCustomer = False;
		
		// get the parms differently if clean urls is enabled or not
		if ( variable_get('clean_url', 0) == 1 ) {
			// clean urls enabled
			$flag = arg(3);  // employee | user  | customer
			if ( $flag == 'employee') {
				$bEmployee = True;
			}
			else if ( $flag == 'customer') {
				$bCustomer = True;
			}
			else {
				$bUser = True;
			}
		}
		else {
			if ( (isset($_GET['employee'])) && ($_GET['employee'] == '1') ) {
				$bEmployee = True;
			}
			else if ( (isset($_GET['customer'])) && ($_GET['customer'] == '1') ) {
				$bCustomer = True;
			}
			else {
				$bUser = True;
			}
				
		}
		if ( $bEmployee ) {
			// creating an employee account (extra table entries)
			_add_employee_user_form_elements($form, $form_state, $form_id);	
		}
		else if ( $bCustomer ) {
			_add_customer_user_form_elements($form, $form_state, $form_id);
		}
		else {  
			// creating a regular user account without employee extras
			// remove 'employee' role option from Role checkbox group
			_add_nonemployee_user_form_elements($form, $form_state, $form_id);
		}
}

/*
 *		user_form_user_profile_form_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional employee record fields to the user profile form (edit user)
 */
function sabreQMS_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
		drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.useredit.js');
		
		$user = (object) Null;
		$user = $form['#user'];
		$user_id = $user->uid;
				
		if ( _user_is_customer($user_id) ) {
			_add_customer_user_form_elements($form, $form_state, $form_id);	
		}
		else if ( _user_is_employee($user_id) ) {
			_add_employee_user_form_elements($form, $form_state, $form_id);	
		}
		else {
			// creating a regular user account without employee extras
			// remove 'employee' role option from Role checkbox group
			_add_nonemployee_user_form_elements($form, $form_state, $form_id);
		}
}



/*
 *		user_form_user_admin_permissions_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional javascript to alter the form in the browser
 */
function sabreQMS_form_user_admin_permissions_alter(&$form, &$form_state, $form_id) {
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.userperms.js');
}

/*
 *		user_form_user_admin_roles_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional javascript to alter the form in the browser
 */
function sabreQMS_form_user_admin_roles_alter(&$form, &$form_state, $form_id) {
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.userroles.js');
	
}

/*
 *		user_form_user_admin_role_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 * 		Adds additional javascript to alter the form in the browser
 */
function sabreQMS_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:
		case 7:
		case 8:
			$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' => '&nbsp;&nbsp;&nbsp;' . l(t('Cancel'), 'admin/people/permissions/roles'),
	);
   * */
}


/*
 *		sabreQMS_form_user_login_block_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 *    Alters the user login block form
 *    
 */
function sabreQMS_form_user_login_block_alter(&$form, &$form_state) {
	_user_login_alter($form, $form_state);
	//echo "sabreQMS_form_user_login_block_alter<br/>";
}

/*
 *		sabreQMS_form_user_login_alter()
 *
 * 		overrides:  hook_form_FORM_ID_alter()
 *    Alters the user login regular form
 *    
 */
function sabreQMS_form_user_login_form_alter(&$form, &$form_state) {
	_user_login_alter($form, $form_state);
	//echo "sabreQMS_form_user_login_form_alter<br/>";
}


/*
 *		_user_login_alter()
 *
 *		Called by:
 * 			sabreQMS_form_user_login_block_alter()
 *			sabreQMS_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] = 'sabreQMS_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 sabreQMS_customer_validate($form, $form_state) {
	
	$user_id = isset($form_state['uid']) ? $form_state['uid'] : 0 ;
	
	
	//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_id > 0) && _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 . '>QMS Administrator</a>';
		}
		else {
			$msg = 'QMS Administrator.';
		}
		form_set_error('name',  $msg);
	}
	
}






/*
 *		sabreQMS_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 sabreQMS_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;
}


/*
 *		sabreQMS_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 sabreQMS_user_delete($account) {
	db_delete('qms_employees')
			->condition('user_id', $account->uid)
			->execute();
			
	db_delete('qms_customers_users')
			->condition('user_id', $account->uid)
			->execute();
			
	global $tech_list;
	$tech_list->reload();	
}


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

function _add_employee_user_form_elements(&$form, &$form_state, $form_id) {
			
	$form['first_name'] = array(
		'#type' => 'textfield',
		'#title' => t('First Name'),
		'#weight' => -30,
		'#maxlength' => 50,
		'#size' => 50,
	);
	
	$form['last_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Last Name'),
		'#weight' => -29,
		'#maxlength' => 50,
		'#size' => 50,
		'#required' => True,
	);

	// display adjustments for this element were added to the style sheet sabreQMS.css
	$form['receive_feedback'] = array(
		'#type' => 'checkbox',
		'#title' => t('Receive Feedback'),
		'#weight' => 5,
		'#prefix' => '',
		'#suffix' => '<div class="description qms-tech-desc">
									When checked, this user will receive emailed User Feedback response notifications.</div>',
	);	
	
	// remove 'customer' role from checkbox list	
	$key = array_search('customer', $form['account']['roles']['#options']);
	if ( $key !== False ) {
		unset($form['account']['roles']['#options'][$key]);
	}
  
  $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') . 
                            '"; return false;'),
	);
	
	/*
	$form['actions']['cancel_edit'] = array(
		'#markup' => '&nbsp;&nbsp;' . l(t('Cancel'), 'admin/people'),
	);*/
	
	$user = (object) NULL;
  $user_id = '';
	
	if ( isset($form_state['user']) ) {
		$user = $form_state['user'];
		$user_id = $user->uid;
	}
	
	$form['#validate'][] = 'sabreQMS_validate_employee_user';
	
	
	if ( $user_id > 0 ) {
		//editing existing user info
		
		$sql = 'SELECT first_name, last_name, full_name, receive_feedback FROM {qms_employees} e WHERE user_id = :uid';
		$results = db_query($sql, array(':uid' => $user->uid));
		
		if ( $results->rowCount() <> 0 ) {		
			$employee = $results->fetchObject();
		
			$form['first_name']['#default_value'] = $employee->first_name;
			$form['last_name']['#default_value'] = $employee->last_name;
			//$form['tech']['#default_value'] = $employee->tech;
			$form['receive_feedback']['#default_value'] = $employee->receive_feedback;
			
			// 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_employee_user_form_data_handler';
		}
		else {
			// 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_employee_user_form_data_handler';
		}
	}	
	else {
		// 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_employee_user_form_data_handler';
	}
	return $form;
}

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


/*
 * 	_add_customer_user_form_elements()
 *
 * 	Alter form elements to handle customer-only fields for adding/updating
 */

function _add_customer_user_form_elements(&$form, &$form_state, $form_id) {
	
	global $customer_list;
	$user = (object) NULL;
  $user_id = '';
	$customer_id = 0;
	
	if ( isset($form_state['user']) ) {
		$user = $form_state['user'];
		$user_id = $user->uid;
	}
	
	// find the 'customer' role
	$roles = user_roles($members_only = True);
	$customer_role_id = 4;
	$contractor_role_id = 8;
	
	//$cust_key = array_search('customer', $form['account']['roles']['#options']);
	$cust_key = isset($form['account']['roles']['#options'][$customer_role_id]) ? $customer_role_id : 0;
	
	// find the 'contractor' role if it exists in the system
	//$contractor_key = array_search('contractor', $form['account']['roles']['#options']);
	$contractor_key = isset($form['account']['roles']['#options'][$contractor_role_id]) ? $contractor_role_id : 0;
		
	if ( $cust_key ) {
		// found the customer role, save the key, but turn off all other role options
		// re-add the customer, and contractor role & default it

		foreach($form['account']['roles']['#options'] As $key => $value) {
			if (( $key != $contractor_key) && ( $key != $cust_key)) {
				unset($form['account']['roles']['#options'][$key]);
			}
		}
		
		// this won't work now as we cannot disable the checkbox array with 'contractors'
		// checkbox array has to have individ. elements disable after the fact (post-process)
		
		//$form['account']['roles'][$cust_key]['#disabled'] = True;
		$form['account']['roles']['#default_value'] = array($cust_key);
		
		// contractor is defined is the system, add as option and include in default_value if it has been assigned previously
		if ( $contractor_key ) {
			if ( isset($user->roles[$contractor_key]) ) {
				$form['account']['roles']['#default_value'][] = $contractor_key;
			}
		}
	}
	
	
	$results = db_query('SELECT customer_id FROM {qms_customers_users} WHERE user_id = :uid', 
												array(':uid' => $user_id));
	if ( $results->rowCount() ) {
		$customer_id = $results->fetchField();
	}
	
	$form['customer'] = array(
		'#type' => 'select',
		'#title' => t('User Affiliated with Customer'),
		'#options' => $customer_list->get_active(),
		'#default_value' => (($customer_id > 0) ? $customer_id : 0) ,
		'#required' => True,
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'qms-customer-select'),
	);
	
	/*
	$form['customer_role_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $cust_key,
		'#attributes' => array('id' => 'qms-customer-role-id',
													 'class' => array('qms-hidden-field')),
	);
	*/
	
	$form['#validate'][] = 'sabreQMS_validate_customer_user';
  
  $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') . 
                            '"; return false;'),
	);
	
  /*
	$form['actions']['cancel_edit'] = array(
		'#markup' => '&nbsp;&nbsp;' . l(t('Cancel'), 'admin/people'),
	);
   * 
   */
	
	// adds a custom submit handler to the form to save the non-employee data
	$form['#submit'][] = 'store_customer_user_form_data_handler';
	
	return $form;
}



/*
 * 	sabreQMS_validate_customer_user()
 *
 * 	Validates the additional customer user form elements
 */
function sabreQMS_validate_customer_user($form, $form_state) {
	if ( (int)$form_state['values']['customer'] == 0) {
		form_set_error('customer', t('Customer must be specified for Customer User Accounts.'));
	}
}



/*
 * 	_add_nonemployee_user_form_elements()
 *
 * 	Alter form elements to handle nonemployee fields for adding/updating
 */

function _add_nonemployee_user_form_elements(&$form, &$form_state, $form_id) {
	
	$employee_role_id = 5;
	$customer_role_id = 4;
	
	foreach( $form['account']['roles']['#options'] as $key => $role ) {
		switch ($key) {
			case $employee_role_id:
			case $customer_role_id:
				unset($form['account']['roles']['#options'][$key]);
				break;
			default:
		}
	}	
	/*
	$form['actions']['cancel_edit'] = array(
		'#markup' => '&nbsp;&nbsp;' . l(t('Cancel'), 'admin/people'),
	);*/
  
  $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') . 
                            '"; return false;'),
	);
	
	// adds a custom submit handler to the form to save the non-employee data
	$form['#submit'][] = 'store_nonemployee_user_form_data_handler';
	
	
	
	return $form;
}


/*
 * 	store_employee_user_form_data_handler()
 *
 * 	Handles storing the employee data into the employee db record
 */
function store_employee_user_form_data_handler(&$form, &$form_state) {
	
	$user = $form_state['user'];
	$employee = (object) NULL;
  
  $bSaved = False;
	
	
	$employee->first_name = $user->first_name;
	$employee->last_name = $user->last_name;
	//$employee->tech = $user->tech;
	$employee->receive_feedback = $user->receive_feedback;
	
	$employee->full_name = $employee->last_name;
	if ( $employee->first_name <> '' ) {
		$employee->full_name .= ', ' . $employee->first_name;
	}
	
	$employee->user_id = $user->uid;
	
	// find out if the employee 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 {qms_employees} e WHERE user_id = :uid';
	$results = db_query($sql, array(':uid' => $employee->user_id));
	
	if ( $results->rowCount() > 0 ) {
		// the employee record exists, store the updated data by key
		if ( False == drupal_write_record('qms_employees', $employee, 'user_id')) {
			$msg = "Oops!  Something went wrong updating the employee record.";
			drupal_set_message(t($msg));
    } else { $bSaved = True; }
	}
	else {
		// the employee record doesn't exist, store new
		if ( False == drupal_write_record('qms_employees', $employee)) {
			$msg = "Oops!  Something went wrong saving the new employee record.";
			drupal_set_message(t($msg));
		} else { $bSaved = True; }
	}
	
  if ($bSaved) {
    global $tech_list;
    $tech_list->reload();
  }
	
	drupal_goto('admin/people');
}



/*
 * 	store_nonemployee_user_form_data_handler()
 *
 * 	Handles storing the employee data into the employee db record
 *  For now, nothing special, other than routing after
 */
function store_nonemployee_user_form_data_handler(&$form, &$form_state) {
  global $tech_list;
  $tech_list->reload();
	drupal_goto('admin/people');
}

/*
 * 	store_customer_user_form_data_handler()
 *
 * 	Handles storing the customer-user linking data 
 */
function store_customer_user_form_data_handler(&$form, &$form_state) {
	
	//$form_state['values']['roles'][4] = 4;
	$user = $form_state['user'];
  $bSaved = False;
	
	$customer_user = (object) Null;
	$customer_user->customer_id = (int)$form_state['values']['customer'];
	$customer_user->user_id = $user->uid;
	
	// find out if the customer-user record exists	
	$sql = 'SELECT customers_users_id FROM {qms_customers_users} WHERE user_id = :uid';
	$results = db_query($sql, array(':uid' => $customer_user->user_id));
	
	if ( $results->rowCount() > 0 ) {
		// the customer-user record exists, store the updated data by key
		$customer_user->customers_users_id = $results->fetchField();
		
		if ( False == drupal_write_record('qms_customers_users', $customer_user, 'customers_users_id')) {
			$msg = "Oops!  Something went wrong updating the customer-user record.";
			drupal_set_message(t($msg));
    } else { $bSaved = True; }
	}
	else {
		// the customer-user link record doesn't exist, store new
		if ( False == drupal_write_record('qms_customers_users', $customer_user)) {
			$msg = "Oops!  Something went wrong saving the new customer-user record.";
			drupal_set_message(t($msg));
		} else { $bSaved = True; }
	}
  
  // often a customer is also a contractor and appears in the tech_list
  if ($bSaved) {
    global $tech_list;
    $tech_list->reload();
  }
	
	drupal_goto('admin/people');
}



