<?php

/*
 *	Simulator record functions for sabreQMS module
 */

require_once ('sabreQMS.scheduler.tasks.inc');
require_once('sabreQMS.files.inc');
require_once('sabreQMS.simulatorfiles.inc');

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

function simulators_display() {
	
	if (user_access('view admin lists') == False) {
		return;
	}
	
	// Check permissions -- only allow editing capabilities if 'administer' enabled
	$bAllowAdmin = user_access('administer sabreQMS');
  
  $prefix_sims = variable_get(QMS_VAR_SIMS_USE_CUSTOMER_PREFIX, 1);
  
  $table_header = array();
  
  if ( $prefix_sims ) {
    $table_header[] = array( 'data' => t('Customer'), 
                             'class' => array('qms-simulators-tbl-customer') );
  }

	$table_header[] = array( 'data' => t('Simulator'), 'class' => array('qms-simulators-tbl-sim'));
  $table_header[] = array( 'data' => t('Active'), 'class' => array('qms-simulators-tbl-active'));
  $table_header[] = array( 'data' => t('FAA Id'), 'class' => array('qms-simulators-tbl-faaid'));
  $table_header[] = array( 'data' => t('Status'), 'class' => array('qms-simulators-tbl-status'));
  $table_header[] = array( 'data' => t('Files'), 'class' => array('qms-simulators-tbl-files'));
  $table_header[] = array( 'data' => t('Searches'), 'class' => array('qms-simulators-tbl-searches'));
	$table_header[] = array( 'data' => t('Notify'), 'class' => array('qms-simulators-tbl-notify'));
	
	if ( $bAllowAdmin ) { 
    $table_header[] = array('data' => 'Admin', 'class' => array('qms-admin') ); 	
  }
	
	global $user;
	
	
	// Get list of simulators
	$query = db_select('qms_simulators', 's');
	
	// check if this simulator has notifications set up... if so, indicate true/false
	$q2 = $query->addExpression('IF(s.simulator_id IN(SELECT simulator_id FROM qms_notifications), 1, 0)', 'notify');
	
	$user_is_customer_id = _user_is_customer($user->uid);
	if ( $user_is_customer_id > 0 ) {
		$query->condition('s.customer_id', $user_is_customer_id);
	}
	
	$query->condition('s.deleted', 0);

	$query->leftJoin('qms_customers', 'c', 's.customer_id = c.customer_id');
	$query->fields('s', array('simulator_id', 'sim_name', 'active', 
                            'faa_id', 'device_id_internal', 
                            'status_code', 'files_attached',
                            'include_all_searches'));
	$query->fields('c', array('customer'));
	$query->orderBy('customer', 'ASC')->orderBy('sim_name', 'ASC');
	$result = $query->execute();					
						
	/*
	$sql = "SELECT s.simulator_id, s.sim_name, s.active, c.customer  
					FROM {qms_simulators} s 
					LEFT JOIN {qms_customers} c ON s.customer_id = c.customer_id 
					ORDER BY c.customer, s.sim_name";
	$result = db_query($sql);
	*/

	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
    
    $row_data = array();
    
    if ( $prefix_sims ) {
      $row_data[] = $row->customer;
    }
    $row_data[] = _st_format_sim_name($row->sim_name, $row->device_id_internal);
    $row_data[] = array('data' => ($row->active ? 'x' : ''),
                        'class' => array('qms-simulators-tbl-active'));
    $row_data[] = array('data' => (strlen($row->faa_id) ? $row->faa_id : ''),
                        'class' => array('qms-simulators-tbl-faaid'));
    $row_data[] = array('data' => $row->status_code,
                        'class' => array('qms-simulators-tbl-status'));
    $row_data[] = array('data' => ($row->files_attached ? 'x' : ''),
                        'class' => array('qms-simulators-tbl-files'));
    $row_data[] = array('data' => ($row->include_all_searches ? 'x' : ''),
                        'class' => array('qms-simulators-tbl-files'));
    $row_data[] = array('data' => ($row->notify ? 'x' : ''), 
                        'class' => array('qms-simulators-tbl-notify'));
		
		if ( $bAllowAdmin ) {
			$row_data[] = _st_generate_options('simulator', $row->simulator_id);
		}
		
		$table_rows[] = array( 'data' => $row_data	);
		$i++;
	}
	
	$content = '';

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

	return $content;
}

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

function simulator_form($form, $form_state, $simulator_id = 0) {

	if ( user_access('administer sabreQMS') == FALSE ) {
    return form_set_error( t('Unauthorized'), t('Administrator access required'));
  }	
	
  global $customer_list;
	$simulator = (object) Null;
  $sim_files = array();

	
	if ( $simulator_id ) {   // Edit existing record
    
    $simulator = _get_simulator($simulator_id);
	
		if ( (object) null == $simulator ) {
	    form_set_error( t('Oops!'), 
         t('Something seems to have gone wrong.  Simulator not found.'));
			drupal_goto('qmssettings/simulators');
			return;
	  }
		

    $sim_files = _get_simulator_files($simulator_id);
	}
  
  // all page-specific javascript loaded in the after_build function
	$form['#after_build'][] = 'simulator_form_after_build';
	
 
	
	$form['simulator_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Simulator Name'),
		'#maxlength' => 100,
		'#default_value' => (($simulator_id > 0) ? $simulator->sim_name : ''),
	);	
  $form['simulator_active'] = array(
		'#type' => 'checkbox',
		'#title' => t('Active?'),
		'#default_value' => (($simulator_id > 0) ? (int) $simulator->active : 1),
		'#disabled' => (($simulator_id > 0) ? False : True),
    '#prefix' => '<div class="left-div">',
	);		
  
  $form['faa_id'] = array(
		'#type' => 'textfield',
		'#title' => t('FAA Id'),
		'#maxlength' => 10,
    '#size' => 10,
		'#default_value' => (($simulator_id > 0) ? $simulator->faa_id : ''),
    
	);	
  
  $form['customer'] = array(
		'#type' => 'select',
		'#title' => t('Customer'),
		'#options' => $customer_list->get(),
		'#default_value' => (($simulator_id > 0) ? $simulator->customer_id : 0),
		'#attributes' => array( 'id' => 'qms-customer-select',
														'class' => array('qms-select')),	
    '#suffix' => '</div>',
	);
  
  $form['include_all_searches'] = array(
		'#type' => 'checkbox',
		'#title' => t('Include in all Searches?'),
		'#default_value' => (($simulator_id > 0) ? 
                          (int) $simulator->include_all_searches : 1),
		//'#disabled' => (($simulator_id > 0) ? False : True),
    '#prefix' => '<div class="right-div">',
	);	
  
  $form['device_id_internal'] = array(
		'#type' => 'textfield',
		'#title' => t('Device Internal Id'),
		'#maxlength' => 5,
    '#size' => 5,
		'#default_value' => (($simulator_id > 0) ? $simulator->device_id_internal : ''),
	);	
	
  // get the list of possible sim statuses
  $status_list = _get_simulator_statuses();
  
  if ( count($status_list) ) {
    $form['status'] = array(
      '#type' => 'select',
      '#title' => t('Operational Status'),
      '#options' => $status_list,
      '#default_value' => (($simulator_id > 0) ? $simulator->status_code : 0),
      '#attributes' => array( 'id' => 'qms-status-select',
                              'style' => 'width:50px;'),	
    );
  }
  $form['markup_1'] = array(
    '#markup' => '</div><div class="clearBoth">&nbsp;</div>',
  );
  
	
		
	
	$form['simulator_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $simulator_id,  // if NEW, this will be 0
		'#attributes' => array('id' => 'qms-simulator-id',
													 'class' => array('qms-hidden-field')),
	);	
	
	$bHideSelectOption = True;
	$user_list = new UserList();
	$group_list = new UserGroupList($bHideSelectOption);		
	
	$notify_list = _get_simulator_notifications($simulator_id);
	$notify_table = _format_notifications_table($notify_list, 'EDIT');
	
	// turn database results array into an assoc array by user_id
	// needs to be in the same format as the UserList
	$assigned_user_list = array();
	$assigned_group_list = array();
	foreach($notify_list as $n) {
		if ( $n->user_id ) {
			$assigned_user_list[$n->user_id] = $n->name;
		}
		else {
			// add the [Group] prefix so that the UserGroupList class can match against the list
			$assigned_group_list[$n->user_group_id] = '[Group] ' .$n->group_name;
		}
	}
	
	
	$form['fs_notify'] = array(
		'#type' => 'fieldset',
		'#title' => 'Simulator Activity E-mail Notifications',
		//'#collapsible' => True,
		//'#collapsed' => ( !count($notify_list) ? True : False),
	);
	
	$form['fs_notify']['notifications'] = array(
		'#markup' => $notify_table,
	);
	
	$form['fs_notify']['notify_select'] = array(
		'#type' => 'select',
		'#title' => t('Add User or User Group'),
		'#options' => array_merge($user_list->get($assigned_user_list), $group_list->get($assigned_group_list)),
		'#default_value' => 0,
		'#attributes' => array('id' => 'qms-notify-select',			
													 'class' => array('qms-select')), 

		'#prefix' => '<table class="qms-plain-table"><tr ><td style="width:35%">',
		
	);
	
	$form['fs_notify']['notify_all'] = array(
		'#type' => 'checkbox',
		'#title' => 'All Alerts',
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-all'),
		'#suffix' => '</td>',
	);
	
	
	$form['fs_notify']['markup1'] = array(
		'#markup' => '<td>',
	);
	$form['fs_notify']['notify_discrepancy_new'] = array(
		'#type' => 'checkbox',
		'#title' => t('Discrepancy Alerts: New'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-discrepancy-new',
														'class' => array('qms-notify-checkbox')),
	);
	$form['fs_notify']['notify_discrepancy_updated'] = array(
		'#type' => 'checkbox',
		'#title' => t('Discrepancy Alerts: Updated'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-discrepancy-updated',
														'class' => array('qms-notify-checkbox')),
	);
	$form['fs_notify']['notify_discrepancy_closed'] = array(
		'#type' => 'checkbox',
		'#title' => t('Discrepancy Alerts: Closed'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-discrepancy-closed',
														'class' => array('qms-notify-checkbox')),
	);
  
  $form['fs_notify']['notify_trouble_call'] = array(
		'#type' => 'checkbox',
		'#title' => t('Trouble Call Alerts'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-trouble-call',
														'class' => array('qms-notify-checkbox')),
	);
  
	$form['fs_notify']['markup2'] = array(
		'#markup' => '</td><td>',
	);
  
  $form['fs_notify']['notify_preflight_new'] = array(
		'#type' => 'checkbox',
		'#title' => t('Preflight Alerts') . ': ' . t('New'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-preflight-new',
														'class' => array('qms-notify-checkbox')),
	);
  $form['fs_notify']['notify_preflight_open'] = array(
		'#type' => 'checkbox',
		'#title' => t('Preflight Alerts') . ': ' . t('Open/Not Cleared'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-preflight-open',
														'class' => array('qms-notify-checkbox')),
	);
	$form['fs_notify']['notify_shift_log'] = array(
		'#type' => 'checkbox',
		'#title' => t('Shift Log Alerts'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-shift-log',
														'class' => array('qms-notify-checkbox')),
	);
	$form['fs_notify']['notify_simulator_downtime'] = array(
		'#type' => 'checkbox',
		'#title' => t('Simulator Downtime Alerts'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-simulator-downtime',
														'class' => array('qms-notify-checkbox')),
	);
  $form['fs_notify']['notify_elog'] = array(
		'#type' => 'checkbox',
		'#title' => t('E-Log Alerts'),
		'#default_value' => False,
		'#attributes' => array('id' => 'qms-notify-elog',
													'class' => array('qms-notify-checkbox')),
	);

	$form['fs_notify']['markup3'] = array(
		'#markup' => '</td></tr></table>',
	);

	
	
	$form['fs_notify']['add_notify'] = array(
		'#type' => 'button',
		'#value' =>  t('Add'), // label changes to 'update'
		'#attributes' => array('id' => 'qms-btn-add-notify',
                           'style' => 'width:6.5em;',
													 'qms-url' => (( $simulator_id > 0 ) ? 
																url('simulator/notify/addupdate') : 
																url('simulator/notify/refresh')) ),
		'#prefix' => '<div class="qms-actions">',
		//'#suffix' => '<a id="qms-btn-clear-selection" href="">Clear</a></div>',
	);
  $form['fs_notify']['clear_notify'] = array(
		'#type' => 'button',
		'#value' => t('Clear'),
		'#attributes' => array('id' => 'qms-btn-clear-selection',
                            'style' => 'width:6.5em;',
                           'class' => array('qms-btn-extra')),
		//'#prefix' => '<div class="qms-actions">',
		'#suffix' => '</div>',
	);
	
	if ( $simulator_id == 0 ) {  // storage field for new simulator adding notification settings
		// need to wrap this in a hidden div since the textarea seems to want to display the grabber bar
		$form['fs_notify']['notify_list_to_add'] = array(
			'#type' => 'textarea',
			'#default_value' => '',
			'#prefix' => '<div id="qms-list-hidden" class="qms-hidden-field">',
			'#attributes' => array('id' => 'qms-notify-list-to-add'),
		);
	}
	else {
		$form['fs_notify']['edit_notify_id'] = array(
			'#type' => 'textfield',
			'#default_value' => '',
			'#attributes' => array('id' => 'qms-edit-notify-id',
														 'class' => array('qms-hidden-field')),
		);
		$form['fs_notify']['edit_recipient_id'] = array(
			'#type' => 'textfield',
			'#default_value' => '',
			'#attributes' => array('id' => 'qms-edit-recipient-id',
														 'class' => array('qms-hidden-field')),
		);
		
	}
	
  //  -----------------------------------------	
	
	if ( $simulator_id )  {
		
		// edit existing -- handle file interface differently
		// for existing simulators, display table of files attached.
		
		$table_headers = array(array('data' => 'Files', 'class' => 'qms-files-tbl-col1'),
													 array('data' => 'Uploaded By', 'class' => 'qms-files-tbl-col2'),
													);
		$table_rows = array();

		//if ( $user_perms->admin || $user_perms->delete_discrepancy_files  ) {
		$table_headers[] = array('data' => 'Admin');
		//}

		$i = 0;	
    if ( count($sim_files) ) {
      foreach ( $sim_files as $f ) {	
        $table_rows[] = array( 
           'data' => array( 
              l( t($f->file_name), 
                 "simulator/file/download/" . $f->file_id,
                 array('attributes' => array('target'=>'_blank')) ), 
              $f->name . ' - ' . _st_format_date($f->uploaded_timestamp, 'short'),
            ) );		
          $table_rows[$i]['data'][] =  l( t('Delete'), "simulator/file/delete/" . $f->file_id, 
                                            array('attributes' => array('class' => 'qms-file-delete') ) );
        //}
        $i++;
      }	
    }
		
		

		$files_table = theme( 'table', array(
			'header' => $table_headers,
			'rows' => $table_rows,
      'empty' => t('None'),
      'attributes' => array('class' => array('qms-sim-files-table'))
		));

		unset($table_headers);
		unset($table_rows);
	}
		
	$form['fs_files'] = array(
		'#type' => 'fieldset',
		'#title' => t('Simulator Files'),
		'#collapsible' => True,
		'#collapsed' => ( !count($sim_files) ),
	);
	
	$form['fs_files']['files_begin_div'] = array(
		'#markup' => '<div id="qms-files-div">',
	);

	
	if ( $simulator_id ) {
		$form['fs_files']['files'] = array(
			'#markup' => $files_table,
			'#prefix' => '<div id="qms-files-tbl-div">',
			'#suffix' => '</div>',
		);
	}
	global $base_url;
	$form['fs_files']['chk_add_file'] = array(
		'#type' => 'checkbox', 
		'#title' => t('Add Files to this Simulator') . '<span class="qms-waiting"><img class="qms-waiting-img" src="' . 
																								$base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
		'#default_value' => 0,
		'#attributes' => array('id' => 'qms-add-files-chk'),			
		'#suffix' => '<div class="qms-desc">You will be prompted to upload files on the next screen.</div>',
	);
	
	
	$form['fs_files']['files_end_div'] = array(
		'#markup' => '</div>',
	);

	global $base_url;
	
	$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/simulators') . '"; return false;'),
    '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' . 
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
	);
	
	
	// 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.
*/

/* 
 * simulator_form_after_build()
 *
 */
function simulator_form_after_build($form, &$form_state)
{
	drupal_add_library('system','ui.dialog');
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
  
	
	if ( (int)$form['simulator_id']['#default_value'] == 0) {
		drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.simulatoradd.js');
	}
	else {
		drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.simulatoredit.js');
	}
	
	return $form;
}


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

function simulator_form_validate($form, $form_state) {
	if ( trim($form_state['values']['simulator_name']) == '' ) {
		form_set_error('simulator_name', t('Simulator Name is a required field'));
	}
	if ( (int)$form_state['values']['customer'] == 0 ) {
		form_set_error('customer', t('Customer is a required field'));
	}
	
}

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

function simulator_form_submit($form, $form_state) {
	
	$simulator = (object) NULL;
	$notify_list = array();
  $timestamp = time();
  global $user;
  $msg = '';
	
	$simulator_id = (int) $form_state['values']['simulator_id'];
	
	if ( !$simulator_id ) {
		$simulator->active = 1;
		$notify_list_to_add = Trim($form_state['values']['notify_list_to_add']);
		$notify_list = strlen($notify_list_to_add) ? 
              explode('|', $notify_list_to_add) : array();
		
	}
	$simulator->customer_id = (int) $form_state['values']['customer'];
	$simulator->sim_name = $form_state['values']['simulator_name'];
	$simulator->active = (int) $form_state['values']['simulator_active'];
  $simulator->include_all_searches = 
          (int) $form_state['values']['include_all_searches'];
  $simulator->faa_id = $form_state['values']['faa_id'];
  $simulator->device_id_internal = $form_state['values']['device_id_internal'];
  $simulator->status_code = !empty($form_state['values']['status']) ? $form_state['values']['status'] : '';
  $add_files = (isset($form_state['values']['chk_add_file']) ? (int)$form_state['values']['chk_add_file'] : 0 );
  
	// notifications are updated through AJAX callbacks, not here in the submit
	
	

	if ( !$simulator_id )   {  
		// new record		
    
    $simulator->created_date = $timestamp;
    $simulator->created_by_user = $user->uid;
    
		
		// Table:  {qms_simulators}
		if ( False == drupal_write_record('qms_simulators', $simulator)) {
			$msg = "Oops!  Something went wrong saving the new simulator record to the database.";
			drupal_set_message(t($msg));
		}
		
		// add the simulator's notifications
		
		$notification = (object) Null;
		$notification->simulator_id = $simulator->simulator_id;
		
		$notification->user_id = 0;
		$notification->user_group_id = 0;
		$notification->notify_discrepancy_new = 0;
		$notification->notify_discrepancy_updated = 0;
		$notification->notify_discrepancy_closed = 0;
		$notification->notify_shift_log = 0;
		$notification->notify_simulator_downtime = 0;
    $notification->notify_preflight_open = 0;
    $notification->notify_preflight_new = 0;
    $notification->notify_trouble_call = 0;
    $notification->notify_elog = 0;
    
		
    if ( count($notify_list) ) {
      foreach( $notify_list as $n ) {
        $notify_rec = explode('=', $n);
        $name = $notify_rec[0];   											// group name or user name
        $id = (int)$notify_rec[1];										  // group id or user id ( has a suffix of U or G)
        $type = substr($notify_rec[1], -1);							// get the id suffix (right most char)
        $settings_list = explode(',', $notify_rec[2]);  // split the notify flags into an array

        if ( $type == 'U'	) {
          $notification->user_id = $id;
          $notification->user_group_id = 0;
        }
        else if ( $type == 'G'	) {
          $notification->user_id = 0;
          $notification->user_group_id = $id;
        }

        $notification->notify_discrepancy_new = $settings_list[0];
        $notification->notify_discrepancy_updated = $settings_list[1];
        $notification->notify_discrepancy_closed = $settings_list[2];
        $notification->notify_shift_log = $settings_list[3];
        $notification->notify_simulator_downtime = $settings_list[4];
        $notification->notify_preflight_open = $settings_list[5];
        $notification->notify_preflight_new = $settings_list[6];
        $notification->notify_trouble_call = $settings_list[7];
        $notification->notify_elog = $settings_list[8];



        drupal_write_record('qms_notifications', $notification);

        // clear for the next record to add
        $notification->notification_id = 0;
        $notification->user_id = 0;
        $notification->user_group_id = 0;
        $notification->notify_discrepancy_new = 0;
        $notification->notify_discrepancy_updated = 0;
        $notification->notify_discrepancy_closed = 0;
        $notification->notify_shift_log = 0;
        $notification->notify_simulator_downtime = 0;
        $notification->notify_preflight_open = 0;
        $notification->notify_preflight_new = 0;
        $notification->notify_trouble_call = 0;
        $notification->notify_elog = 0;
      }
    }
		
		// if possible, connect to Scheduler database
		$is_linked = variable_get(SCH_QMS_LINK, 0);
		if ( $is_linked ) {
      
      if ( False == _scheduler_simulator_add($simulator)) {
        $msg .= "Unable to add new simulator record to Scheduler.";
        drupal_set_message(t($msg));
      }
      else {
        $msg .= "Simulator successfully added to Scheduler.";
      }
		}
		
		
	}
	else {
		// update existing
    $simulator->simulator_id = $simulator_id;
    $simulator->updated_date = $timestamp;
    $simulator->updated_by_user = $user->uid;
    
		// Table:  {qms_simulators}
		if ( False == drupal_write_record('qms_simulators', $simulator, 'simulator_id')) {
			$msg = "Oops!  Something went wrong updating the simulator record.";
			drupal_set_message(t($msg));
		}
	}
	global $simulator_list;
	$simulator_list->reload();
	
	
  
  // WHERE ARE WE GOING NEXT???

	if ( $add_files ) {
		/*	route to file upload form
		** Email Notifications will be sent after completion of File Upload Form
		** whether or not files are uploaded
		*/
		drupal_goto('simulator/file/add/' . $simulator->simulator_id);
	}
	else {
		drupal_goto('qmssettings/simulators');
	}
}







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

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

	$simulator_id = check_plain($simulator_id);
  
  global $simulator_list;
  
  $simulator_name = $simulator_list->getName($simulator_id);
	
//	// Get record by id
//	$sql = "SELECT sim_name FROM {qms_simulators} s WHERE simulator_id = :sid";
//	$result = db_query($sql, array(':sid' => $simulator_id));
//	
//	if ( $result->rowCount() == 0 ) {
//    form_set_error( t('Oops!'), t('Something seems to have gone wrong.  Simulator not found.'));
//		drupal_goto('simulator');
//		return;
//  }
//	
//	$simulator_name = $result->fetchField();
	
	// check if the simulator is linked to a Dicrepancy record
	$sql = "SELECT discrepancy_id FROM {qms_discrepancy_log} d WHERE simulator_id = :sid LIMIT 1";
	$result = db_query($sql, array(':sid' => $simulator_id));
	if ( $result->rowCount() ) {
		// cannot delete, linkage found
		$msg = "Unable to delete " . $simulator_name .  ".  Simulator is linked to discrepancy records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/simulators');
		return;	
	}
	
	
	// check if the simulator is linked to a Shift Log record
	$sql = "SELECT shift_log_id FROM {qms_shift_log} s WHERE simulator_id = :sid LIMIT 1";
	$result = db_query($sql, array(':sid' => $simulator_id));
	if ( $result->rowCount() ) {
		// cannot delete, linkage found
		$msg = "Unable to delete " . $simulator_name .  ".  Simulator is linked to shift_log records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/simulators');
		return;	
	}		
	
	// check if the simulator is linked to a Job
	$sql = "SELECT job_id FROM {qms_jobs} j WHERE simulator_id = :sid LIMIT 1";
	$result = db_query($sql, array(':sid' => $simulator_id));
	if ( $result->rowCount() ) {
		// cannot delete, linkage found
		$msg = "Unable to delete " . $simulator_name .  ".  Simulator is linked to job records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/simulators');
		return;	
	}		
	
	// check if the simulator is linked to a Preventative Maintenance record
	$sql = "SELECT prev_maint_id FROM {qms_prev_maint} p WHERE simulator_id = :sid LIMIT 1";
	$result = db_query($sql, array(':sid' => $simulator_id));
	if ( $result->rowCount() ) {
		// cannot delete, linkage found
		$msg = "Unable to delete " . $simulator_name .  ".  Simulator is linked to Preventative Maintenance records.";
		drupal_set_message(t($msg));	
		drupal_goto('qmssettings/simulators');
		return;	
	}			
  
	
	
	$form['simulator_id'] = array(
		'#type' => 'value',
		'#value' => $simulator_id,
	);
	
	$form['simulator_name'] = array(
		'#type' => 'value',
		'#value' => $simulator_name,
	);
  
  $title = t('Delete Simulator') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . $simulator_name . '</h2><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'qmssettings/simulators';
  $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);
  
}

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

function simulator_delete_confirm_submit($form, $form_state) {
  
  try {
	
    if ( $form_state['values']['confirm']) {
      $simulator_id = $form_state['values']['simulator_id'];
      $simulator_name = $form_state['values']['simulator_name'];




      // LINK TO SCHEDULER DATABASE -- if possible
      $is_linked = variable_get(SCH_QMS_LINK, 0);
      $sch_num_deleted = 0;
      if ( $is_linked ) {

        $sch_num_deleted = _scheduler_simulator_delete($simulator_id);

      }

      // ------------ back to QMS db -------------------
      if ( $sch_num_deleted  || !$is_linked ) {
        // delete from database
        $qms_num_deleted = db_delete('qms_simulators')
                    ->condition('simulator_id', $simulator_id, '=')
                    ->execute();

        $num_rows1 = db_delete('qms_prev_maint')
                    ->condition('simulator_id', $simulator_id, '=')
                    ->execute();

        $num_rows2 = db_delete('qms_notifications')
                    ->condition('simulator_id', $simulator_id, '=')
                    ->execute();

        // DELETE SHIFT LOG FILES

        // need to delete physical files on the server
        // in addition to the db references

        // are there any shift log files?  We just need one for this shift log
        $results = db_query('SELECT file_id, file_uri FROM {qms_simulator_files} f WHERE simulator_id = :sid LIMIT 1',
                            array(':sid' => $simulator_id));

        if ( $results->rowCount() ) {
          $file_rec = $results->fetchObject();

          // deletes the physical files from their server location + the subdirectory
          _delete_all_attached_files($file_rec->file_uri);   

          // delete all of the shift log's file references from database
          $num_rows3 = db_delete('qms_simulator_files')
                ->condition('simulator_id', simulator_id)
                ->execute();	
        }										
      }
      else {  // just flag for delete
        $num_rows = db_update('qms_simulators')
                    ->fields(array(
                        'deleted' => 1,
                        'active' => 0,
                      ))
                    ->condition('simulator_id', $simulator_id)
                    ->execute();
      }


      $msg = 'Simulator record for ' . $simulator_name . ' has been deleted.';

      drupal_set_message(t($msg));

      global $simulator_list;
      $simulator_list->reload();
    }

    drupal_goto('qmssettings/simulators');
  }
  catch (Exception $e) {
    watchdog('sabreQMS', 'simulator_delete_confirm_submit()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}



/*
 *  _get_simulator()
 */
function _get_simulator($simulator_id) {
  try {
    $simulator = (object) null;
    
    if ( !$simulator_id ) { return $simulator; }
    
    // get the record
		$sql = "SELECT sim_name, active, customer_id, status_code, 
            files_attached, faa_id, device_id_internal, include_all_searches  
            FROM {qms_simulators} s WHERE simulator_id = :sid";
		$result = db_query($sql, array(':sid' => $simulator_id));
		
		if ( $result->rowCount() ) {
	    $simulator = $result->fetchObject();
	  }
    return $simulator;
  }
  catch (Exception $e) {
    watchdog('sabreQMS', '_get_simulator()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}





/*
 *  _get_simulator_notifications($simulator_id = 0)
 *
 *	Returns the list of notifications for this simulator
 *
 */

function _get_simulator_notifications($simulator_id = 0) {
  
  try {
	
    if ( $simulator_id == 0 ) return array();

    $sql = "SELECT n.notification_id, n.user_group_id, n.user_id, 
                   n.notify_discrepancy_new, n.notify_discrepancy_updated, 
                   n.notify_discrepancy_closed, n.notify_shift_log, 
                   n.notify_simulator_downtime, n.notify_preflight_open, 
                   n.notify_preflight_new, n.notify_trouble_call, 
                   n.notify_elog, 
                   u.name, g.group_name 
            FROM   {qms_notifications} n
            LEFT JOIN {users} u ON n.user_id = u.uid 
            LEFT JOIN {qms_user_groups} g ON n.user_group_id = g.user_group_id 
            WHERE 	n.simulator_id = :sid 
            ORDER BY u.name ASC, g.group_name ASC";
    $result = db_query($sql, array(':sid' => $simulator_id));

    if ( $result->rowCount() == 0 ) {
      return array();
    }

    return db_query($sql, array(':sid' => $simulator_id))->fetchAll();
  }
  catch(Exception $e) {
    watchdog('sabreQMS', '_get_simulator_notifications()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}


/*
 *  _format_notifications_table($notify_list, $mode = 'EDIT')
 *
 *	$notify_list = array of notifications records for a single simulator
 *  $mode = ['ADD'| 'EDIT'], slight differences in formatting for each
 *
 *  returns a formatted/themed table of notifications
 */

function _format_notifications_table($notify_list, $mode = 'EDIT') {
	
	$content = "";
	$row_data = array();
  
    //kpr($notify_list);
	
	$i = 0;
	foreach($notify_list as $n) {
		
		if ( $mode == 'ADD') {
			$notify_row = explode('=', $n);
			$settings_list = explode(',', $notify_row[2]);
			
			$bComma = False;
			$notify = "";
			if ( $settings_list[0]	|| 
					 $settings_list[1] ||
					 $settings_list[2]  ) {
						
				$notify = t('Discrepancy Alerts') . ':  ';
				if ( $settings_list[0] ) {
					$notify .= t('New');
					$bComma = True;
				}
				if ( $settings_list[1] ) {
					$notify .= ($bComma ? ', ' : '') . t('Updated');
					$bComma = True;
				}
				if ( $settings_list[2] ) {
					$notify .= ($bComma ? ', ' : '') . t('Closed');
					$bComma = True;
				}
				$notify .= '<br />';
			}
      if ( $settings_list[7] ) {
				$notify .= t('Trouble Call Alerts') . '<br />';
			}
      $bComma = False;
      if ( $settings_list[5]	|| 
					 $settings_list[6]  ) {
						
				$notify .= t('Preflight Alerts') . ':  ';
				if ( $settings_list[6] ) {
					$notify .= t('New');
					$bComma = True;
				}
				if ( $settings_list[5] ) {
					$notify .= ($bComma ? ', ' : '') . t('Open');
					$bComma = True;
				}
				
				$notify .= '<br />';
			}
			
			if ( $settings_list[3] ) {
				$notify .= t('Shift Log Alerts') . '<br />';
			}
			if ( $settings_list[4] ) {
				$notify .= t('Simulator Downtime Alerts') . '<br />';
			}
      if ( $settings_list[5] ) {
				$notify .= t('E-Log Alerts') . '<br />';
			}
			
			$link_options = l( t('Remove'), "",  array('attributes' => array('class' => 'qms-remove', 'row' => $i) ) );
			$row_data[$i] = array('data' => array( $notify_row[0], $notify, $link_options));
		}
		else {  // EDIT
			$link = '';
			$recipient = '';
			$recipient_id = '';
			
			if ( $n->user_id > 0 ) {
				$recipient = $n->name;
				$recipient_id = $n->user_id . "U";
			}
			else {
				$recipient = '[' . t('Group') . '] ' . $n->group_name;
				$recipient_id = $n->user_group_id . "G";
			}
			
			$link = l( t('Edit'), "simulator/notify/" . $n->notification_id, 
						array('attributes' => array('class' => 'qms-edit', 'row' => $i, 'recipient_id' => $recipient_id, 'recipient' => $recipient) ) );
			
			$link .= l( t('Remove'), "simulator/notify/remove/" . $n->notification_id, 
						array('attributes' => array('class' => 'qms-remove', 'row' => $i, 'recipient_id' => $recipient_id, 'recipient' => $recipient) ) );
			
			
			$bComma = False;
			$notify = "";
			if ( $n->notify_discrepancy_new 			|| 
					 $n->notify_discrepancy_updated 	||
					 $n->notify_discrepancy_closed  ) {
						
				$notify = t('Discrepancy Alerts') . ':  ';
				if ( $n->notify_discrepancy_new ) {
					$notify .= 'New';
					$bComma = True;
				}
				if ( $n->notify_discrepancy_updated ) {
					$notify .= ($bComma ? ', ' : '') . t('Updated');
					$bComma = True;
				}
				if ( $n->notify_discrepancy_closed ) {
					$notify .= ($bComma ? ', ' : '') . t('Closed');
					$bComma = True;
				}
				$notify .= '<br />';
			}
      if ( $n->notify_trouble_call ) { 
        $notify .= t('Trouble Call Alerts') . '<br />'; 
      }
      $bComma = False;
      if ( $n->notify_preflight_open 			|| 
					 $n->notify_preflight_new       ) {
						
				$notify .= t('Preflight Alerts') . ':  ';
				if ( $n->notify_preflight_new ) {
					$notify .= t('New');
					$bComma = True;
				}
				if ( $n->notify_preflight_open ) {
					$notify .= ($bComma ? ', ' : '') . t('Open');
					$bComma = True;
				}
				
				$notify .= '<br />';
			}
      
			
			if ( $n->notify_shift_log ) { 
        $notify .= t('Shift Log Alerts') . '<br />'; 
      }
			if ( $n->notify_simulator_downtime ) { 
        $notify .= t('Simulator Downtime Alerts') . '<br />'; 
      }
      if ( $n->notify_elog ) {
        $notify .= t('E-Log Alerts'). '<br />';
      }
      						
			$row_data[] = array( 'data' => array($recipient,	$notify, $link) );	
		}
		$i++;
	}
							
	

	// rebuild table
	$content = '<div id="qms-notify-div">';
	
	$content .= theme( 'table', array(
		'header' => array(array('data' => 'Users and Groups to Notify', 'class' => 'qms-notify-tbl-col1'), 
										  array('data' => 'Notifications', 'class' => 'qms-notify-tbl-col2'), 
											array('data' => 'Admin')),
		'rows' => $row_data,
    'empty' => t('None'),
    'attributes' => array('class' => array('qms-notify-table')),
	));
	
	$content .= '</div>';
	
	return $content;
}


/*
 *  simulator_add_update_notification_callback()
 *
 *	AJAX Callback Function
 *
 */
function simulator_add_update_notification_callback() {
		
	$content = "";
	$notify_list = array();
	
	$notification = (object) Null;
	$notification->user_id = 0;
	$notification->user_group_id = 0;	
	
	$notification->notification_id = 
          ( isset($_POST['notification_id'])  ? (int)$_POST['notification_id'] : 0 );
	$notification->simulator_id = 
          ( isset($_POST['simulator_id'])  ? (int)$_POST['simulator_id'] : 0 );
	$type = ( isset($_POST['id'])  ? substr($_POST['id'], -1) : '' );
	$id = ( isset($_POST['id'])  ? (int)$_POST['id'] : 0 );
	
	if ( $type == 'U'	) {
		$notification->user_id = $id;
		$notification->user_group_id = 0;
	}
	else if ( $type == 'G'	) {
		$notification->user_id = 0;
		$notification->user_group_id = $id;
	}
	
	$name = ( isset($_POST['name'])  ? $_POST['name'] : '');
	$settings_list = ( isset($_POST['settings'])  ? 
                     explode(',', $_POST['settings']) : array(0,0,0,0,0,0,0,0,0));
	
	$notification->notify_discrepancy_new = 
          ( isset($settings_list[0]) ? (int)$settings_list[0] : 0 );
	$notification->notify_discrepancy_updated = 
          ( isset($settings_list[1]) ? (int)$settings_list[1] : 0 );
	$notification->notify_discrepancy_closed = 
          ( isset($settings_list[2]) ? (int)$settings_list[2] : 0 );
	$notification->notify_shift_log = 
          ( isset($settings_list[3]) ? (int)$settings_list[3] : 0 );
	$notification->notify_simulator_downtime = 
          ( isset($settings_list[4]) ? (int)$settings_list[4] : 0 );
  $notification->notify_preflight_open = 
          ( isset($settings_list[5]) ? (int)$settings_list[5] : 0 );
  $notification->notify_preflight_new = 
          ( isset($settings_list[6]) ? (int)$settings_list[6] : 0 );
  $notification->notify_trouble_call = 
          ( isset($settings_list[7]) ? (int)$settings_list[7] : 0 );
  $notification->notify_elog = 
          ( isset($settings_list[8]) ? (int)$settings_list[8] : 0 );
  
	if ( ($notification->simulator_id > 0) && ($id > 0) && ($type <> '') && count($settings_list) > 0 ) {
		
		if ( $notification->notification_id ) {
			drupal_write_record('qms_notifications', $notification, 'notification_id');
		}
		else {
			drupal_write_record('qms_notifications', $notification);
		}
		
		$notify_list = _get_simulator_notifications($notification->simulator_id);
		$content = _format_notifications_table($notify_list, 'EDIT');

	}
	
	die($content);
}

/*
 *  simulator_remove_notification_callback()
 *
 *	AJAX Callback Function
 *
 */
function simulator_remove_notification_callback($notification_id) {
	
	$content = "";
	$notify_list = array();
	
	$simulator_id = ( isset($_POST['simulator_id'])  ? (int)$_POST['simulator_id'] : 0 );
	
	if ( ($simulator_id > 0) && ($notification_id > 0) ) {
		// delete group's user links
		db_delete('qms_notifications')
							->condition('notification_id', $notification_id, '=')
							->execute();

		$notify_list = _get_simulator_notifications($simulator_id);
		$content = _format_notifications_table($notify_list, 'EDIT');
	}
	
	die($content);
}

/*
 *  simulator_notification_table_refresh_callback()
 *
 *	AJAX Callback Function  -- Before Simulator has been Added
 *  Reformats and redisplays the notification table without links to the simulator which has not been added yet
 *
 */
function simulator_notification_table_refresh_callback() {
	
	// break notify list into individual records
	$nl = ( isset($_POST['notify_list'])  ? $_POST['notify_list'] : '' );
	
	$notify_list = array();

	
	if ( strlen($nl) > 0 ) {
		$notify_list = explode('|', $nl);
	}
	else {  // only one in the list
		$notify_list = $nl;
	}
	
	$content = _format_notifications_table($notify_list, 'ADD'); 					
	
	die($content);
}


/*
 *	get_simulator_notification_callback()
 *
 *  AJAX callback to retrieve a notification record
 */
function get_simulator_notification_callback($notification_id) {
  try {
    
    if ( !$notification_id ) {
      return drupal_json_output(array(
        'success' => False,
      ));	
    }
	
    $sql = 'SELECT user_id, user_group_id, 
                   notify_discrepancy_new, notify_discrepancy_updated, 
                   notify_discrepancy_closed, notify_shift_log, 
                   notify_simulator_downtime, notify_preflight_open, 
                   notify_preflight_new, notify_trouble_call, notify_elog 
            FROM {qms_notifications} n 
            WHERE notification_id = :nid';
    $result = db_query($sql, array(':nid' => $notification_id));

    $notification = $result->fetchObject();

    $recipient_id = ( ($notification->user_id > 0) ? $notification->user_id . "U" : $notification->user_group_id . "G" );

    return drupal_json_output(array(
        'success' => True,
        'id' => $recipient_id, 
        'discrepancy_new' => $notification->notify_discrepancy_new, 
        'discrepancy_updated' => $notification->notify_discrepancy_updated, 
        'discrepancy_closed' => $notification->notify_discrepancy_closed, 
        'shift_log' => $notification->notify_shift_log, 
        'simulator_downtime' => $notification->notify_simulator_downtime,                         
        'preflight_open' => $notification->notify_preflight_open,
        'preflight_new' => $notification->notify_preflight_new,
        'trouble_call' => $notification->notify_trouble_call,
        'elog' => $notification->notify_elog,
      ));	
  }
  catch(Exception $e) {
		watchdog('sabreQMS', 'get_simulator_notification_callback()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}


/*
 *  _get_simulator_statuses()
 * 
 * return:  the list of status codes from qms_simulator_statuses
 */
function _get_simulator_statuses() {
  try{
    $status_list = array();
    
    $sql = 'SELECT status_code FROM qms_simulator_statuses 
            WHERE `order` > 0 ORDER BY `order` ASC';
    $result = db_query($sql);
    
    foreach($result as $row) {
      $status_list[$row->status_code] = $row->status_code;
    }
    
    return $status_list;
    
  }
  catch(Exception $e) {
		watchdog('sabreQMS', '_get_simulator_statuses()' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}













