<?php
/*
 *	Simulator record functions for sabreScheduler module
 *
 *	These functions may be moved to the sabreTools module at a later time if Simulator management (add/edit)
 *  is permitted through the Scheduler.  For now, its display only and remains separate.
 */

require_once('sabreScheduler.QMS.tasks.inc');

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

function simulators_display() {
	
	//$access = ((variable_get('sabre_qms', 0) == 1) ? 'view admin lists' : 'view manage menu');
	
	if (user_access('view manage menu') == False) {
		return '';
	}
  
  $bEdit = user_access('edit settings');
	
	$table_header = array( 
		array( 'data' => t('Simulator'), 'class' => array('sch-simulators-tbl-name') ),
    array( 'data' => t('FAA Id') ),
		array( 'data' => t('Active?') ),
	);
  
  if ( $bEdit ) {
    $table_header[] = array( 'data' => t('Admin'), 'class' => array('qms-admin') );
  }
	
	// Get list of simulators
	$query = db_select('sch_simulators', 's');
	$query->fields('s', array('simulator_id', 'sim_name', 'active', 
                            'faa_id', 'device_id_internal'));
	$query->condition('deleted', 0); // do not include sims flagged for deletion
	$query->orderBy('sim_name')->orderBy('device_id_internal');
	$result = $query->execute();					
						
	$i = 0;
	$table_rows = array();
	
	foreach ($result as $row) {
    
    $sim_name = _st_format_sim_name($row->sim_name, $row->device_id_internal);
    
		$row_data = array(
			l($sim_name , 'simulator/view/' . $row->simulator_id, 
         array('query' => array('destination' => 'simulators'))),
      $row->faa_id,
			($row->active ? 'x' : ''),
		);
    if ( $bEdit ) {
      $row_data[] = _st_generate_options('simulator', $row->simulator_id);
    }
		
		$table_rows[] = array('data' => $row_data);
		$i++;
	}
	
  $content = '';
  
  if ( $bEdit ) {
    $content .=  l(t('Add Simulator'), 'simulator/add',	
                array('attributes' => array('class' => array('sch-simulator-add')) ) );
  }

	$content .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
		'empty' => t('None'),
	));

	return $content;
}

/*
 *	simulator_view()
 *
 *	returns:  Displays info about a specific simulator
 *
 */

function simulator_view_form($form, $form_state, $simulator_id) {
	
	if ( !user_access('view manage menu') || !$simulator_id ) {
		return;
	}
	
	drupal_add_js('(function($) {
										Drupal.behaviors.schSimulatorView = {
											attach: function(context, settings) {
												var title = $("#page-title", context).text(); 
												var simname = $("#qms-sim-name", context).text();
												$("#page-title", context).html(title + ":&nbsp;&nbsp;" + simname ); 
												$("#qms-btn-done", context).click(function() {
													window.location = $(this).attr("qms-url");
													return false;
												});
											}
										}
									}(jQuery));', 'inline');
	
	
	$simulator = (object) Null;
	$destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'simulators';
	}
	

	// Get the existing record

	$simulator = _get_simulator($simulator_id);
	if ( $simulator == (object) Null ) {
		drupal_set_message( t('Oops!  Something seems to have gone wrong.  Simulator not found.'));
		drupal_goto($goto_url);
		return;
	}

	$form['timestamp'] = array(
		'#markup' => _st_format_record_timestamp_table($simulator),
	);
	
	
	$form['simulator_name'] = array(
		'#type' => 'item',
		'#title' => t('Simulator Name'),
		'#markup' => '<span>' . $simulator->sim_name . '</span>' . 
                  '<span id="qms-sim-name" class="qms-hidden">' .  // page-title display
                    _st_format_sim_name($simulator->sim_name, $simulator->device_id_internal) . 
                 '</span>',
	);	
  
  if ( strlen($simulator->device_id_internal) ) {
    $form['device_id_internal'] = array(
      '#type' => 'item',
      '#title' => t('Device Internal Id'),
      '#markup' => $simulator->device_id_internal,

    );	
  }
  if ( strlen($simulator->faa_id) ) {
    $form['faa_id'] = array(
      '#type' => 'item',
      '#title' => t('FAA Id'),
      '#markup' => $simulator->faa_id,
    );
  }

	$form['simulator_active'] = array(
		'#type' => 'checkbox',
		'#title' => t('Active?'),
		'#default_value' => $simulator->active,
		'#disabled' => True,
    '#suffix' => '<br />',
	);		
  
  
  
  

	$form['simulator_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $simulator_id,
		'#attributes' => array('class' => array('qms-hidden')),
	);	
  
  

	$form['actions'] = array( '#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Done',
		'#attributes' => array('id' => 'qms-btn-done',
													 'qms-url' => url($goto_url)),
	);
	return $form;
}





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


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

	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized Administrator access required'));
		return $form;	
  }	
	

	$simulator = (object) Null;
	
	if ( $simulator_id > 0 ) {   // Edit existing record
		
		$simulator = _get_simulator($simulator_id);
		
		if ( $simulator == (object) Null ) {
	    form_set_error( t('Oops!'), t('Something seems to have gone wrong.  Simulator not found.'));
			drupal_goto('simulators');
			return;
	  }
		$form['timestamp'] = array(
			'#markup' => _st_format_record_timestamp_table($simulator),
		);
	}
	
	$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),
	);		
  
  
  $form['faa_id'] = array(
		'#type' => 'textfield',
		'#title' => t('FAA Id'),
		'#maxlength' => 10,
    '#size' => 10,
		'#default_value' => (($simulator_id > 0) ? $simulator->faa_id : ''),
	);	
  $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 : ''),
    '#suffix' => '<br class="clearBoth" />',
	);	
	
	$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')),
	);		
  
  
  
  $form['files_table'] = array(
    '#markup' => _get_simulator_files_table($simulator_id),
  );
  
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
	);
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url('simulators') . '"; return false;'),
	);
	
	
	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'));
	}
}


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


function simulator_form_submit($form, $form_state) {
	
	$simulator = new stdClass();
	global $user;
	
	$simulator->simulator_id = (int) $form_state['values']['simulator_id'];
	
	if ($simulator->simulator_id == 0) {
		$simulator->active = 1;
	}
	$simulator->sim_name = $form_state['values']['simulator_name'];
	$simulator->active = (int) $form_state['values']['simulator_active'];
  $simulator->faa_id = $form_state['values']['faa_id'];
  $simulator->device_id_internal = $form_state['values']['device_id_internal'];


	if  ($simulator->simulator_id == 0)   {  
		// new record		
		$simulator->created_by_user = $user->uid;
		$simulator->created_date = REQUEST_TIME;
	
		if ( False == drupal_write_record('sch_simulators', $simulator)) {
			$msg = "Oops!  Something went wrong saving the new simulator record to the database.";
			drupal_set_message(t($msg));
			return;
		}
		else {
			$msg = "Simulator successfully saved.  ";
		}
		
		// --------------------- New Simulators Only ----------------------------
		// If adding in Scheduler, connect to QMS and add it there as well
		$is_linked = variable_get('sch_qms_link', 0);
		
		if ( $is_linked ) {
      
			// if possible, connect to QMS database
      if ( False == _qms_simulator_add($simulator)) {
        $msg .= "Unable to add new simulator record to the QMS database.";
        drupal_set_message(t($msg));
      }
      else {
        $msg .= "Simulator successfully added to QMS.";
      }
		}
	}
	else {
		// update existing
		$simulator->updated_by_user = $user->uid;
		$simulator->updated_date = REQUEST_TIME;
		
		if ( False == drupal_write_record('sch_simulators', $simulator, 'simulator_id')) {
			$msg = "Oops!  Something went wrong updating the simulator record.";
			drupal_set_message(t($msg));
			return;
		}
		else {
			$msg = "Simulator successfully updated.";
		}
	}
  
  _clear_scheduler_cache(SCH_EXCEPTIONS_SEARCH_FORM);
  _clear_scheduler_cache(SCH_ELOGS_SEARCH_FORM);
	
	drupal_goto('simulators');
}



/*
 *	simulator_file_download()
 *
 *  implements hook_file_download()
 */

function simulator_file_download($file_id) {
   
  // these files are stored in QMS, but can be viewed by users in Scheduler
  return _qms_simulator_file_download($file_id);

}


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

function simulator_delete_confirm($form, $form_state, $simulator_id) {
	try {
	
		if ( user_access('view manage menu') == FALSE ) {
	    drupal_set_message( t('Unauthorized.  Permission is required'));
			drupal_goto('simulators');
			return $form;	
	  }

		$simulator_name = _get_simulator_name($simulator_id);

	
		// check if the simulator is linked to a Schedule
		$sql = "SELECT schedule_id FROM {sch_schedules}  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 has schedule records records.";
			drupal_set_message(t($msg));	
			drupal_goto('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 = 'simulators';
    $yes_btn = 	t('Delete');
    $no_btn = t('Cancel');

    return confirm_form($form, $title,	$goto_if_canceled, $question, $yes_btn, $no_btn);
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, 'simulator_delete_confirm() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	simulator_delete_confirm_submit()  
 *
 *	Submit after confirmation, delete the specified record
 */
function simulator_delete_confirm_submit($form, $form_state) {
	try {
		$qms_num_deleted = 0;
			
		if ( $form_state['values']['confirm']) {
			$simulator_id = $form_state['values']['simulator_id'];
			$simulator_name = $form_state['values']['simulator_name'];
			
				// if possible, connect to QMS database
			$is_linked = variable_get('sch_qms_link', 0);

			if ( $is_linked ) {
        
        $qms_num_deleted = _qms_simulator_delete($simulator_id);
        
			}
			
			// ------------ back to scheduler db -------------------
			if ( $qms_num_deleted  || !$is_linked ) {
				$sch_num_deleted = db_delete('sch_simulators')
										->condition('simulator_id', $simulator_id)
										->execute();
				
			}
			else {
				$num_rows = db_update('sch_simulators')
										->fields(array(
										    'deleted' => 1,
										    'active' => 0,
										  ))
										->condition('simulator_id', $simulator_id)
										->execute();
			}
	
			$msg = 'Simulator record ' . $simulator_name . ' has been deleted.';
			drupal_set_message(t($msg));
		}
    
    _clear_qms_cache(SCH_EXCEPTIONS_SEARCH_FORM);
    _clear_qms_cache(SCH_ELOGS_SEARCH_FORM);
	
		drupal_goto('simulators');
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, 'simulator_delete_confirm_submit() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}




/*
 * simulator_status_display()
 * 
 * 
 */


function simulator_status_display($mode, $simulator_id) {
  
  if ( user_access('access sabreScheduler') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Permission is required'));
    drupal_goto('');
    return;	
  }
  $content = '';
  
//  global $user;
//  
//  $user_customer_id =  _get_user_customer_id();
//  $bKioskMode = (( $user_customer_id == 1 ) && 
//                    user_access('kiosk mode') &&
//                    ($user->uid != 1) );
//  if ( $bKioskMode ) {
//    drupal_add_js(drupal_get_path('module', 'sabreScheduler') . 
//                        '/js/sabreScheduler.kioskreset.js');
//    $content .= '<div id="qms-kiosk-url" class="qms-hidden">' . 
//                  url('kiosk') . '</div>';
//  }
  
  
  $content .= _qms_simulator_discrepancy_items($mode, $simulator_id);
  
  $sdf = drupal_get_form('status_display_form');
  $content .= render($sdf);
  
  return $content;
}


/*
 * 
 *
 */

function simulator_files_display($simulator_id) {
  
  global $user;
  $content = '';
  
//  $user_customer_id =  _get_user_customer_id();
//  $bKioskMode = (( $user_customer_id == 1 ) && 
//                    user_access('kiosk mode') &&
//                    ($user->uid != 1) );
//  if ( $bKioskMode ) {
//    drupal_add_js(drupal_get_path('module', 'sabreScheduler') . 
//                        '/js/sabreScheduler.kioskreset.js');
//    $content .= '<div id="qms-kiosk-url" class="qms-hidden">' . 
//                  url('kiosk') . '</div>';
//  }
  
  
  $content .= _get_simulator_files_table($simulator_id);
  $df = drupal_get_form('status_display_form');
  $content .= render($df);
  
  return $content;
  
}


/*
 * status_display_form()
 * 
 */

function status_display_form($form, $form_state) {
  
  $form['dummy'] = array(
      '#markup' => '',
  );
  
  $form['actions'] = array( '#type' => 'actions');
	$form['actions']['done'] = array(
		'#type' => 'submit',
		'#value' => t('Done'),
		'#attributes' => array('id' => 'qms-btn-done'),  // close screen, go to home page
	);
  
  return $form;
}

/*
 * status_display_form_submit()
 * 
 */
function status_display_form_submit($form, $form_state) {
  
  drupal_goto('');
}






/*
 *	_get_simulator($simulator_id)  
 *
 *	get the simulator record by simulator_id
 */

function _get_simulator($simulator_id) {
	try {
		
		$simulator = (object) Null;
		if ( $simulator_id > 0 ) {
			$sql = "SELECT simulator_id, sim_name, active, deleted, 
                     faa_id, device_id_internal, 
										 created_date, created_by_user, updated_date, updated_by_user 
							FROM {sch_simulators} s
							WHERE simulator_id = :sid";
			$results = db_query($sql, array(':sid' => $simulator_id));

			if ( $results->rowCount() ) {
			  $simulator = $results->fetchObject();
				// for compatibility
				//$simulator->created_by_user = 0;
				//$simulator->updated_by_user = 0;
			}
		}
		return $simulator;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_simulator() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}

/*
 *	_get_simulator_name($simulator_id)  
 *
 *	get the sim name by simulator_id
 */
function _get_simulator_name($simulator_id = 0, $assignment_id = 0)
{
	try {
		
		$sim_name = '';
		
		if ( $simulator_id ) {
			$sql = "SELECT sim_name, device_id_internal FROM {sch_simulators} s 
              WHERE simulator_id = :id";
			$result = db_query($sql, array(':id' => $simulator_id));
      if ( $result->rowCount()) {
        $sim = $result->fetchObject();
        
        $sim_name = _st_format_sim_name($sim->sim_name, $sim->device_id_internal);
        
      }
		}
    else if ( $assignment_id ) {
      $sql = "SELECT sim_name, device_id_internal 
              FROM {sch_simulators} sim 
              INNER JOIN {sch_schedules} sch ON sch.simulator_id = sim.simulator_id 
              INNER JOIN {sch_assignments} a ON sch.schedule_id = a.schedule_id 
              WHERE a.assignment_id = :id";
			$result = db_query($sql, array(':id' => $assignment_id));
      if ( $result->rowCount()) {
        $sim = $result->fetchObject();
        
        $sim_name = _st_format_sim_name($sim->sim_name, $sim->device_id_internal);
      }
    }
		return $sim_name;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_simulator_name() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *  _get_simulator_files_table($simulator_id)
 * 
 *  formats a list of files linked to this simulator
 *  simulator files are stored in QMS, but can be accessed and viewed in Scheduler
 * 
 *  all file_ids are references in the QMS system only and are not native to Scheduler
 */
function _get_simulator_files_table($simulator_id) {
  
  $content = '';
  $sim_name = '';
  $table_rows = array();
  
  $table_header = array(array('data' => 'Files', 'class' => 'qms-files-tbl-col1'),
												 array('data' => 'Uploaded By', 'class' => 'qms-files-tbl-col2'),
												);
  
  if ( $simulator_id ) {

    // get the list of files for this sim from QMS
    $files = _qms_get_simulator_files($simulator_id);		

    if (count($files)) {
      foreach ( $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_system_date($f->uploaded_timestamp, 'short'),
          ) );		
      }	
    }
    
    
    $sim_name = _get_simulator_name($simulator_id);
    
  }
  
  
	
	// refresh table
  $content .= '<h3>' . $sim_name . '</h3>';
  
	$content .= '<div id="qms-files-tbl-div">';
  
	$content .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
    'empty' => t('None'),
	));
  //$content .= '<p class="qms-desc">' . t('Files Loaded into QMS') . '</p>';
	$content .= '</div>';
		
	return $content;


}


/*
 *  _get_simulator_schedule()
 */
function _get_simulator_schedule($simulator_id, $tgt_date = 0) {
  if (!$simulator_id) { return False; }
  
  $schedule_id = 0;
  
  try {
    
    $date = _st_format_system_timestamp($tgt_date);
    
    $query = db_select('sch_schedules', 's')
             ->condition('s.simulator_id', $simulator_id, '=');
    
    $query->where("( DATE(FROM_UNIXTIME(begin_date)) <= DATE(FROM_UNIXTIME(:dt)) ) AND 
                   ( DATE(FROM_UNIXTIME(:dt)) <=  DATE(FROM_UNIXTIME(end_date)) OR end_date = 0)", 
                  array(':dt' => $date));
          
    $query->fields('s', array('schedule_id'));
    
    $schedule_id = $query->execute()->fetchField();
    return $schedule_id;
            
  } catch (Exception $ex) {
    watchdog(SCH_SCHEDULER, '_get_simulator_schedule() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}
