<?php

/**
 *		sabreScheduler Module for plugin to Drupal 7 Framework
 *
 *		Customers
*/

//require_once( drupal_get_path('module', 'sabreTools') . '/sabreScheduler.lib.inc' );


/*
 *	customer_display()
 *
 *	returns:  Displays table list of customers (Manager)
 *
 */

function customer_display() {
	
	try {
    
    if (user_access('view manage menu') == False) {
      drupal_goto('');
      return;
    }	
	
    $bEdit = user_access('edit settings');
	
		$table_header = array( 
			array( 'data' => t('Customer') ),
			array( 'data' => t('Code') ),
			array( 'data' => t('Users') ),
			array( 'data' => t('Groups') ),
			array( 'data' => t('Active?') ),
		);
    
    if ( $bEdit ) { $table_header[] = array( 'data' => t('Admin') ); }
	
		// Get list of customers
		$sql = "SELECT c.customer_id, c.customer, c.customer_code, c.active, 
            c.fill_color, c.font_color, 
									 (SELECT COUNT(*) FROM {sch_users} su WHERE su.customer_id = c.customer_id ) AS `user_count`,
									 (SELECT COUNT(*) FROM {sch_groups} g WHERE g.customer_id = c.customer_id ) AS `group_count` 
						FROM {sch_customers} c 
						ORDER BY c.customer";
		$result = db_query($sql);

		$i = 0;
		$table_rows = array();
	
		foreach ($result as $row) {
		
			$row_data = array(
				$row->customer,
        array( 'data' => $row->customer_code, 
               'style' => 'background-color:#' . $row->fill_color . 
                          '; color:#' . $row->font_color . 
                          '; border-color:#CCCCCC;' ),
				$row->user_count,
				$row->group_count,
				($row->active ? 'x' : ''),
			);
      if ( $bEdit ) { 
        $row_data[] = _st_generate_options('customer', $row->customer_id);
      }
		
			$table_rows[] = array('data' => $row_data	);
			$i++;
		}
	
    $content = '';
    
    if ( $bEdit ) {
      $content .= l( t('Add Customer'), 'customer/add', array('class' => array('qms-customer-add')) );
    }
	
		$content .= theme('table', array(
			'header' => $table_header,
			'rows' => $table_rows,
			'empty' => t('None'),
		));

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

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

function customer_form($form, $form_state, $customer_id = 0) {

	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Permission is required.'));
		drupal_goto('customers');
		return $form;
  }

	$customer = (object) Null;
	
	$destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'customers';
	}
  
  
	

	if ( $customer_id ) {   // Get the existing record
		
		$customer = _get_customer($customer_id);
		if ( $customer == (object) Null ) {
			drupal_set_message( t('Oops!  Something seems to have gone wrong.  Customer not found.'));
			drupal_goto($goto_url);
			return;
		}
		
		$form['timestamp'] = array(
			'#markup' => _st_format_record_timestamp_table($customer),
		);
	}
  	
	$form['customer_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Customer Name'),
		'#maxlength' => 100,
		'#required' => True,
		'#default_value' => ($customer_id ? $customer->customer : ''),
	);	
	
	$form['customer_code'] = array(
		'#type' => 'textfield',
		'#title' => t('Customer Code'),
		'#maxlength' => 5,
		'#size' => 5,
		'#required' => True,
		'#default_value' => ($customer_id ? $customer->customer_code : ''),
		'#attributes' => array('id' => 'sch-customer-code'),
    '#prefix' => '<div class="sch-customer-code-colors"><div id="sch-customer-code-div">',
    '#suffix' => '</div>',
	);	
  
  $form['fill_color'] = array(
    '#type' => 'jquery_colorpicker',
    '#title' => t('Fill Color'),
    '#default_value' => (!empty($customer->fill_color) ? $customer->fill_color : ''),
    '#attributes' => array('id' => 'sch-fill-color'),
    '#prefix' => '<div id="sch-fill-color-div">',
    '#suffix' => '</div>',
  );
  
  $form['font_color'] = array(
    '#type' => 'jquery_colorpicker',
    '#title' => t('Font Color'),
    '#default_value' => (!empty($customer->font_color) ? $customer->font_color : ''),
    '#attributes' => array('id' => 'sch-font-color'),
    '#prefix' => '<div id="sch-font-color-div">',
    '#suffix' => '</div></div><div class="clearBoth">&nbsp;</div>',
  );
	
		
	$form['customer_active'] = array(
		'#type' => 'checkbox',
		'#title' => t('Active?'),
		'#default_value' => ($customer_id ? $customer->active : 1),
		'#disabled' => ($customer_id ? False : True),
		'#suffix' => '<div class="qms-desc">Setting customer to inactive automatically blocks all linked user accounts</div>',
	);
  
  
		
	$form['customer_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $customer_id,
		'#attributes' => array('class' => array('qms-hidden')),
	);	

			
	if ( $customer_id ) {   // Edit existing record

		// ------------------- GET USER ACCOUNTS LINKED TO THIS CUSTOMER ---------------------
		
		$form['manage_users'] = array(
		 	'#markup' => '<h3><hr />' . t('Users') . '</h3>' . 
							 l(t('Manage Users'), 'admin/people', array('query' => array('destination' => 'customer/edit/' . $customer_id))) . 		
							 '&nbsp;&nbsp;&bull;&nbsp;&nbsp;' . 
							 l(t('Add New User'), 'admin/people/create', array('query' => array('destination' => 'customer/edit/' . $customer_id))),
		);
		
		$customer_users = _get_customer_users($customer_id);
		
		// there are users linked... add them to a table
		$table_header = array(
			array('data' => t('Linked Users')),
			array('data' => t('EMail')),
			array('data' => t('Active?'), 'class' => array('sch-users-tbl-active')),
			array('data' => t('Admin'), 'class' => array('sch-users-tbl-admin')),
		);
		$table_rows = array();
		$cu_table = '';
				
		
		if ( isset($customer_users) ) {
			foreach( $customer_users as $row) {
				$row_data = array(
					$row->full_name,
					l($row->mail, 'mailto:' . $row->mail),
					($row->status ? 'x' : ''),
					l(t('Edit'), 'user/' . $row->user_id . '/edit', array('query' => array('destination' => 'customer/edit/' . $customer_id))),
				);
			
				$table_rows[] = array( 'data' => $row_data );		
			}
		}
		
		$cu_table = theme( 'table', array(
			'header' => $table_header,
			'rows' => $table_rows,
			'empty' => t('None'),
		));
		
		$form['user_table'] = array(
		 	'#markup' => '<div id="qms-customer-users-div">' . $cu_table . '</div>',
		);
		
		
		// ------------------- GET GROUPS LINKED TO THIS CUSTOMER ---------------------

		$form['manage_groups'] = array(
		 	'#markup' => '<h3><hr />' . t('Groups') . '</h3>' . l(t('Add Group'), 'group/add/' . $customer_id),
		);
		
		$groups = _get_customer_groups($customer_id);

		// there are groups linked... add them to a table
		$table_header = array(
			array('data' => t('Linked Group')),
			array('data' => t('Code')),
			array('data' => t('Users Assigned')),
			array('data' => t('Admin'), 'class' => array('sch-groups-tbl-admin')),
		);
		$table_rows = array();
		$g_table = '';

		if ( isset($groups)  ) {
			foreach( $groups as $row ) {
				$group_users = _get_customer_group_users($row->group_id, True);
				
				$row_data = array(
					$row->group_name,
					$row->group_code,
					$group_users,
					l(t('Edit'), 'group/edit/' . $customer_id . '/' . $row->group_id, 
								array('attributes' => array('class' => array('qms-link-edit')))) . 
					l(t('Delete'), 'group/delete/' . $customer_id . '/' . $row->group_id, 
								array('attributes' => array('class' => array('qms-link-delete')))),
				);

				$table_rows[] = array( 'data' => $row_data );		
			}
		}

		$g_table .= theme( 'table', array(
			'header' => $table_header,
			'rows' => $table_rows,
			'empty' => t('None'),
		));

		$form['groups_table'] = array(
		 	'#markup' => '<div id="qms-groups-div">' . $g_table . '</div>',
		);
	}
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
	);
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url($goto_url) . '"; return false;'),
	);
//	$form['actions']['cancel'] = array(
//		'#markup' => l(t('Cancel'), $goto_url),
//	);
	

	return $form;
}




/*
 *	customer_form_validate()  
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates customer_form after it is submitted
 */

function customer_form_validate($form, $form_state) {
	if ( trim($form_state['values']['customer_name']) == '' ) {
		form_set_error('customer_name', t('Customer Name is a required field'));
	}
	
	$customer_id = (int)$form_state['values']['customer_id'];
	$code = $form_state['values']['customer_code'];
	
	if ( trim($code) == '' ) {
		form_set_error('customer_code', t('Customer Code is a required field'));
	}
	else if ( False == _is_customer_code_unique($customer_id, $code) ) {
		form_set_error('customer_code', t('Customer Code must be unique.  Another customer already uses this code.'));
	}
	
}

/*
 *	customer_form_submit()  
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves customer_form data upon successful submit
 */

function customer_form_submit($form, $form_state) {
	
	$customer = new stdClass();
	global $user;
	
	$customer_id = (int)$form_state['values']['customer_id'];
	$customer->customer = $form_state['values']['customer_name'];
	$customer->customer_code = $form_state['values']['customer_code'];
  $customer->fill_color = (!empty($form_state['values']['fill_color']) ? 
                            $form_state['values']['fill_color'] : '');
  $customer->font_color = (!empty($form_state['values']['font_color']) ? 
                            $form_state['values']['font_color'] : '');
	
	if ($customer_id == 0) {
		$customer->active = 1;
		$customer->created_date = REQUEST_TIME;
		$customer->created_by_user = $user->uid;
		
		// new record
		// Table:  {qms_customers}
		if ( False == drupal_write_record('sch_customers', $customer)) {
			$msg = "Oops!  Something went wrong storing the customer record.";
			drupal_set_message(t($msg));
			drupal_goto('customers');
			return False;
		}
	}
	else {
		$customer->customer_id = $customer_id;
		$customer->active = (int) $form_state['values']['customer_active'];
		$customer->updated_date = REQUEST_TIME;
		$customer->updated_by_user = $user->uid;
		
		// update existing
		// Table:  {qms_customers}
		if ( False == drupal_write_record('sch_customers', $customer, 'customer_id')) {
			$msg = "Oops!  Something went wrong updating the customer record.";
			drupal_set_message(t($msg));
			drupal_goto('customers');
			return False;
		}
	}
	

	drupal_set_message($customer->customer . ' ' . t('successfully saved.'));
	drupal_goto('customers');
	
	_clear_scheduler_cache(SCH_CUSTOMER_LIST);  
  _clear_scheduler_cache(SCH_ELOGS_SEARCH_FORM); 
	return True;
}

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

function customer_delete_confirm($form, $form_state, $customer_id = 0) {
	
	try {
		
		if ( user_access('view manage menu') == FALSE ) {
	    drupal_set_message( t('Unauthorized Access.  Permission is required.'));
			drupal_goto('customers');
			return $form;	
	  }

		$customer_name = _get_customer_name($customer_id);
		if ( $customer_name == '' ) {
			drupal_set_message( t('Oops!  Something seems to have gone wrong.  Customer not found.'));
			drupal_goto('customers');
			return $form;	
		}
		
		// check if the customer has user accounts linked
		$sql = "SELECT customer_id FROM {sch_users} WHERE customer_id = :cid LIMIT 1";
		$result = db_query($sql, array(':cid' => $customer_id));
		if ( $result->rowCount() ) {
			// cannot delete, customer linked to user account records
			$msg = "Unable to delete " . $customer_name .  ".  Customer has user accounts linked.";
			drupal_set_message(t($msg));	
			drupal_goto('customers');
			return $form;	
		}
		
		// check if the customer has linked assignments
		$sql = "SELECT customer_id FROM {sch_assignments} WHERE customer_id = :cid LIMIT 1";
		$result = db_query($sql, array(':cid' => $customer_id));
		if ( $result->rowCount() ) {
			// cannot delete, customer linked to assignments
			$msg = "Unable to delete " . $customer_name .  ".  Customer has assignments.";
			drupal_set_message(t($msg));	
			drupal_goto('customers');
			return $form;	
		}
		
	
		$form['customer_id'] = array(
			'#type' => 'value',
			'#value' => $customer_id,
		);
	
		$form['customer_name'] = array(
			'#type' => 'value',
			'#value' => $customer_name,
		);
    
    $title = t('Delete Customer') . '?';
    $question = t('Are you sure you want to delete?') . 
                '<h2>' . $customer_name . '</h2><br />' . 
                t('This action cannot be undone.');
		$goto_if_canceled = 'customers';
		$yes_btn = 	t('Delete');
		$no_btn = t('Cancel');
	
		return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);	
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, 'customer_delete_confirm() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

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

function customer_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$customer_id = $form_state['values']['customer_id'];
		$customer_name = $form_state['values']['customer_name'];
	
		// delete from database
		$num_rows = db_delete('sch_customers')
								->condition('customer_id', $customer_id, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows == 1 ) {
			// success
			
			$msg = 'Customer record for ' . $customer_name . ' has been deleted.';
		}
		else {
			$msg = 'Oops!  Unable to delete record for ' . $customer_name . '.';
		}
		drupal_set_message(t($msg));	
	}
	_clear_scheduler_cache(SCH_CUSTOMER_LIST);  
  _clear_scheduler_cache(SCH_ELOGS_SEARCH_FORM);  
	drupal_goto('customers');
}



/*
 *	_get_customer_select_list()
 *
 *	returns a selection list of customers.  
 *	$active_only = True flag filters the list to only active customers
 *	default = all customers
 */
function _get_customer_select_list($active_only = True) {
	try {
		$sql = '';
		$list = array();
		
		if ( $active_only ) {
			$sql = "SELECT customer_id, customer, active FROM {sch_customers} WHERE active = 1 ORDER BY customer";	
		}
		else {
			$sql = "SELECT customer_id, customer, active FROM {sch_customers} ORDER BY customer";	
		}
		
		$results = db_query($sql);

		$list[0] = '- Select -';  // add default option

		foreach($results as $row) {
      $suffix = '';
      if ( !$active_only ) {
        $suffix = ( $row->active ? '' : '*');
      }
			$list[$row->customer_id] = $row->customer . $suffix;
		}
		
		return $list;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_select_list() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}




/*
 *	_get_customer($customer_id)  
 *
 *	get the customer record by customer_id
 */
function _get_customer($customer_id) 
{
	try {
		
		$customer = (object) Null;
		if ( $customer_id > 0 ) {
			$sql = "SELECT customer_id, customer, customer_code, active, 
                     fill_color, font_color, 
			 							 created_date, created_by_user, 
			               updated_date, updated_by_user 
							FROM {sch_customers} c 
							WHERE customer_id = :cid";
			$results = db_query($sql, array(':cid' => $customer_id));

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

/*
 *	_get_customer_name($customer_id)  
 *
 *	get the customer name by customer_id
 */
function _get_customer_name($customer_id = 0, $user_id = 0) 
{
	try {
		
		$customer_name = '';
		
		if ( (int)$customer_id > 0 ) {
			$sql = "SELECT customer FROM {sch_customers} c WHERE customer_id = :cid";
			$customer_name = db_query($sql, array(':cid' => $customer_id))->fetchField();
		}
		else if ( (int)$user_id > 0 ) {
			$sql = "SELECT c.customer FROM {sch_customers} c, {sch_users} su 
							WHERE c.customer_id = su.customer_id 
							AND	  su.user_id = :uid";
			$customer_name = db_query($sql, array(':uid' => $user_id))->fetchField();
		}
		/*
		else if ( $group_id ) {
			$sql = "SELECT c.customer FROM {sch_customers} c, {sch_groups} g 
							WHERE c.customer_id = g.customer_id 
							AND	  g.group_id = :gid";
			$customer_name = db_query($sql, array(':gid' => $group_id))->fetchField();
		}
		*/
		return $customer_name;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_name() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	_get_customer_code($customer_id)  
 *
 *	get the customer name by customer_id
 */
function _get_customer_code($customer_id = 0) 
{
	try {
		
		$customer_code = '';
		
		if ( (int)$customer_id > 0 ) {
			$sql = "SELECT customer_code FROM {sch_customers} c WHERE customer_id = :cid";
			$customer_code = db_query($sql, array(':cid' => $customer_id))->fetchField();
		}
		
		return $customer_code;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_code() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	_get_user_customer_id()  
 *
 *	get the customer name by customer_id
 */
function _get_user_customer_id() 
{
	try {
		
		$customer_id = 0;
    global $user;
		
    $sql = "SELECT customer_id FROM {sch_users} 
            WHERE user_id = :uid";
    $customer_id = db_query($sql, array(':uid' => $user->uid))->fetchField();

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






/*
 *	_get_customer_user_group_name($customer_id)  
 *
 *	get the customer user's assigned group name by customer_id && user_id
 */
function _get_customer_user_group_name($customer_id = 0, $user_id = 0) 
{
	try {
		
		$group_name = '';
		
		$query = db_select('sch_groups', 'g');
		$query->innerJoin('sch_group_users', 'gu', 'g.group_id = gu.group_id');
		$query->condition('gu.user_id', $user_id);
		$query->condition('g.customer_id', $customer_id);
		$query->fields('g', array('group_name'));
		$results = $query->execute();
		
		if ( $results->rowCount() ) {
			$group_name = $results->fetchField();
		}
		return $group_name;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_user_group_name() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	_get_customer_users($customer_id)  
 *
 *	get a list of users for this customer
 */
function _get_customer_users($customer_id) 
{
	try {
		
		$customer_users = array();
		if ( $customer_id ) {
			
			// get the list of users linked to this customer
			$sql = "SELECT su.user_id, su.full_name, u.mail, u.status  
							FROM {sch_users} su, {users} u 
							WHERE su.customer_id = :cid
							AND   su.user_id = u.uid 
							ORDER BY su.full_name";
			$results = db_query($sql, array(':cid' => $customer_id));
			if ( $results->rowCount() ) {
				$customer_users = $results->fetchAll();
			}
						
		}
		return $customer_users;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_users() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

/*
 *	_get_customer_groups($customer_id)  
 *
 *	get a list of groups for this customer
 */
function _get_customer_groups($customer_id) 
{
	try {
		
		$groups = array();
		
		if ( $customer_id ) {
		
			
			$sql = "SELECT g.group_id, g.group_name, g.group_code 
							FROM {sch_groups} g
							WHERE g.customer_id = :cid 
							ORDER BY g.group_name";		
			
			/*
			$sql = "SELECT g.group_id, g.group_name, group_concat(su.full_name separator '; ') AS `group_users` 
							FROM {sch_groups} g, {sch_groups_users} gu, {sch_users} su 
							LEFT JOIN {sch_groups_users} gu ON g.group_id = gu.group_id 
							LEFT JOIN {sch_users} gu ON gu.user_id = su.user_id 
							WHERE g.customer_id = :cid 
							GROUP BY g.group_id 
							ORDER BY g.group_name";						
			*/				
						
			$results = db_query($sql, array(':cid' => $customer_id));
			if ( $results->rowCount()) {
				$groups = $results->fetchAll();
			}
		}
		return $groups;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_groups() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	_is_customer_code_unique($customer_id, $code)  
 *
 *	checks customer code for uniqueness
 */
function _is_customer_code_unique($customer_id, $code)  {
	try{
		if ( !strlen($code) ) {
			return False;
		} 
		
		$sql = "SELECT customer_id FROM {sch_customers} c 
						WHERE customer_code = :code 
						AND   customer_id != :id 
						LIMIT 1";
		$result = db_query($sql, array( ':code' => $code, ':id' => $customer_id ));
		if ( $result->rowCount() ) {
			return False;
		}
		
		return True;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_is_customer_code_unique() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}











