<?php

/*
 *	ATA Chapters record functions for sabreQMS module
 */



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

function atachapters_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' => 'Chapter' ),
	);
	
	if ( $bAllowAdmin == True ) {
		$table_header[] = array(
			'data' => 'Admin',
			//'class' => 'sorttable_nosort',
		);
	}
	
	
	// Get list of chapters
	$result = db_query("SELECT chapter_id, chapter, code FROM {qms_ata_chapters} c ORDER BY code");

	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
		
		
		$row_data = array(
			(sprintf("%d - %s", $row->code, $row->chapter)),
		);
		
		if ( $bAllowAdmin == True ) {
			$row_data[] = _st_generate_options('atachapter', $row->chapter_id);
		}
		
		$table_rows[] = array( 'data' => $row_data	);
		$i++;
	}

	$content = '';

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

	return $content;
}

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

function atachapter_form($form, $form_state, $chapter_id = '') {

	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Administrator access required'));
    drupal_goto('');
    return;
  }
  
	$atachapter = array();
	
	$form['chapter'] = array(
		'#type' => 'textfield',
		'#title' => t('Chapter'),
		'#maxlength' => 100,
		'#default_value' => '',
	);		
	
	$form['code'] = array(
		'#type' => 'textfield',
		'#title' => t('Code'),
		'#maxlength' => 4,
		'#size' => 5,
		'#default_value' => '',
	);		
		
	$form['chapter_id'] = array(
		'#type' => 'value',
		'#value' => 'NEW',
	);				
		
	
	if ( $chapter_id <> '' ) {   // Edit existing record
		
		// get the record
		$sql = "SELECT chapter, code FROM {qms_ata_chapters} c WHERE chapter_id = :cid";
		$result = db_query($sql, array(':cid' => $chapter_id));
		
		if ( $result->rowCount() == 0 ) {
      drupal_set_message( t('Oops!  Something seems to have gone wrong.  ' . 
                          'ATA Chapter not found.'));
      drupal_goto('qmssettings/atachapters');
      return;
	  }
		
		$atachapter = $result->fetchObject();
		
		// set existing customer values into form
		$form['chapter_id']['#value'] = $chapter_id;		
		$form['chapter']['#default_value'] = $atachapter->chapter;
		$form['code']['#default_value'] = $atachapter->code;
	}
	
	$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/atachapters') . '"; return false;'),
	);
	

	return $form;
}

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

function atachapter_form_validate($form, $form_state) {
	if ( trim($form_state['values']['chapter']) == '' ) {
		form_set_error('chapter', t('Chapter is a required field.'));
	}
}

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

function atachapter_form_submit($form, $form_state) {
	$atachapter = (object) NULL;
	
	$mode = $form_state['values']['chapter_id'];
	if ($mode != 'NEW') {  
		// editing existing, get the record id
		$atachapter->chapter_id = (int) $form_state['values']['chapter_id'];
	}
	$atachapter->chapter = trim($form_state['values']['chapter']);
	$atachapter->code = trim($form_state['values']['code']);
	

	if  ( $mode == 'NEW' )  {  
		// new record
		// Table:  {qms_ata_chapters}
		if ( False == drupal_write_record('qms_ata_chapters', $atachapter) ) {
			$msg = "Oops!  Something went wrong storing the ata chapter record.";
			drupal_set_message(t($msg));
		}
	}
	else {
		// update existing
		// Table:  {qms_ata_chapters}
		if ( False == drupal_write_record('qms_ata_chapters', $atachapter, 'chapter_id')) {
			$msg = "Oops!  Something went wrong updating the ata chapter record.";
			drupal_set_message(t($msg));
		}
	}
	
	global $chapter_list;
	$chapter_list->reload();
	
	drupal_goto('qmssettings/atachapters');
}



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

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

	$chapter_id = check_plain($chapter_id);
	
	// Get record by id
	$sql = "SELECT chapter FROM {qms_ata_chapters} c WHERE chapter_id = :cid";
	$result = db_query($sql, array(':cid' => $chapter_id));
	
	if ( $result->rowCount() == 0 ) {
    drupal_set_message(t('Oops!  Something seems to have gone wrong.  ' . 
                        'Ata Chapter not found'));
		drupal_goto('qmssettings/atachapters');
		return;
  }
	
	
	$chapter = $result->fetchField();
	
	
	// check if the ATA chapter is linked to a Dicrepancy record
	$sql = "SELECT discrepancy_id FROM {qms_discrepancy_log} d WHERE ata_chapter_id = :cid LIMIT 1";
	$result = db_query($sql, array(':cid' => $chapter_id));
	if ( $result->rowCount() ) {
		// cannot delete, customer linked to discrepancy records
		$msg = "Unable to delete " . $chapter .  ".  Ata Chapter is linked to discrepancy records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/atachapters');
		return;	
	}	
	
	$form['chapter_id'] = array(
		'#type' => 'value',
		'#value' => $chapter_id,
	);
	
	$form['chapter'] = array(
		'#type' => 'value',
		'#value' => $chapter,
	);
  
  $title = t('Delete ATA Chapter') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . $chapter . '</h2><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'qmssettings/atachapters';
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);	
}

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

function atachapter_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$chapter_id = $form_state['values']['chapter_id'];
		$chapter = $form_state['values']['chapter'];
	
	
		// delete from database
		$num_rows = db_delete('qms_ata_chapters')
								->condition('chapter_id', $chapter_id, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows == 1 ) {
			$msg = 'Ata Chapter record "' . $chapter . '" has been deleted.';
		}
		else {
			$msg = 'Oops!  Unable to delete record for ' . $chapter . '.';
		}
	
		drupal_set_message(t($msg));
	
		global $chapter_list;
		$chapter_list->reload();
	}
	
	drupal_goto('qmssettings/atachapters');
}







