<?php

/*
 *	Simulator record functions for sabreQMS module
 */



/*
 *	customer_group_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays the form for adding/updating
 */

function customer_group_form($form, $form_state, $customer_id = 0, $group_id = 0) {

	if ( False == user_access('view manage menu') ) {
		drupal_goto('');
		return $form;	
  }

	$group = (object) Null;
	$group_user_list = array();
	$userlist = array();
	
	// all page-specific javascript loaded in the after_build function
	$form['#after_build'][] = 'customer_group_form_after_build';
	
	if ( $customer_id && !$group_id ) {
		$userlist = _get_customer_users($customer_id);
		$group = new stdClass();
	}
	else if ( $group_id  ) {   // Edit existing record
		
		$group = _get_customer_group($group_id);
		
		if ( $group == (object) Null ) {
	    drupal_set_message( t('Oops!  Something seems to have gone wrong.  Customer Group not found.'));
			drupal_goto('customer/edit/' . $customer_id);
			return;
	  }
	
		$userlist = _get_customer_users($customer_id);
		$group_user_list = _get_customer_group_users($group_id);
		
		$form['timestamp'] = array(
			'#markup' => _st_format_record_timestamp_table($group),
		);
	}	
	
	$form['group_name'] = array(
		'#type' => 'textfield',
		'#title' => t('User Group Name'),
		'#maxlength' => 50,
		'#default_value' => (($group_id > 0) ? $group->group_name : ''),
	);	
	
	$form['group_code'] = array(
		'#type' => 'textfield',
		'#title' => t('Group Code'),
		'#maxlength' => 5,
		'#size' => 5,
		'#required' => True,
		'#default_value' => ($group_id ? $group->group_code : ''),
		'#attributes' => array('id' => 'sch-group-code'),
	);	
	
	
	
	$form['group_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $group_id,
		'#attributes' => array('id' => 'sch-group-id',
													 'class' => array('qms-hidden')),
	);	
	
	$form['customer_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $customer_id,
		'#attributes' => array('id' => 'sch-customer-id',
													 'class' => array('qms-hidden')),
	);	
	
	
	//----------- build the user list table for this user group -----------------
	
	$user_table = _format_customer_group_users_table($group_user_list, (($group_id > 0) ? 'EDIT':'ADD'));
	
	
	$form['fs_users'] = array(
		'#type' => 'fieldset',
		'#title' => 'Users Assigned to Group',
	);


	$form['fs_users']['users'] = array(
		'#markup' => $user_table,
	);

	// turn database results array into an assoc array by user_id
	// needs to be in the same format as the UserList
	$user_select_list = array(0 => '- Select -');
	if ( isset($group_user_list) ) {	
		foreach($userlist as $u) {
				$user_select_list[$u->user_id] = $u->full_name;
		}
	}
	
	
	$assigned_user_list = array();
	if ( isset($group_user_list) ) {
		foreach($group_user_list as $u) {
				$assigned_user_list[$u->user_id] = $u->full_name;
		}
		$user_select_list = array_diff($user_select_list, $assigned_user_list);
	}
	
	

	$form['fs_users']['user_select'] = array(
		'#type' => 'select',
		'#title' => t('Add User'),
		'#options' => $user_select_list,
		'#default_value' => 0,
		'#attributes' => array('id' => 'qms-user-select',			
													 'class' => array('qms-select')),  // this is necessary for CKEditor functions
		// putting this in a 1x1 table for consistency
		'#prefix' => '<table class="qms-plain-table"><tr style="vertical-align:bottom;"><td style="width:35%">',
		'#suffix' => '</td>',
	);
	
	$form['fs_users']['add_user'] = array(
		'#type' => 'button',
		'#value' => t('Add'),
		'#attributes' => array('id' => 'qms-btn-add-user',
													 'qms-url' => (( $group_id > 0 ) ? 
																url('group/user/add') : 
																url('group/user/refresh')) ),
		'#prefix' => '<td><div class="qms-actions">',
		
	);
  $form['fs_users']['clear_user'] = array(
		'#type' => 'button',
		'#value' => t('Clear'),
		'#attributes' => array('class' => array('qms-btn-clear'),
                           'id' => 'qms-btn-clear-selection'), 
    '#suffix' => '</div></td></tr></table>',
                           
	);
  
	
	if ( !$group_id ) {  // storage field for new user group, adding users
		// need to wrap this in a hidden div since the textarea seems to want to display the grabber bar
		$form['fs_users']['users_to_add'] = array(
			'#type' => 'textarea',
			'#default_value' => '',
			'#prefix' => '<div id="qms-users-hidden" class="qms-hidden-field">',
			'#attributes' => array('id' => 'qms-users-to-add'),
		);
	}
	
	// storage area for dynamic dialog elements
	$form['popup_dialog'] = array(
		'#type' => 'markup',
		'#markup' => '<div id="qms-message-box"></div>',
	);
	
	

	
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
		'#attributes' => array('id' => 'qms-btn-submit'),
	);
	
	global $base_url;
  
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url('customer/edit/' . $customer_id) . '"; return false;'),
    '#suffix' => '<span id="qms-waiting"><img class="qms-waiting-img" src="' . 
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>'
	);
	
		
	// storage area for dynamic dialog element
	$form['popup_dialog'] = array(
		'#markup' => '<div id="qms-message-box"></div>',
	);
	

	return $form;
}

/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it. 
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/

/* 
 * customer_group_form_after_build()
 *
 */
function customer_group_form_after_build($form, &$form_state)
{
	drupal_add_library('system','ui.dialog');
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	$sabreScheduler = drupal_get_path('module', 'sabreScheduler');
	
	if ( (int)$form['group_id']['#default_value'] == 0) {
		drupal_add_js($sabreScheduler . '/js/sabreScheduler.groupadd.js');
	}
	else {
		drupal_add_js($sabreScheduler . '/js/sabreScheduler.groupedit.js');
	}

	return $form;
}



/*
 *	customer_group_form_validate()  
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates form after it is submitted
 */

function customer_group_form_validate($form, $form_state) {
	if ( trim($form_state['values']['group_name']) == '' ) {
		form_set_error('group_name', t('User Group Name is a required field'));
	}
	if ( trim($form_state['values']['group_name']) == '' ) {
		form_set_error('group_code', t('User Group Code is a required field'));
	}
}

/*
 *	simulator_form_submit()  
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves form data upon successful submit
 */

function customer_group_form_submit($form, $form_state) {
	
	global $user;
	$group = new stdClass();
	$group->group_id = (int) $form_state['values']['group_id'];
	$group->customer_id = (int) $form_state['values']['customer_id'];
	$group->group_name = Trim($form_state['values']['group_name']);
	$group->group_code = Trim($form_state['values']['group_code']);
	
	

	if  ( $group->group_id == 0 )  {  
		// new record
		$group->created_date = REQUEST_TIME;
		$group->created_by_user = $user->uid;
		
		$users_to_add = Trim($form_state['values']['users_to_add']);
		$userlist = explode('|', $users_to_add);
		
		
		if ( False == drupal_write_record('sch_groups', $group)) {
			$msg = "Oops!  Something went wrong saving the new user group record to the database.";
			drupal_set_message(t($msg));
		}
		
		// add the group's users
		if ( isset($userlist) ) {
			$group_user = new stdClass();
			$group_user->group_id = $group->group_id;
			$group_user->user_id = 0;
		
			foreach( $userlist as $u ) {
				$user_rec = explode('=', $u);
				if ( isset($user_rec[1]) ) {
					$group_user->user_id = $user_rec[1];
					drupal_write_record('sch_groups_users', $group_user);
				}

				unset($group_user->groups_users_id);
			}
		}
		
	}
	else {
		// update existing
		$group->updated_date = REQUEST_TIME;
		$group->updated_by_user = $user->uid;
		
		if ( False == drupal_write_record('sch_groups', $group, 'group_id')) {
			$msg = "Oops!  Something went wrong updating the user group record.";
			drupal_set_message(t($msg));
		}
		// assigned users are handled in separate ajax callbacks for editing user groups
	}
	CustomerList::clear();
	drupal_goto('customers/edit/' . $group->customer_id);
}

/*
 *	customer_group_delete_confirm()  
 *
 *	Validate and Ask for confirmation before deleting record
 */

function customer_group_delete_confirm($form, $form_state, $customer_id, $group_id) {
	
	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized Access.  Permission is required.'));
		drupal_goto('customers');
		return $form;	
  }
	
	$group = _get_customer_group($group_id);
	
	if ( $group->group_name == "" ) {
    drupal_set_message( t('Oops!  Group not found.'));
		drupal_goto('customer/edit/' . $customer_id);
		return;
  }
	
	$form['group_id'] = array(
		'#type' => 'value',
		'#value' => $group_id,
	);
	
	$form['customer_id'] = array(
		'#type' => 'value',
		'#value' => $customer_id,
	);
	
	
	$form['group_name'] = array(
		'#type' => 'value',
		'#value' => $group->group_name,
	);
	
	$title = t('Delete Group');
	$goto_if_canceled = 'customer/edit/' . $customer_id;
	$question = t('You are about to delete the group record, <br /><br /><b>' . $group->group_name . 
								'</b><br /><br />Are you sure?  This action cannot be undone.');
	$yes_btn = 	t('Delete');
	$no_btn = t('Cancel');

	return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);	
}

/*
 *	customer_group_delete_confirm_submit()  
 *
 *	Submit after confirmation, delete the specified record
 */

function customer_group_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$group_id = (int)$form_state['values']['group_id'];
		$customer_id = (int)$form_state['values']['customer_id'];
		$group_name = $form_state['values']['group_name'];
			
	
		// delete from database
		$num_rows = db_delete('sch_groups')
								->condition('group_id', $group_id, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows != 1 ) {
			$msg = 'Oops!  Unable to delete record for ' . $group_name . '.';
			drupal_set_message(t($msg));
			drupal_goto('customers/edit/' . $customer_id);
			return;
		}
		
		// delete group's user links
		db_delete('sch_groups_users')
							->condition('group_id', $group_id, '=')
							->execute();
				
		$msg = 'User Group record, ' . $group_name . ' has been deleted.';

		drupal_set_message(t($msg));
	}
	CustomerList::clear();
	drupal_goto('customer/edit/' . $customer_id);
}


/*
 *  customer_group_add_user_callback()
 *
 *	AJAX Callback Function
 *
 */
function customer_group_add_user_callback() {
	
	try {
		global $user;
		$content = "";
		$group_user_list = array();
		$group_id = ( isset($_POST['group_id'])  ? (int)$_POST['group_id'] : 0 );
		$user_id = ( isset($_POST['user_id'])  ? (int)$_POST['user_id'] : 0 );

		if ( ($group_id > 0) && ($user_id > 0) ) {
			$query = db_insert('sch_groups_users')
							 	->fields(array('group_id', 'user_id'))
		  					->values(array(
													'group_id' => $group_id,
													'user_id' => $user_id,
												))
								->execute();
							
				db_update('sch_groups')
									->fields(array(
											'updated_date' => REQUEST_TIME,
											'updated_by_user' => $user->uid,
										))
									->condition('group_id', $group_id)
									->execute();
		
						
			$group_user_list = _get_customer_group_users($group_id);					
		}
		$content = _format_customer_group_users_table($group_user_list, "EDIT"); 	
		die($content);
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, 'customer_group_add_user_callback() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}

/*
 *  customer_group_remove_user_callback()
 *
 *	AJAX Callback Function
 *
 */
function customer_group_remove_user_callback($user_id) {
	
	try{
		$content = "";
		$group_user_list = array();
		global $user;

		$group_id = ( isset($_POST['group_id'])  ? (int)$_POST['group_id'] : 0 );

		if ( ($group_id ) && ($user_id ) ) {
			// delete group's user links
			db_delete('sch_groups_users')
								->condition('group_id', $group_id )
								->condition('user_id', $user_id )
								->execute();
								
			db_update('sch_groups')
								->fields(array(
										'updated_date' => REQUEST_TIME,
										'updated_by_user' => $user->uid,
									))
								->condition('group_id', $group_id)
								->execute();
			

			$group_user_list = _get_customer_group_users($group_id);	
			$content = _format_customer_group_users_table($group_user_list, "EDIT"); 			
		}

		die($content);
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, 'customer_group_remove_user_callback() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}


/*
 *  customer_group_remove_user_callback()
 *
 *	AJAX Callback Function
 *  Reformats and redisplays user table without links to the user group which has not been added yet
 *
 */
function customer_group_user_table_refresh_callback() {
	
	// break user id list into individual records
	$ul = trim($_POST['user_list']);
	$group_user_list = array();
	$user_row_data = array();

	
	if ( strlen($ul) > 0 ) {
		$group_user_list = explode('|', $ul);
		//asort($group_user_list);
	}
	else {  // only one in the list
		$group_user_list = $ul;
	}
	
	
	$content = _format_customer_group_users_table($group_user_list, 'ADD'); 					
	
	die($content);
}

/*
 *  _format_customer_group_users_table()
 *
 *	accepts the  user group list and formats it/themes it into a table
 *
 */

function _format_customer_group_users_table($group_user_list, $mode = 'EDIT') {
	
	$content = "";
	$user_row_data = array();
	
	$i = 0;
	if ( isset($group_user_list) ) 
	{
		foreach($group_user_list as $u) {
		
			if ( $mode == 'ADD') {
				$user_info = explode('=', $u);
				$link_options = l( t('Remove'), "",  array('attributes' => array('class' => 'qms-user-remove', 'row' => $i) ) );
				$user_row_data[$i] = array('data' => array( $user_info[0], $link_options));
			}
			else {  // EDIT
				$row = array(
					$u->full_name,
					l( t('Remove'), "group/user/remove/" . $u->user_id, 
									array('attributes' => array('class' => 'qms-user-remove', 'row' => $i, 'username' => $u->full_name) ) ),
				);
				$user_row_data[] = array( 'data' => $row );	
			}
			$i++;
		}	
	}

	// rebuild table
	$content = '<div id="qms-users-div">';
	
	$content .= theme( 'table', array(
		'header' => array(array('data' => 'Users', 'class' => 'qms-user-group-tbl-col1'), 
											array('data' => 'Admin')),
		'rows' => $user_row_data,
		'empty' => t('None'),
	));
	
	$content .= '</div>';
	
	return $content;
}


/*
 *  _get_customer_group($group_id = 0)
 *
 *	Returns the Group info
 *
 */

function _get_customer_group($group_id = 0) {
	
	try{
		$group = (object) Null;
	
		if ( $group_id ) {
			// get the record
			$sql = "SELECT g.group_id, g.group_name, g.group_code, g.customer_id, c.customer, 
									   g.created_date, g.created_by_user, g.updated_date, g.updated_by_user 
							FROM {sch_groups} g, {sch_customers} c 
							WHERE g.group_id = :gid 
							AND   g.customer_id = c.customer_id";
			$result = db_query($sql, array(':gid' => $group_id));

			if ( $result->rowCount() ) {
				$group = $result->fetchObject();
			}
		}

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

}
	
	
/*
 *  _get_customer_group_users($group_id = 0)
 *
 *	Returns the User Group users list
 *
 */

function _get_customer_group_users($group_id = 0, $bConCat = False) {
	
	try{
		
	
		if ( $group_id ) {
			$group_users = array();
			
			if ( !$bConCat ) {
				// get the record
				$sql = "SELECT su.user_id, su.full_name
								FROM   {sch_groups_users} gu, {sch_users} su 
								WHERE  gu.group_id = :gid 
								AND		 gu.user_id = su.user_id 
								ORDER BY su.full_name ASC";
				$result = db_query($sql, array(':gid' => $group_id));

				if ( $result->rowCount() ) {
					$group_users = $result->fetchAll();
				}
			}
			else {
				$group_users = '';
				$sql = "SELECT group_concat(su.full_name separator '; ') AS `group_users` 
								FROM {sch_groups_users} gu, {sch_users} su 
								WHERE gu.group_id = :gid 
								AND   gu.user_id = su.user_id";		
												
				$result = db_query($sql, array(':gid' => $group_id));

				if ( $result->rowCount() ) {
					$group_users = $result->fetchField();
				}
			}
		}

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




