<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Shift Log search function handling
 *    
*/

//require_once('sabreQMS.utils.inc');


/*
 *	user_feedback()
 *
 */
function user_feedback() {
	
	if (user_access('user feedback') == False) {
		drupal_set_message(t('Unauthorized:  Permission to access is required'));
    return;
  }


	$user_feedback_form = '';
	
	// TO DO:
	/*
		In order to make caching to work properly, I need to have a minimal call to drupal_get_form (button rendering only)
		while the rest of the major form pieces can be cached and stored for repeated use.
		or the form submit routing does not get set correctly and drupal gets lost of what to do when the form is submitted
	*/

/*
	$form_cache = cache_get('QMS_userfeedback_form');
	if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
		$user_feedback_form = $form_cache->data;
	}
	else {
		// search results not in cache, create empty div for ajax to populate after search
		// search results will get populated to cache after ajax call
*/
    $form_elems = drupal_get_form('user_feedback_form');
		$user_feedback_form = render($form_elems);

/*		
		// maintains cache entry for the form for 20 min before refresh (time in seconds)
		// not tied to any one user, can be shared in the database by multiple users
		cache_set('QMS_userfeedback_form', $user_feedback_form, 'cache', time() + (20 * 60));			
	}
*/
	
	return $user_feedback_form;
	
}


/*
 *	user_feedback_form()
 *
 *  overloads:  hook_form()
 */
function user_feedback_form() {
	
		// all page-specific javascript loaded in the after_build function
	$form['#after_build'][] = 'user_feedback_form_after_build';
	

	//------------ BUILD FORM ------------------
	
	$form['name'] = array(
		'#type' => 'textfield',
		'#title' => t('Name'),
		'#size' => 60,
		'#maxlength' => 100,
		'#required' => True,
		'#attributes' => array('id' => 'qms-feedback-name'),
	);
	
	$form['email'] = array(
		'#type' => 'textfield',
		'#title' => t('Email'),
		'#size' => 60,
		'#maxlength' => 100,		
		'#required' => True,
		'#attributes' => array('id' => 'qms-feedback-email'),
	);
	
	global $base_url;
	
	$form['image_filepath'] = array(
		'#type' => 'textfield',
		// this is a kluge.  The browser needs a normal path
		// url returns 'http://www.example.com?q=sites/default/files' which won't work with the browser
		// get the base url from drupal globals and assemble
		'#default_value' => $base_url . QMS_IMAGES_DIR,
		'#attributes' => array('id' => 'qms-img-filepath',
													 'class' => array('qms-hidden-field')),
	);
	
	

	$form['comment'] = array(
		'#type' => 'textarea',
		'#title' => t('Comment'),
		'#maxlength' => QMS_TEXTAREA_MAX,
		'#required' => True,
		'#attributes' => array('id' => 'qms-feedback-comment',
														'qms-max-length' => QMS_TEXTAREA_MAX),
	);
	
	$form['ratings'] = array(
		'#type' => 'fieldset',
		'#title' => t('Ratings'),
		'#collapsible' => False,
		'#attributes' => array('id' => 'qms-feedback-ratings-div',
													 'style' => array('width:100%')),
	);
	

	$opts = array(
		0 => t('Not Applicable'),
		1 => t('Needs Improvement'),
		2 => t('Meets Expectations'),
		3 => t('Exceeds Expectations'),
	);
	
	$form['ratings']['as_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
													 'style' => array('padding-bottom:12px')),		
	);
	
	$form['ratings']['as_rate_box']['as_rate'] = array(
		'#type' => 'radios',
		'#title' => t('Aircraft System: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-0'),
	);
	
	$form['ratings']['hardware_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
													'style' => array('padding-bottom:12px')),		
	);
	
	$form['ratings']['hardware_rate_box']['hardware_rate'] = array(
		'#type' => 'radios',
		'#title' => t('Hardware: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-1'),
	);
	
	$form['ratings']['ios_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
														'style' => array('padding-bottom:12px')),		
	);
	
	$form['ratings']['ios_rate_box']['ios_rate'] = array(
		'#type' => 'radios',
		'#title' => t('IOS: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-2'),
	);
	
	$form['ratings']['instrument_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
														'style' => array('padding-bottom:12px')),		
	);
	
	$form['ratings']['instrument_rate_box']['instrument_rate'] = array(
		'#type' => 'radios',
		'#title' => t('Instrument: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-3'),
	);
	
	$form['ratings']['sound_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
														'style' => array('padding-bottom:12px')),		
	);
	
	$form['ratings']['sound_rate_box']['sound_rate'] = array(
		'#type' => 'radios',
		'#title' => t('Sound: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-4'),
	);
	
	$form['ratings']['motion_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
														'style' => array('padding-bottom:12px')),		
	);
	
	$form['ratings']['motion_rate_box']['motion_rate'] = array(
		'#type' => 'radios',
		'#title' => t('Motion: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-5'),
	);
	
	$form['ratings']['visual_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
														'style' => array('padding-bottom:12px')),		
	);
	
	$form['ratings']['visual_rate_box']['visual_rate'] = array(
		'#type' => 'radios',
		'#title' => t('Visual: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-6'),
	);
	
	$form['ratings']['other_rate_box'] = array(
		'#type' => 'container',
		'#attributes' => array('class' => array('container-inline'),
														'style' => array('padding-bottom:12px')),		
	);

	$form['ratings']['other_rate_box']['other_rate'] = array(
		'#type' => 'radios',
		'#title' => t('Other: <br />'),
		'#options' => $opts,
		//'#attributes' => array('id' => 'qms-rating-7'),
	);

	$form['ratings']['other_rate_box']['other_rate_text']= array(
		'#type' => 'textfield',
		//'#title' => t('Description:  '),
		'#size' => 70,
		'#maxlength' => 100,
		'#required' => False,
		'#attributes' => array('id' => 'qms-feedback-other-text'),
	);
	
	$form['email_copy'] = array(
		'#type' => 'checkbox',
		'#title' => t('Email a copy of these feedback responses to me.'),
		'#attributes' => array('id' => 'qms-email-copy'),
		'#prefix' => '<div id="qms-email-copy-div">',
		'#suffix' => '</div">',
	);
	
	
	
	
	//--------------------------------------------
	// Adds a simple submit button that refreshes the form and clears its contents 
	// -- this is the default behavior for forms.
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#name' => 'submit',
		'#attributes' => array('class' => array('qms-btn-submit')),
	);
	
  $form['actions']['clear'] = array(
		'#type' => 'button',
		'#value' => t('Clear'),
    '#name' => 'clear',
		'#attributes' => array('class' => array('qms-btn-clear', 'qms-btn-extra')),
	);
	
		
	// 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.
*/

/* 
 * user_feedback_form_after_build()
 *
 */
function user_feedback_form_after_build($form, &$form_state)
{
	//drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.userfeedbackinput.js');
	
	return $form;
}


/*
 *	user_feedback_form_validate()
 *
 *  overloads:  hook_form_validate()
 */
function user_feedback_form_validate($form, $form_state) {

	if ( trim( $form_state['values']['name'] ) == '' ) {
		form_set_error('name', t('Please enter your name.'));
	}
	$email = trim($form_state['values']['email']);
	
	if ( $email == '' ) {
		form_set_error('email', t('Please enter your email address.'));
	}
	if (!valid_email_address($email)) {
    form_set_error('email', 'Your email address appears malformed');
  }
  
	if ( trim( $form_state['values']['comment'] ) == '' ) {
		form_set_error('comment', t('Please enter a comment.'));
	}
	if ( ((int)$form_state['values']['other_rate'] > 0) &&
			(trim( $form_state['values']['other_rate_text'] ) == '') ) {
		form_set_error('other_rate_text', t('You have indicated a rating for "Other", but you do not provide a description of what Other represents.'));
	}
}

/*
 *	user_feedback_form_submit()
 *
 *  overloads:  hook_form_submit()
 */
function user_feedback_form_submit($form, $form_state) {
	$feedback = (object) Null;
	
	$feedback->date_entered = time();
	$feedback->name = trim($form_state['values']['name']);
	$feedback->email = trim($form_state['values']['email']);
	$feedback->comment = trim($form_state['values']['comment']);
	$feedback->as_rate = (int)$form_state['values']['as_rate'];
	$feedback->hardware_rate = (int)$form_state['values']['hardware_rate'];
	$feedback->ios_rate = (int)$form_state['values']['ios_rate'];
	$feedback->instrument_rate = (int)$form_state['values']['instrument_rate'];
	$feedback->motion_rate = (int)$form_state['values']['motion_rate'];
	$feedback->sound_rate = (int)$form_state['values']['sound_rate'];
	$feedback->visual_rate = (int)$form_state['values']['visual_rate'];
	$feedback->other_rate = (int)$form_state['values']['other_rate'];
	$feedback->other_text = trim($form_state['values']['other_rate_text']);
	$email_copy = (int)$form_state['values']['email_copy'];
	
	
	// store the feedback as a new record
	if ( drupal_write_record('qms_user_feedback', $feedback)) {
		// new record
		// new id was assigned -- saved successfully
		$msg = 'Thank you for your feedback.';
	}
	else {
		$msg = 'Oops!  Our apologies, something went wrong storing your feedback.';
	}
	drupal_set_message(t($msg));	
	
	
	// format an email message to send out
	$body = _format_body_user_feedback_email($feedback);
	$subject = 'QMS User Feedback Responses';
	
	
	// get the email addresses of the qms users who are notified of user feedback & send the emails out
	$result = db_query("SELECT mail FROM {users} u, {qms_employees} e WHERE u.uid = e.user_id AND e.receive_feedback = 1");
	foreach($result as $row) {
		$to = $row->mail;
		
		_st_send_drupal_email($feedback->user_feedback_id, $subject, $body, $to);		
	}
	
	// send a copy of the feedback results to the user if the checkbox was checked
	if ( $email_copy ) {
		$to = $feedback->email;
		$body .= '<br /><br />Thank you for your feedback!';
		_st_send_drupal_email($feedback->user_feedback_id, $subject, $body, $to);		
	}
	
	drupal_goto('');
}


/*
 *	user_feedback_display()
 *
 *  returns a table of user feedback that has been logged
 */

function user_feedback_display($called_by_pager = False) {
		
	if ( user_access('view admin lists') == False ) {
    drupal_set_message( t('Unauthorized Access.  Permission is required.'));
		drupal_goto('');
		return;	
	}		
	
	if ( ! $called_by_pager ) {
		drupal_add_library('system','ui.dialog');
		drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
		drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.userfeedback.js');
	}
	

	
	$num_per_page =  QMS_RECORDS_PER_PAGE;  

	$table_header = array( 
		array( 'data' => 'Date', 'field' => 'date_entered', 'sort' => 'desc' ),
		array( 'data' => 'Name/Email', 'field' => 'name', 'sort' => 'asc' ),
		array( 'data' => 'Comment', 'field' => 'comment' ),
		array( 'data' => 'AS', 'field' => 'as_rate' ),
		array( 'data' => 'HW', 'field' => 'hardware_rate' ),
		array( 'data' => 'IOS', 'field' => 'ios_rate' ),
		array( 'data' => 'Inst', 'field' => 'instrument_rate' ),
		array( 'data' => 'Mot', 'field' => 'motion_rate' ),
		array( 'data' => 'Snd', 'field' => 'sound_rate' ),
		array( 'data' => 'Vis', 'field' => 'visual_rate' ),
		array( 'data' => 'Other', 'field' => 'other_rate' ),
		array( 'data' => 'Admin' ),
	);
	
	$search_init = array(
		'table_name' => 'qms_user_feedback',
		'table_alias' => 'f',
		'table_header' => $table_header,
		'pager_path' => 'feedback/pager',
		'order' => 'Date',
		'sort' => 'desc',
		'variable' => False,
	);

	$query = _st_setup_paged_search($search_init);

	
	// Need to use the DB abstration layer here for the paging features
	//$query = db_select('qms_user_feedback', 'f');
		
	$query->fields('f', array('user_feedback_id', 'date_entered', 
                            'name', 'email', 'comment', 
														'as_rate', 'hardware_rate', 'ios_rate', 
                            'instrument_rate', 'motion_rate',
														'sound_rate', 'visual_rate', 
                            'other_rate', 'other_text') );

	$max_count = 0;
	$result = _st_execute_paged_search($query, $max_count);

	
	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
		
		$row_data = array(
			_st_format_date($row->date_entered, 'custom', 'Y-m-d'),
			l(t($row->name), 'mailto:' . $row->email),
			((strlen($row->comment) > 40) ? substr($row->comment, 0, 39) . '...' : $row->comment),
			$row->as_rate,
			$row->hardware_rate,			
			$row->ios_rate,
			$row->instrument_rate,
			$row->motion_rate,
			$row->sound_rate,
			$row->visual_rate,
			$row->other_rate,
			l( t('Email-to-Me'), 'feedback/send/' . $row->user_feedback_id,  
										array('attributes' => array('class' => array('qms-feedback-send')) ) ) . 
										'<br />' .
										l( t('Delete'), 'feedback/delete/' . $row->user_feedback_id,  
																	array('attributes' => array('class' => array('qms-feedback-delete')) ) ),
		);
		
		$table_rows[] = array('data' => $row_data);
		$i++;
	}
	
	
	$content = '<div id="qms-feedback-results-div">';
	
	$content .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
    'empty' => t('None'),
	));
	
	//Append pager:  http://api.drupal.org/api/drupal/includes--pager.inc/function/theme_pager
	$content .= theme('pager', array('tags' => array(), 'quantity' => $num_per_page));
	$content .= '</div>';
	
	if ( $called_by_pager ) {
		die($content);
	}
	$content .= '<div id="qms-message-box" style="display:none"></div>';// storage area for dynamic dialog element
	return $content;
}

/*
 *	email_feedback_to_admin()
 *
 *	Callback handler from user_feedback_display()  allows admin to resend user feedback email to self
 *  from clicking on the link in the user_feedback_display() table
 */

function email_feedback_to_admin($feedback_id) {
	
	if ( $feedback_id == 0 ) {
		return;
	}
	
	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized Access.  Administrator access required.'));
		drupal_goto('');
		return;	
  }
	
	
	$sql = "SELECT user_feedback_id, date_entered, name, email, comment, 
								 as_rate, hardware_rate, ios_rate, instrument_rate, motion_rate, 
								 sound_rate, visual_rate, other_rate, other_text 
					FROM {qms_user_feedback} f WHERE user_feedback_id = :fid";
	$result = db_query($sql, array(':fid' => $feedback_id));
	
	if ( $result->rowCount() == 0 ) {
		return;
	}
	
	$feedback = $result->fetchObject();
	
	global $user;
	
	// format an email message to send out
	$body = _format_body_user_feedback_email($feedback);
	$subject = 'QMS User Feedback Responses';
	_st_send_drupal_email($feedback->user_feedback_id, $subject, $body, $user->mail);   // in sabreQMS.utils.inc
	
	drupal_set_message(t('The feedback record from ' . $feedback->name . ' has been sent to ' . $user->mail));		
	drupal_goto('feedback');
}

/*
 *	_format_body_user_feedback_email()
 *
 *  sends the emails for user_feedback
 */

function _format_body_user_feedback_email($feedback) {
	$body  = '<strong>Name:</strong>&nbsp;&nbsp;&nbsp;' . $feedback->name . '<br /><br />';
	$body .= '<strong>Email:</strong>&nbsp;&nbsp;&nbsp;<a href="mailto:' . $feedback->email . '">' . $feedback->email . '</a><br /><br />';
	$body .= '<strong>Comment:</strong><br />' . $feedback->comment . '<br /><br />';
	$body .= '<table><tr><td colspan="2"><strong>Ratings:</strong></td></tr>';
	$body .= '<tr><td>Aircraft System: &nbsp;&nbsp;</td><td>' . _get_ratings_text($feedback->as_rate) . '</td></tr>';
	$body .= '<tr><td>Hardware: </td><td>' . _get_ratings_text($feedback->hardware_rate)  . '</td></tr>';
	$body .= '<tr><td>IOS: </td><td>' . _get_ratings_text($feedback->ios_rate)  . '</td></tr>';
	$body .= '<tr><td>Instrument: </td><td>' . _get_ratings_text($feedback->instrument_rate) . '</td></tr>';
	$body .= '<tr><td>Motion: </td><td>' . _get_ratings_text($feedback->motion_rate) . '</td></tr>';
	$body .= '<tr><td>Sound: </td><td>' . _get_ratings_text($feedback->sound_rate)  . '</td></tr>';
	$body .= '<tr><td>Visual: </td><td>' . _get_ratings_text($feedback->visual_rate) . '</td></tr>';
	$body .= '<tr><td>Other: <br />Description:</td><td>' . _get_ratings_text($feedback->other_rate)  . '<br />';
	$body .= $feedback->other_text . '</td></tr></table><br /><br />';
	return $body;
}


/*
 *	_get_ratings_text()
 *
 *	returns the text description for the numeric rating response
 *  Called by sabreQMS.userfeedback.inc, user_feedback_form_submit()
 */
function _get_ratings_text($rating) {
	switch ($rating) {
		case 0:	return 'Not Applicable';
		case 1: return 'Needs Improvement';
		case 2: return 'Meets Expectations';
		case 3: return 'Exceeds Expectations';
	}
}


/*
 *	user_feedback_delete_callback()  
 *
 *	Delete feedback record through ajax callback
 */
/*
function user_feedback_delete_callback($feedback_id) {
	
	if ( user_access('administer sabreQMS') == FALSE ) {
    form_set_error( t('Unauthorized Access'), t('Administrator access required.'));
		drupal_goto('');
		return;	
  }

	if ( $feedback_id == 0 ) {
		return;
	}

	// delete from database
	$num_rows = db_delete('qms_user_feedback')
							->condition('user_feedback_id', $feedback_id, '=')
							->execute();
	
	return user_feedback_display(True); 
}
*/

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

function user_feedback_delete_confirm($form, $form_state, $feedback_id) {
	
	if ( $feedback_id == 0 ) {
		return;
	}
	
	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized Access.  Administrator access required.'));
		drupal_goto('');
		return;	
  }
	
	// Get record by id
	$sql = "SELECT name FROM {qms_user_feedback} WHERE user_feedback_id = :fid";
	$result = db_query($sql, array(':fid' => $feedback_id));
	
	if ( !$result->rowCount() ) {
		drupal_set_message( t('Feedback Not Found!'), 'warning');
		drupal_goto('feedback');
		return;
	}
	
	$feedback_name = $result->fetchField();
	
	
	$form['feedback_id'] = array(
		'#type' => 'value',
		'#value' => $feedback_id,
	);
	
	$form['feedback_name'] = array(
		'#type' => 'value',
		'#value' => $feedback_name,
	);
	
	$title = t('Delete User Feedback Entry') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . t('Feedback from ') . $feedback_name . '</h2><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'feedback';
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  // force this here to avoid a problem with routing if cancelled
  //$_GET['destination'] = $goto_if_canceled;
  
  return confirm_form($form, $title,	$goto_if_canceled, $question, 
                      $yes_btn, $no_btn);
	
}

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

function user_feedback_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$feedback_id = $form_state['values']['feedback_id'];
		$feedback_name = $form_state['values']['feedback_name'];
		
		if ( $feedback_id == 0 ) {
			return;
		}
	
	
		// delete from database
		$num_rows = db_delete('qms_user_feedback')
								->condition('user_feedback_id', $feedback_id, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows == 1 ) {
			$msg = 'Feedback from ' . $feedback_name . ' has been deleted.';
		}
		else {
			$msg = 'Oops!  Unable to delete feedback for ' . $feedback_name . '.';
		}
		drupal_set_message(t($msg));
	}
	
	drupal_goto('feedback');
}








