<?php
/**
 *		
 *		sabreScheduler Module for plugin to Drupal 7 Framework
 *
 *		Session Definitions (Names) function handling
 *    
*/


/*
 *	session_definitions_display()
 *
 *	displays a list of session definitions
 */
function session_definitions_display() {
	
	if (user_access('view manage menu') == False) {
		drupal_goto('');
		return;
	}	
  
  $bEdit = user_access('edit settings');

	
	// ------------------- GET SESSIONS ---------------------

	$query = db_select('sch_session_names', 'sn');
	$query->fields('sn', array('session_name_id', 'session_name'));
	$query->orderBy('session_name_id', 'ASC');

	$results = $query->execute();
	
	$table_header = array(
		array('data' => t('Order'), 'class' => array('sch-sessions-tbl-order')),
		array('data' => t('Sessions'), 'class' => array('sch-sessions-tbl-sessions')),
	);
  if ( $bEdit ) {
    $table_header[] = array('data' => t('Admin'), 'class' => array('sch-sessions-tbl-admin'));
  }
  
	$table_rows = array();
	$i = 0;
	
	foreach ($results as $row) {
		$row_data = array(
			$row->session_name_id,
			$row->session_name,
		);
    
    if ( $bEdit ) {
      $row_data[] = _st_generate_options('session', $row->session_name_id);
    }

		$table_rows[] = array( 'data' => $row_data );		
		$i++;
	}
	
	$content = '<div class="sch-help-div">' . 
									t('Changes made to sessions defined here will immediately take effect in existing schedules ') . 
								 '</div><br />';
	
  if ( $bEdit ) {
    $content .= l( t('Add Session'), 'session/add', array('class' => array('sch-session-add')) );
  }
	
	$content .= '<div id="sch-session-tbl-div">';
	$content .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
		'empty' => t('None'),
		'attributes' => array('id' => 'sch-sessions-tbl'),
	));		
	$content .= '</div>';

	return $content;
}

/*
 *	session_definition_form()
 *
 *	Add or Edit a session
 *  overloads hook_form()
 */

function session_definition_form($form, $form_state, $session_name_id = 0) {
	
	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized.  Permission is required.'));
		drupal_goto('');
		return;
  }

	drupal_add_js('(function($) {
										Drupal.behaviors.schSession = {
											attach: function(context, settings) {
												$("edit-session-name", context).focus();
											}
										}
									}(jQuery));', 'inline');
		
	$form['help'] = array(							
	 	'#markup' => '<div class="sch-help-div">' . 
									t('Changes made to sessions defined here will immediately take effect in existing schedules ') . 
								 '</div><br />',
	);
	

	$session = (object) Null;

	if ( $session_name_id ) {   // Get the existing record
		
		$session = _get_session_name($session_name_id);
		if ( $session == (object) Null ) {
			drupal_set_message( t('Oops!  Something seems to have gone wrong.  Session not found.'));
			drupal_goto('sessions');
			return;
		}
		/*
		$form['timestamp'] = array(
			'#markup' => _st_format_record_timestamp_table($schedule_pattern),
		);
		*/
	}
  	
	$form['session_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Session Name'),
		'#maxlength' => 25,
		'#size' => 25,
		'#required' => True,
		'#default_value' => ($session_name_id ? $session->session_name : ''),
	);	
				
	$form['session_name_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $session_name_id,
		'#attributes' => array('class' => array('qms-hidden')),
	);	
	
			
	
	$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('sessions') . '"; return false;'),
	);
	

	return $form;
	
}

/*
 *	schedule_pattern_form_validate()
 *
 */
function session_definition_form_validate($form, $form_state) {
	if ( trim($form_state['values']['session_name']) == '' ) {
		form_set_error('session_name', t('Session Name is a required field'));
	}
}

/*
 *	session_definition_form_submit()
 *
 */
function session_definition_form_submit($form, $form_state) {

	$session = new stdClass();
	$session_name_id = (int)$form_state['values']['session_name_id'];
	$session->session_name = $form_state['values']['session_name'];
		
	if ( $session_name_id ) {
		$session->session_name_id = $session_name_id;
		
		// update record
		if ( False == drupal_write_record('sch_session_names', $session, 'session_name_id')) {
			$msg = "Oops!  Something went wrong saving the schedule session record.";
			drupal_set_message(t($msg));
			drupal_goto('patterns');
			return False;
		}
	}
	else {
		
		// new record
		if ( False == drupal_write_record('sch_session_names', $session)) {
			$msg = "Oops!  Something went wrong saving the schedule session record.";
			drupal_set_message(t($msg));
			drupal_goto('patterns');
			return False;
		}
	}
	
	drupal_set_message(t('Session successfully saved.'));
	drupal_goto('sessions');
}



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

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

		$session = _get_session_name($session_name_id);
		if ( $session == (object)Null ) {
			drupal_set_message( t('Oops!  Something seems to have gone wrong.  Session not found.'));
			drupal_goto('sessions');
			return $form;	
		}		
		
		// check if the session is linked to schedules
		$sql = "SELECT schedule_session_id FROM {sch_schedule_sessions} WHERE session_name_id = :id LIMIT 1";
		$result = db_query($sql, array(':id' => $session_name_id));
		if ( $result->rowCount() ) {
			// cannot delete, customer linked to assignments
			$msg = "Unable to delete " . $session->session_name .  ".  Session is linked to schedules.";
			drupal_set_message(t($msg));	
			drupal_goto('sessions');
			return $form;	
		}
		
		// check if the session is linked to patterns
		$sql = "SELECT pattern_session_id FROM {sch_pattern_sessions} WHERE session_name_id = :id LIMIT 1";
		$result = db_query($sql, array(':id' => $session_name_id));
		if ( $result->rowCount() ) {
			// cannot delete, customer linked to assignments
			$msg = "Unable to delete " . $session->session_name .  ".  Session is linked to schedule patterns.";
			drupal_set_message(t($msg));	
			drupal_goto('sessions');
			return $form;	
		}
		
	
		$form['session_name_id'] = array(
			'#type' => 'value',
			'#value' => $session_name_id,
		);
	
		$form['session_name'] = array(
			'#type' => 'value',
			'#value' => $session->session_name,
		);
    
    $title = t('Delete Session') . '?';
    $question = t('Are you sure you want to delete?') . 
                '<h2>' . $session->session_name . '</h2><br />' . 
                t('This action cannot be undone.');
    $goto_if_canceled = 'sessions';
    $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, 'session_definition_delete_confirm() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

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

function session_definition_delete_confirm_submit($form, $form_state) {
	
	if ( $form_state['values']['confirm']) {
		$session_name_id = $form_state['values']['session_name_id'];
		$session_name = $form_state['values']['session_name'];
		
		// delete from database
		$num_rows = db_delete('sch_session_names')
								->condition('session_name', $session_name, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows == 1 ) {
			// success
			
			$msg = t('Session record, ') . '<b>' . $session_name . '</b>' . t(' has been deleted.');
		}
		else {
			$msg = t('Oops!  Unable to delete Session, ') . '<b>' . $session_name . '</b>.';
		}
		drupal_set_message(t($msg));	
	}
	
	drupal_goto('sessions');
}




/*
 *	_get_session_name()
 *
 *	retrieves the pattern record
 */

function _get_session_name($session_name_id = 0) {
	try {
		
		$session = (object) Null;
		
		if ( $session_name_id ) { 
			$query = db_select('sch_session_names', 'sn');
			$query->condition('session_name_id', $session_name_id);
			$query->fields('sn', array('session_name_id', 'session_name'));
			$result = $query->execute();
			if ( $result->rowCount() ) {
				$session = $result->fetchObject();
			}
		}												
		return $session;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_session_name() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	_get_session_list()
 *
 *	retrieves the general list of session names
 */

function _get_session_list() {
	try {
		
		//$sn_list[] = '- ' . t('Select') . ' -';
		$session_names = array();
		
		$query = db_select('sch_session_names', 'sn');
		$query->fields('sn', array('session_name_id', 'session_name'));
		$results = $query->execute();
		
		if ( $results->rowCount() ) {
			foreach ($results as $row) {
				$session_names[$row->session_name_id] = $row->session_name;
			}
		}
										
		return $session_names;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_session_list() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}


/*
 *	_get_session_name()
 *
 *	retrieves the pattern record
 */

function _get_session($schedule_id = 0, $session_id = 0) {
	try {
		
		$session = null;
		
		if (!empty($schedule_id) && !empty($session_id) ) { 
			$query = db_select('sch_schedule_sessions', 's');
      $query->leftJoin('sch_schedules', 'sch', 's.schedule_id = sch.schedule_id');
			$query->leftJoin('sch_session_names', 'sn', 's.session_name_id = sn.session_name_id');
			$query->condition('s.schedule_id', $schedule_id);
			$query->condition('s.schedule_session_id', $session_id);
			$query->fields('s', array('schedule_session_id', 'session_name_id', 'begin_time', 'end_time'))
            ->fields('sch', array('schedule_id', 'simulator_id', 'timezone'))
						->fields('sn', array('session_name'));
			$result = $query->execute();
			if ( $result->rowCount() ) {
				$session = $result->fetchObject();
			}
		}												
		return $session;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_session_name() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
}

/*
 *	_get_sessions()
 *
 *	returns a list of sessions for this schedule_id or the simulator
 */
function _get_sessions($schedule_id = 0, $simulator_id = 0, $key_by_id = False) {
	try {
		$sql = '';
		$sessions = array();
		
		if ( !$schedule_id && !$simulator_id ) { return $sessions; }
		
		// get the schedule_sessions for this simulator schedule
		$query = db_select('sch_schedule_sessions', 'ss');
    if ($schedule_id) {
      $query->innerJoin('sch_schedules', 's', 's.schedule_id = ss.schedule_id AND s.schedule_id = :schid', 
                        array(':schid' => $schedule_id));
    } else {
      $query->innerJoin('sch_schedules', 's', 's.schedule_id = ss.schedule_id');
    }
		$query->innerJoin('sch_session_names', 'sn', 'ss.session_name_id = sn.session_name_id');
		
		
		if ( $simulator_id ) {
			$query->condition('s.simulator_id', $simulator_id);
		}
		
		$query->fields('ss', array('schedule_session_id', 'schedule_id', 'session_name_id', 'begin_time', 'end_time'))
				  ->fields('sn', array('session_name'))
					->fields('s', array('simulator_id', 'timezone'));
		$query->orderBy('ss.begin_time', 'ASC');
		$results = $query->execute();

		if ( $results->rowCount() ) {
			if ( $key_by_id ) {
				foreach($results as $row) {
					$sessions[$row->schedule_session_id] = array(
						'schedule_session_id' => $row->schedule_session_id,
						'schedule_id' => $row->schedule_id,
						'session_name_id' => $row->session_name_id,
						'session_name' => $row->session_name,
						'begin_time' => $row->begin_time,
						'end_time' => $row->end_time,
            'timezone' => $row->timezone,
						'simulator_id' => $row->simulator_id,
					);
				}
			}
			else {
				$sessions = $results->fetchAll();
			}	
		}
		return $sessions;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_sessions() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}


/*
 * 		_calc_session_time()
 * 		Determine the total available session time
 * 		IN:   $session object 
 * 		OUT:	$session_begins_ts (unix timestamp),
 * 					$session_ends_ts (unix_timestamp)
 * 	  RETURNS total time
 */

function _calc_session_time($session, $mon, $day, $year, &$session_begins_ts, &$session_ends_ts, $timezone = '') {

  $session_begins_ts = _format_timestamp_parts($year, $mon, $day, 
                                               $session->begin_time, $timezone);
  $session_ends_ts = _format_timestamp_parts($year, $mon, $day, 
                                               $session->end_time, $timezone);

  if (((int) $session->begin_time) > ((int) $session->end_time)) {
    // session overlaps into next day
    // add 1 day of seconds
    // for most other things we want to get an accurate date calc regardless of DST
    // in March & Nov, but that results in a too short or too big block display
    // for this, we can ignore DST and just add seconds
    //$session_ends_ts += SCH_ONE_TS_DAY;
    $session_ends_ts = _add_day_ts($session_ends_ts);
  }

  /// DST FIX <<<<<
  //$session_begins_ts;
  //$session_ends_ts;
  //return $session_ends_ts - $session_begins_ts;
  
  // this function accommodates DST in the calcuation
  return _date_diff_seconds($session_begins_ts, $session_ends_ts);
  
}


	
