<?php

/*
 *	Customer record functions for sabreQMS module
 */


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

function customers_display() {
	
	if (user_access('view admin lists') == False) {
		return;
	}
	
	// Check permissions -- only allow editing capabilities if 'administer officers' enabled
	$bAllowAdmin = user_access('administer sabreQMS');

	$table_header = array( 
		array( 'data' => 'Customer' ),
		array( 'data' => 'Users' ),
		array( 'data' => 'Simulators' ),
		array( 'data' => 'Active?' ),
	);
	
	if ( $bAllowAdmin == True ) {
		$table_header[] = array(
			'data' => 'Admin',
			//'class' => 'sorttable_nosort',
		);
	}
	
	
	// Get list of customers
	$sql = "SELECT c.customer_id, c.customer, c.active, 
								 (SELECT COUNT(*) FROM {qms_customers_users} cu WHERE cu.customer_id = c.customer_id ) AS `user_count`, 
								 (SELECT COUNT(*) FROM {qms_simulators} s WHERE s.customer_id = c.customer_id AND s.deleted = 0 ) AS `simulator_count` 
					FROM {qms_customers} c 
					ORDER BY customer";
	$result = db_query($sql);

	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
		
		$row_data = array(
			$row->customer,
			$row->user_count,
			$row->simulator_count,
			($row->active ? 'x' : ''),
		);
		
		if ( $bAllowAdmin == True ) {
			$row_data[] = _st_generate_options('customer', $row->customer_id);
		}
		
		$table_rows[] = array( 'data' => $row_data	);
		$i++;
	}
	
	$content = '';

	if ( $bAllowAdmin )
	{
		$content = l( t('Add Customer'), 'customer/add', array('class' => array('customer_add')) );
	}
	
	$content .= theme('table', array(
		'header' => $table_header,
		'rows' => $table_rows,
		'empty' => t('None'),
	));

	return $content;
}

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

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

	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Administrator access required'));
		drupal_goto('qmssettings/customers');
		return;
  }
  	
	$form['customer_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Customer Name'),
		'#maxlength' => 100,
		'#default_value' => '',
	);	
		
	$form['customer_active'] = array(
		'#type' => 'checkbox',
		'#title' => t('Active?'),
		'#default_value' => 1,
		'#disabled' => True,
		'#suffix' => '<div class="qms-desc">Setting customer to inactive automatically blocks all linked user accounts</div><br />',
	);		
		
	$form['customer_id'] = array(
		'#type' => 'value',
		'#value' => 'NEW',
	);		
	
			
		
	
	if ( (int)$customer_id > 0 ) {   // Edit existing record
		
		$customer = array();
		$cu_table = '';
		$sim_table = '';
		
		$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('qmssettings/customers');
			return;
		}
		
		// set existing customer values into form
		$form['customer_id']['#value'] = $customer_id;		
		$form['customer_name']['#default_value'] = $customer->customer;
		$form['customer_active']['#default_value'] = (int) $customer->active;
		$form['customer_active']['#disabled'] = False;
		
		
		
		// ------------------- GET USER ACCOUNTS LINKED TO THIS CUSTOMER ---------------------
		$form['manage_users'] = array(
			'#markup' => '<hr />' . l(t('Administer Users'), 'admin/people'),
		);
		
		
		// get the list of users linked to this customer
		$sql = "SELECT u.uid, u.name, u.mail, u.status
						FROM {users} u, {qms_customers_users} cu  
						WHERE u.uid = cu.user_id 
						AND   cu.customer_id = :cid
						ORDER BY u.name";
		$results = db_query($sql, array(':cid' => $customer_id));
		
		if ( $results->rowCount() ) {
			
			// there are users linked... add them to a table
			$table_headers = array(
				array('data' => 'Linked Users'),
				array('data' => 'EMail'),
				array('data' => 'Active?'),
			);
			$table_rows[] = array();
			
			foreach( $results as $row) {
				$row_data = array(
					$row->name,
					l($row->mail, 'mailto:' . $row->mail),
					//'<a href=mailto:' . $row->mail . '>' . $row->mail . '</a>',
					($row->status ? 'x' : ''),
				);
				
				$table_rows[] = array( 'data' => $row_data );		
			}
			
			$cu_table = '<div id="qms-customer-users-div">';
			$cu_table .= theme( 'table', array(
				'header' => $table_headers,
				'rows' => $table_rows,
			));
			$cu_table .= '</div>';
			
			$form['customer_users'] = array(
				'#markup' => $cu_table,
			);
			
		}
		unset($table_rows);
		unset($table_headers);
		
		// ------------------- Get SIMULATORS linked to this CUSTOMER ---------------------
		$form['manage_simulators'] = array(
			'#markup' => '<hr />' . l(t('Administer Simulators'), 'qmssettings/simulators'),
		);
		
		
		// get the list of sims linked to this customer
		$sql = "SELECT simulator_id, sim_name, device_id_internal, active 
						FROM {qms_simulators} 
						WHERE customer_id = :cid 
						ORDER BY sim_name, device_id_internal";
		$results = db_query($sql, array(':cid' => $customer_id));
		
		if ( $results->rowCount() ) {
			
			// there are users linked... add them to a table
			$table_headers = array(
				array('data' => 'Simulator'),
				array('data' => 'Active?'),
			);
			$table_rows[] = array();
			
			foreach( $results as $row) {
				$row_data = array(
					_st_format_sim_name($row->sim_name, $row->device_id_internal),
					($row->active ? 'x' : ''),
				);
				
				$table_rows[] = array( 'data' => $row_data );		
			}
			
			$sim_table = '<div id="qms-simulators-div">';
			$sim_table .= theme( 'table', array(
				'header' => $table_headers,
				'rows' => $table_rows,
			));
			$sim_table .= '</div>';
			
			$form['simulators'] = array(
				'#markup' => $sim_table,
			);
		}
		
	}
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#attributes' => array('class' => array('qms-btn-submit')),
	);
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                            url('qmssettings/customers') . 
                                         '"; return false;'),
	);
	

	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_form_submit()  
 *
 *  overloads:  hook_form_submit()
 *
 *	Saves customer_form data upon successful submit
 */

function customer_form_submit($form, $form_state) {
	$customer = (object) NULL;
	
	$mode = $form_state['values']['customer_id'];
	if ($mode == 'NEW') {
		$customer->customer = $form_state['values']['customer_name'];
		$customer->active = 1;
		$customer->notify_employee_user_id = 0;
	}
	else {
		$customer->customer_id = (int) $form_state['values']['customer_id'];
		$customer->customer = $form_state['values']['customer_name'];
		$customer->active = (int) $form_state['values']['customer_active'];
		$customer->notify_employee_user_id = 
				( isset($form_state['values']['notify_employee']) ? (int)$form_state['values']['notify_employee'] : 0 );
	}
	

	if  ( $mode == 'NEW' )  {  
		// new record
		// Table:  {qms_customers}
		if ( False == drupal_write_record('qms_customers', $customer)) {
			$msg = "Oops!  Something went wrong storing the customer record.";
			drupal_set_message(t($msg));
			drupal_goto('qmssettings/customers');
			return False;
		}
	}
	else {
		// update existing
		// Table:  {qms_customers}
		if ( False == drupal_write_record('qms_customers', $customer, 'customer_id')) {
			$msg = "Oops!  Something went wrong updating the customer record.";
			drupal_set_message(t($msg));
			drupal_goto('qmssettings/customers');
			return False;
		}
	}
	
	global $customer_list;
	$customer_list->reload();
	
	drupal_set_message(t('Customer record successfully saved.'));
	drupal_goto('qmssettings/customers');
	return True;
}



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

function customer_delete_confirm($form, $form_state, $customer_id) {
	
	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized Access.  Administrator access required.'));
		drupal_goto('qmssettings/customers');
		return;	
  }

	$customer_id = check_plain($customer_id);
	
	// Get Customer record by id
	$sql = "SELECT customer FROM {qms_customers} c WHERE customer_id = :cid";
	$result = db_query($sql, array(':cid' => $customer_id));
	
	if ( $result->rowCount() == 0 ) {
    drupal_set_message( t('Oops!  Something seems to have gone wrong.  Customer not found.'));
		drupal_goto('qmssettings/customers');
		return;
  }
	
	$customer_name = $result->fetchField();
	
	// check if the customer is linked to a Dicrepancy record
	$sql = "SELECT d.discrepancy_id 
					FROM {qms_discrepancy_log} d, {qms_simulators} s 
					WHERE s.customer_id = :cid 
					AND   s.simulator_id = d.simulator_id 
					LIMIT 1";
	$result = db_query($sql, array(':cid' => $customer_id));
	if ( $result->rowCount() ) {
		// cannot delete, customer linked to discrepancy records
		$msg = "Unable to delete " . $customer_name .  ".  Customer is linked to discrepancy records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/customers');
		return;	
	}
	
	// check if the customer has user accounts linked
	$sql = "SELECT customers_users_id FROM {qms_customers_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('qmssettings/customers');
		return;	
	}
	
	// check if the customer has simulators linked
	$sql = "SELECT simulator_id FROM {qms_simulators} WHERE customer_id = :cid LIMIT 1";
	$result = db_query($sql, array(':cid' => $customer_id));
	if ( $result->rowCount() ) {
		// cannot delete, customer linked to simulatort records
		$msg = "Unable to delete " . $customer_name .  ".  Customer has simulators linked.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/customers');
		return;	
	}
	
	
	$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 = 'qmssettings/customers';
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);
	
}

/*
 *	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('qms_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));
	
		global $customer_list;
		$customer_list->reload();
	}
	
	drupal_goto('qmssettings/customers');
}



/*
 *	_get_customer($customer_id)  
 *
 *	get the customer record by customer_id
 */
function _get_customer($customer_id) 
{
	$customer = (object) Null;

	$sql = "SELECT customer, active 
					FROM {qms_customers} c 
					WHERE customer_id = :cid";
	$results = db_query($sql, array(':cid' => $customer_id));

	if ( $results->rowCount() ) {
	  $customer = $results->fetchObject();
	}
	return $customer;
}








