<?php

/*
 *	Corrective Actions record functions for sabreQMS module
 */



/*
 *	corrective_actions_display()
 *
 *	returns:  Displays table list of simulators
 *
 */

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

	$table_header = array( 
		array( 'data' => t('Corrective Action') ),
		array( 'data' => t('For Report Type')),
	);
	
	if ( $bAllowAdmin ) {
		$table_header[] = array( 'data' => 'Admin' );
	}
	
	
	// Get list of customers
	$result = db_query("SELECT action_id, action, report_code 
											FROM {qms_corrective_actions} c ORDER BY action");

	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
		
		$report_type = '';
		switch ($row->report_code) {
			case 'DR': $report_type = t('Discrepancy'); break;
			case 'TC': $report_type = t('Trouble Call'); break;
			default:   $report_type = t('All'); break;
		}
	
		$row_data = array(
			$row->action,
			$report_type,
		);
		
		if ( $bAllowAdmin == True ) {
			$row_data[] = _st_generate_options('corrective_action', $row->action_id);
		}
		
		$table_rows[] = array( 'data' => $row_data	);
		$i++;
	}


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

	return $content;
}

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

function corrective_action_form($form, $form_state, $action_id = 0) {

	if ( user_access('administer sabreQMS') == FALSE ) {
    return form_set_error( t('Unauthorized'), t('Administrator access required'));
  }

	drupal_add_js('(function($) {
										Drupal.behaviors.qmsCorrectiveActionForm = {
											attach: function(context, settings) {
												$("#qms-action_id", context).once().focus();
											}
										}
									}(jQuery));', 'inline');


	$corr_action = (object) Null;
	
	if ( $action_id ) {   // Edit existing record
		
		// get the record
		$sql = "SELECT action_id, action, report_code 
						FROM {qms_corrective_actions} 
						WHERE action_id = :aid";
		$result = db_query($sql, array(':aid' => $action_id));
		
		if ( !$result->rowCount() ) {
			$msg = 'Oops!  Something seems to have gone wrong.  Corrective Action not found.';
	    drupal_set_message( t($msg));
			drupal_goto('qmssettings/corrective_actions');
			return $form;
	  }				
		$corr_action = $result->fetchObject();
	}

  	
	$form['action'] = array(
		'#type' => 'textfield',
		'#title' => t('Action'),
		'#maxlength' => 255,
		'#default_value' => ($action_id ? $corr_action->action : ''),
		'#attributes' => array('id' => 'qms-action_id'),
	);	
	
	$report_codes = array();
	if ( $action_id ) {
		$report_codes = (!strlen($corr_action->report_code) ? 
													array('DR', 'TC') : array($corr_action->report_code));
	}
	else {
		$report_codes = array('DR', 'TC');
	}									
	
	$form['report_codes'] = array(
    '#type' => 'checkboxes',
    '#options'=> array (
      'DR' => t('Discrepancy Reports'),
      'TC' => t('Trouble Calls'),
      ),
			// if report_code is empty corrective_action applies to ALL reports
    '#default_value' => $report_codes,
  );
  	
	
	$form['action_id'] = array(
		'#type' => 'value',
		'#value' => ($action_id ? $action_id : 0),
	);				
		
	
	
	$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/corrective_actions') . 
                                         '"; return false;'),
	);
	

	return $form;
}

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

function corrective_action_form_validate($form, $form_state) {
	if ( trim($form_state['values']['action']) == '' ) {
		form_set_error('action', t('Action is a required field.'));
	}
	$report_codes = array_filter($form_state['values']['report_codes']);
	if ( !count($report_codes) ) {
		// reports have not be designated for this corr action
		form_set_error('report_types', t('Please select the reports for which this corrective action will be applied.'));
	}
}

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

function corrective_action_form_submit($form, $form_state) {
	$corr_action = new stdClass();
	
	$action_id = $form_state['values']['action_id'];
	if ($action_id > 0) {  
		// editing existing, get the record id
		$corr_action->action_id = (int) $form_state['values']['action_id'];
	}
	$corr_action->action = trim($form_state['values']['action']);
	$corr_action->report_code = '';
	$reports = array_filter($form_state['values']['report_codes']);
	
	// only one selected, otherwise, leave empty for both selections
	// of course, if none selected, doesn't pass validation
	if ( count($reports) == 1 ) { 
		$corr_action->report_code = array_pop($reports);
	}
	
	$msg = '';

	if  ( $action_id == 0 )  {  
		// new record
		// Table:  {qms_corrective_actions}
		if ( False == drupal_write_record('qms_corrective_actions', $corr_action)) {
			$msg = "Oops!  Something went wrong storing the corrective action record.";
			drupal_set_message(t($msg));
		}
	}
	else {
		// update existing
		// Table:  {qms_corrective_actions}
		if ( False == drupal_write_record('qms_corrective_actions', $corr_action, 'action_id')) {
			$msg = "Oops!  Something went wrong updating the corrective action record.";
			drupal_set_message(t($msg));
		}
	}
	
	if ( strlen($msg) == 0 ) {
		$msg = 'Corrective Action successfully saved.';
		drupal_set_message(t($msg));
	}
	
	global $action_list;
	$action_list->reload();
	
	drupal_goto('qmssettings/corrective_actions');
}

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

function corrective_action_delete_confirm($form, $form_state, $action_id) {
	
	if ( user_access('administer sabreQMS') == FALSE ) {
    form_set_error( t('Unauthorized Access'), t('Administrator access required.'));
		drupal_goto('qmssettings/corrective_actions');
		return;	
  }

	$action_id = check_plain($action_id);
	
	// Get record by id
	$sql = "SELECT action FROM {qms_corrective_actions} c WHERE action_id = :aid";
	$result = db_query($sql, array(':aid' => $action_id));
	
	if ( $result->rowCount() == 0 ) {
    form_set_error( t('Oops!'), t('Something seems to have gone wrong.  Corrective Action not found.'));
		drupal_goto('qmssettings/corrective_actions');
		return;
  }
		
	$action = $result->fetchField();
	
	
	// check if the corrective_action is linked to a Dicrepancy record
	$sql = "SELECT discrepancy_id FROM {qms_discrepancy_log} d WHERE corrective_action_id = :aid LIMIT 1";
	$result = db_query($sql, array(':aid' => $action_id));
	if ( $result->rowCount() ) {
		// cannot delete, record linked to a discrepancy
		$msg = "Unable to delete " . $action .  ".  Corrective Action is linked to discrepancy records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/corrective_actions');
		return;	
	}	
	
	// check if the corrective_action is linked to a Trouble Call record
	$sql = "SELECT trouble_call_id FROM {qms_trouble_call_log} d WHERE corrective_action_id = :aid LIMIT 1";
	$result = db_query($sql, array(':aid' => $action_id));
	if ( $result->rowCount() ) {
		// cannot delete, record linked to a discrepancy
		$msg = "Unable to delete " . $action .  ".  Corrective Action is linked to trouble call records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/corrective_actions');
		return;	
	}	
	
	
	$form['action_id'] = array(
		'#type' => 'value',
		'#value' => $action_id,
	);
	
	$form['action'] = array(
		'#type' => 'value',
		'#value' => $action,
	);
  
  $title = t('Delete Corrective Action') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . $action . '</h2><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'qmssettings/corrective_actions';
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);
	
}

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

function corrective_action_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$action_id = $form_state['values']['action_id'];
		$action = $form_state['values']['action'];
	
	
		// delete from database
		$num_rows = db_delete('qms_corrective_actions')
								->condition('action_id', $action_id, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows == 1 ) {
			$msg = 'Corrective Action record "' . $action . '" has been deleted.';
		}
		else {
			$msg = 'Oops!  Unable to delete record for "' . $action . '".';
		}
		drupal_set_message(t($msg));
	
		global $action_list;
		$action_list->reload();
	}
	
	drupal_goto('qmssettings/corrective_actions');
}







