<?php
/**
 *		sabreScheduler Module for plugin to Drupal 7 Framework
 *
 *		Scheduler Report handlers
*/
require_once( drupal_get_path('module', 'sabreTools') . '/sabreTools.lib.inc');
require_once( drupal_get_path('module', 'sabreTools') . '/sabreTools.class.yearlist.inc');
require_once('sabreScheduler.classes.inc');
require_once('sabreScheduler.assignments.inc');
require_once('sabreScheduler.sessions.inc');

//require_once( $GLOBALS['base_url'] . QMS_LIBRARIES . 'PHPExcel/Classes/PHPExcel.php');


define('SCH_FILE_EXPORT_EXCEL_DIR', 'excel_reports');


/*
 * report_open_time()
 *
 */
function report_open_time($simulator_id = '', $interval = '', $begin_date = '', $end_date = '', 
                          $show_form_only = True) {
	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
		return '';
  }

	$content = '';
  
  
  $print_page_heading = 
									'<div class="sch-print-header">' . 
										'<div class="sch-page-title">' .	drupal_get_title() . '</div>' . 
									'</div><br />';


  $content .= (!$show_form_only) ? $print_page_heading : '<br class="clearBoth" />';
	
	$form_elems = drupal_get_form('open_time_report_form', $simulator_id, $interval, 
                                      $begin_date, $end_date);
	$content .= render($form_elems);

	if ( $interval ) {
		$content .= _get_open_time_list($simulator_id, $interval, $begin_date, $end_date);
	}
	
	return $content;
}




/*
 * 	open_time_report_form()
 *
 */

function open_time_report_form($form, $form_state, $simulator_id = '', $interval = '', 
                                $begin_date = '', $end_date = '') {
	/*
	$simulator_id = arg(2);
	$interval = arg(3);
	$date_range = arg(4);
	*/
	
	drupal_add_library('system','ui.dialog');
	drupal_add_library('system','ui.datepicker');
	drupal_add_js(drupal_get_path('module', 'sabreScheduler') . '/js/sabreScheduler.report.opentime.js');
	
	$goto_report_url = url('reports/opentime');
	$return_url = url('manage');
	$search_dates = array();
	
	//if ( $interval == 'C' ) {    $search_dates = explode('&', $date_range);  }
	
	// Get list of simulators to display -- active + inactive
	$simulator_list = new SimulatorList();
	$interval_list = new IntervalList();
	
	
	$form['report_box'] = array(
		'#type' => 'fieldset',
		'#title' => t('Report Settings'),
		'#attributes' => array('id' => 'sch-report-settings-div'),
	);
	
	$form['report_box']['form_table_begin'] = array(
		'#markup' => '<table class="qms-plain-table" style="width:100%;"><tr>',
	);


	$form['report_box']['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Select a Simulator') . '<span>&nbsp;&nbsp;(* = ' . t('inactive')  . ')</span>',
		'#options' => $simulator_list->getScheduledSimSelectList(SimulatorList::INCL_ALL),
		
		'#attributes' => array( 'id' => 'sch-simulator-list',
														'class' => array('qms-select')),
		'#default_value' => (int)$simulator_id,
    '#prefix' => '<td style="width:40%;">',
		'#suffix' => '</td>',
	);

	$form['report_box']['interval'] = array(
		'#type' => 'select',
		'#title' => t('Select the Interval'),
		'#options' => $interval_list->get(),
		'#default_value' => $interval,
		'#attributes' => array( 'id' => 'sch-interval-list' ,
														'style' => 'width:100px;'),
		'#prefix' => '<td>',
		'#suffix' => '</td></tr>',
	);
	
	$form['report_box']['from_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('From Date'),
		'#size' => 10,
		'#date_format' => 'm-d-Y',		
		'#default_value' => (isset($begin_date) ? $begin_date : ''),		
		'#attributes' => array(	'id' => 'sch-from-date',
														'class' => array('qms-date-picker')),
		'#prefix' => '<tr><td  colspan="2"><div id="sch-report-dates">',
		
	);

	$form['report_box']['to_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('To Date'),
		'#size' => 10,
		'#date_format' => 'm-d-Y',
		'#default_value' => (isset($end_date) ? $end_date : ''),	
		'#attributes' => array('id' => 'sch-to-date',
													  'class' => array('qms-date-picker')),
		'#suffix' => '</div></td></tr>',
	);
	
	
	$form['report_box']['form_table_end'] = array(
		'#markup' => '</table>',
	);
	
	$form['report_box']['actions'] = array( 
		'#type' => 'actions',
		'#attributes' => array('style' => 'margin-bottom:0;'),
	);
	$form['report_box']['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
		'#attributes' => array('id' => 'sch-btn-submit',
                           'style' => 'font-weight:bold',
													 'sch-url' => $goto_report_url ),  // close screen, go to home page
	);
  $form['report_box']['actions']['clear'] = array(
		'#type' => 'button',
		'#value' => t('Clear'),
		'#attributes' => array('class' => array('sch-clear', 'qms-btn-extra')),
	);

	
	
	// storage area for dynamic dialog elements
	$form['popup_dialog'] = array(
		'#markup' => '<div id="sch-popup-dialog"></div>',
	);

	
	return $form;
	

}

/*
 * _get_open_time_list()
 *
 */

function _get_open_time_list($simulator_id = '', $interval = '', $begin_date = '', $end_date = '') {
	try{
		
		$begin_date_ts = 0;
		$end_date_ts = 0;
		$now = _st_format_system_timestamp('now');

		if ( $interval == '7') { 			// 7 days
//			$begin_date_ts = REQUEST_TIME;
//			$end_date_ts = strtotime('+ 7 days');
      $begin_date_ts = $now;
      $end_date_ts = _st_modify_system_timestamp($now, '+7 days');

		}
		else if ( $interval == '30') { // 30 days
			$begin_date_ts = $now;
			$end_date_ts = _st_modify_system_timestamp($now, '+30 days');

		}
		else if ($interval == 'C') {	// custom
			//$dr = explode('&', $date_range);
			$begin_date_ts = ( !strlen($begin_date) ? 
                             $now : 
                            _st_modify_system_timestamp($begin_date . ' 00:00:00') );
			$end_date_ts = ( !strlen($end_date) ? 
                            _st_modify_system_timestamp($now, '+7 days') : 
                            _st_format_system_timestamp($end_date . ' 23:59:59') );
		}
		
		
	
		$table_header = array( 
			array( 'data' => t('Date'), 'class' => array('sch-tbl-session-date') ),
			array( 'data' => t('Time'), 'class' => array('sch-tbl-session-time') ),
			array( 'data' => t('Session'), 'class' => array('sch-tbl-session-name') ),
		);
		
		$sl = new SimulatorList();
		$sim_list = array();
		
		if ( $simulator_id ) {
			$sim_list[] = $sl->getScheduledSim((int)$simulator_id);  // returns an object
		}
		else {  // simulator not specified, retrieve ALL
			$sim_list = $sl->getScheduledSimList();  // returns an array
		}
		
		$sim_count = count($sim_list);
		if ( !$sim_count ) {
			drupal_set_message( t('Scheduled simulators not found'), 'status');
			drupal_goto('manage');
			return;
		}
		
		$date_list = _get_calendar_dates($begin_date_ts, $end_date_ts);
		
		
		$content = '<div id="sch-open-sessions-div">';
		
		for ( $s = 0; $s < $sim_count; $s++ ) {
			
			
			// get the schedule_sessions for this simulator schedule
			$sessions = _get_sessions($sim_list[$s]->schedule_id);
			
			// get assignments
			$assignments = _get_assignments($begin_date_ts, $end_date_ts, $sim_list[$s]->schedule_id);
		
			
			$i = 0;
			$table_rows = array();
			$sessValidator = new SessionValidator();
		
			for ( $d = 0; $d < count($date_list); $d++) {
			
				foreach($sessions as $sess) {
				
					$open = False;
          
					$day = _st_format_schedule_date($date_list[$d], 'j', $sess->timezone);
					//$assignment_id = ( isset($assignments[$s->schedule_session_id][$day]) ? $assignments[$s->schedule_session_id][$day] : 0 );
				
					$sessValidator->clear();
					$sessValidator->init(0, 0, $sess->schedule_id, $sess->schedule_session_id, $date_list[$d]);
					$sessValidator->setSession($sess);
					//$sessValidator->setExceptions($exceptions);
					$row_data = array();
				
					
					$open = (SessionValidator::SV_NOCONFLICT == $sessValidator->checkForConflictWithException());
				
					if ( !isset($assignments[$sess->schedule_session_id][$day][0]) && $open ) {
						$begin_time =  _st_left($sess->begin_time, 2) . ':' . _st_right($sess->begin_time, 2);
						$end_time =  _st_left($sess->end_time, 2) . ':' . _st_right($sess->end_time, 2);
						
						$row_data = array(
							_st_format_schedule_date($date_list[$d], 'n/j/Y', $sess->timezone),
							$begin_time . ' - ' . $end_time,
							$sess->session_name,
						);
					}
          
          
				
					$table_rows[] = array('data' => $row_data);
					$i++;
				}
			
			}
      
      //$sl->getName($sim_list[$s]->simulator_id);
      
			$content .= '<h3>' . t('Open Sessions') . ' - ' . 
                      $sl->getName($sim_list[$s]->simulator_id) . ': ' . 
                      $sim_list[$s]->schedule_name . '</h3>';
			$content .= theme( 'table', array(
				'header' => $table_header,
				'rows' => $table_rows,
				'empty' => t('None'),
			));
			$content .= '<br />';
		
		}
	
		return $content;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_open_time_list() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}

/*
 *	report_customer_detail()
 *	
 *	handles both the normal customer detail report & the customer cut_bill report
 */
function report_customer_detail($mode = 'DETAIL', $customer_id = 0, $simulator_id = 0, $view_month = '', $view_year = '') {
	
	if ( !user_access('view manage menu') ) {
    drupal_set_message( t('Unauthorized Access.  Permission is required.'));
		drupal_goto('');
		return '';	
	}		
	
	// if not specified, use the current month and year
	if ( $view_month == '' ) {
		$view_month = date('F');
	}
	if ( $view_year == '' ) {
		$view_year = date('Y');
	}
	
	drupal_add_js(drupal_get_path('module', 'sabreScheduler') . '/js/sabreScheduler.report.detail.js');
	
	global $base_url;
	global $theme;
	$content = '';
	$sub_title = '';
	
	if ( $customer_id ) {
		
		// printing -- heading (logo & title) to top each grid page
		if ( 'DETAIL' == $mode ) {
			$sub_title = t('Customer Schedule Detail Report');
		}
		else { // CUTBILL
			$sub_title = t('Customer Cut/Billable Report');
		}
		
		$print_page_heading = 
										'<div class="sch-print-header">' . 
											//'<img src="' . $base_url . '/sites/all/themes/' . $theme . '/images/logo.png" />' . 
											'<div class="sch-page-title">' .	drupal_get_title() . '</div>' . 
											'<div class="sch-page-subtitle">' . $sub_title . '</div>' .
										'</div>';
		
		$content .= $print_page_heading;
		
		
	}
	
  $form_elems = drupal_get_form('customer_detail_form', $mode, $customer_id, $simulator_id, $view_month, $view_year);
	$content .= render($form_elems);
	
	if ( $customer_id ) {
		$content .= _get_customer_detail_report($mode, $customer_id, $simulator_id, $view_month, $view_year);
	}
	
	return $content;
}




/*
 *	customer_detail_form()
 *
 */
function customer_detail_form($form, $form_state, $mode, $customer_id, $simulator_id, $view_month = '', $view_year = '') {
	
	global $base_url;
	$month_list = new MonthList();
	$year_list = new YearList();
	$width = ($customer_id ? '100%' : '95%');
	
	$goto_url = ( 'DETAIL' == $mode ) ? 'reports/customer/detail' : 'reports/customer/cutbill';
	
	$month_array = $month_list->get(); // includes '- select -' option, need to remove this to calc next/prev month
	array_shift($month_array);
	
	$href_prev_month = _st_array_key_relative($month_array, $view_month, -1);
	$href_prev_year = ((int)$view_year);

	if ( ($href_prev_month === False) ) {
		$href_prev_month = 'December';
		$href_prev_year--;
	}
	$href_next_month = _st_array_key_relative($month_array, $view_month, 1);
	$href_next_year = ((int)$view_year);
	if ( ($href_next_month === False) || ($href_next_month == 'January') ) {
		$href_next_month = 'January';
		$href_next_year++;
	}
		
	$form['report_box'] = array(
		'#type' => 'fieldset',
		'#title' => t('Settings'),
		'#attributes' => array('id' => 'sch-report-box')
	);
	
	
	
	$form['report_box']['form_table_begin'] = array(
		'#markup' => '<div id="sch-grid-view-form">' .
								 '<table class="qms-plain-table" style="vertical-align:bottom;width:' . $width . ';height:5em;"><tr>',
	);
	
	
	$simulator_list = new SimulatorList();
	
	$form['report_box']['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Select a Simulator') . '<span>&nbsp;&nbsp;(* = ' . t('inactive')  . ')</span>',
		'#options' => $simulator_list->getScheduledSimSelectList(SimulatorList::INCL_ALL),
		'#default_value' => ($simulator_id ? $simulator_id : 0),
		'#attributes' => array( 'id' => 'sch-simulator-select',
														'class' => array('qms-select')),
		'#default_value' => (int)$simulator_id,
		'#validated' => True,
		'#prefix' => '<td>&nbsp;</td><td colspan="2" style="vertical-align:bottom;text-align:left;">' ,
		'#suffix' => '</td>',
	);
	
	$customer_list = new CustomerList();

	$form['report_box']['customer'] = array(
		'#type' => 'select',
		'#title' => t('Customer'),
		'#required' => True,
		'#options' => ($customer_id ? $customer_list->getAll(CustomerList::NO_SELECT_OPT) : $customer_list->getAll()),
		'#default_value' => ($customer_id ? $customer_id : 0),
		'#validated' => True,
		'#attributes' => array('id' => 'sch-customer-select',
													 'class' => array('qms-select')),
		'#prefix' => '<td colspan="2" style="vertical-align:bottom;text-align:left;">' ,
		'#suffix' => '</td><td>&nbsp;</td>',
	);	
	
	$form['report_box']['form_table_markup'] = array(
		'#markup' => '</tr><tr>',
	);
	
	// if the customer_id == 0, first time the form is being processed, hide the 
	// navigation arrows, buttons, but show the 'submit' button
	$hide = 'style="visibility:hidden;" ';
	
	$form['report_box']['go_left'] = array(
		'#markup' => 
			'<td style="vertical-align:bottom;width:4em;">' . 
		  '<a ' . ($customer_id ? '' : $hide) . 'href="' . 
		  url($goto_url . '/' . $customer_id . '/' . $simulator_id . '/' . $href_prev_month . '/' . $href_prev_year )  . '">' .
		  '<img class="sch-grid-arrow" src="' . $base_url . QMS_IMAGES_DIR . 'go_left.png' . '" />' .
		  '</a></td>',
	);
	$form['report_box']['view_month'] = array(
		'#type' => 'select',
		'#title' => t('View Month'),
		'#options' => $month_list->get(),
		'#default_value' => $view_month,
		'#required' => False,
		'#attributes' => array('id' => 'sch-view-month-select'),
		'#prefix' => '<td style="vertical-align:bottom;width:10em;">',
		'#suffix' => '</td>',
	);
	$form['report_box']['view_year'] = array(
		'#type' => 'select',
		'#title' => t('View Year'),
		'#options' => $year_list->get(),
		'#default_value' => (int)$view_year,
		'#required' => False,
		'#attributes' => array('id' => 'sch-view-year-select'),
		'#prefix' => '<td style="vertical-align:bottom;">',
		'#suffix' => '</td>',
	);
	
	$form['report_box']['go_to'] = array(
		'#type' => 'button',
		'#default_value' => ( $customer_id ? t('GO') : t('Submit') ),
		'#attributes' => array('class' => array('sch-btn'),
													 'id' => 'sch-btn-submit'),
		'#prefix' => '<td style="vertical-align:bottom;width:7em;">',
		'#suffix' => '</td>',

	);
	
	if ( $customer_id ) {
		$form['report_box']['view_today'] = array(
			'#type' => 'button',
			'#default_value' => t('Today'),
			'#attributes' => array('class' => array('sch-btn'),
														 'id' => 'sch-btn-view-today'),
			'#prefix' => '<td style="vertical-align:bottom;width:7em;">',
			'#suffix' => '</td>',

		);
	}
	
	
	$form['report_box']['go_right'] = array(
		'#markup' => 
			'<td style="vertical-align:bottom;text-align:center;width:5em;">' .
			'<a ' . ($customer_id ? '' : $hide) . 'href="' . 
			url($goto_url . '/' . $customer_id . '/' . $simulator_id . '/' . $href_next_month . '/' . $href_next_year)  . '">' .
			'<img class="sch-grid-arrow" src="' . $base_url . QMS_IMAGES_DIR . 'go_right.png' . '" />' .
			'</a></td>',
	);
	
	
	
	$form['report_box']['href_base'] = array(
		'#type' => 'textfield',
		'#default_value' => url($goto_url),
		'#attributes' => array('class' => array('qms-hidden'),
													 'id' => 'sch-schedule-grid-href-base'),
		//'#suffix' => '</td>',		
	);
	
	$form['report_box']['form_table_end'] = array(
		'#markup' => '</tr></table></div>',
	);
	
	$form['message_box'] = array(
		'#markup' => '<div id="qms-message-box"></div>',
	);
	
	return $form;
}




/*
 *	_get_customer_detail_report()
 *
 */

function _get_customer_detail_report($mode, $customer_id, $simulator_id, $view_month = '', $view_year = '') {
	try {
		$content = '';
    $now = _st_modify_timestamp(0);
		
		$begin_date = 'first day of ' . $view_month . ' ' . $view_year . ' 00:00:00';
		$begin_date_ts = _st_modify_timestamp($now, $begin_date);
		$end_date = 'last day of ' . $view_month . ' ' . $view_year . ' 23:59:59';
		$end_date_ts = _st_modify_timestamp($now, $end_date);
		
		$cutbill = ('CUTBILL' == $mode) ? 1 : 0;
		
		$assignments = _get_customer_assignments($customer_id, $simulator_id, $begin_date_ts, $end_date_ts, $cutbill);
		
		//$content = 'Found ' . count($assignments) . ' records';
		
		$table_header = array( 
			array( 'data' => t('Date'), 'class' => array('sch-tbl-assignment-date2') ),
			array( 'data' => t('Day'), 'class' => array('sch-tbl-assignment-dow') ),
			array( 'data' => t('Start'), 'class' => array('sch-tbl-assignment-begins') ),
			array( 'data' => t('Finish'), 'class' => array('sch-tbl-assignment-ends') ),
			array( 'data' => t('Total Time'), 'class' => array('sch-tbl-assignment-time') ),
			array( 'data' => t('Simulator'), 'class' => array('sch-tbl-assignment-simulator') ),
		);
		if ( $cutbill ) {
			$table_header[] = array( 'data' => t('Cancelled'), 'class' => array('sch-tbl-assignment-cut') );
		}
		
		$table_rows = array();
		
		$i = 0;
		
    if (count($assignments)) {
      foreach($assignments as $assign) {
        $ihours = 0;
        $imins = 0;
        $diff = $assign->end_timestamp - $assign->begin_timestamp;
        _st_calc_seconds_to_hours_minutes($diff, $ihours, $imins);

        $row_data = array(
          _st_format_system_date($assign->begin_timestamp, 'm/d/Y'),
          _st_format_system_date($assign->begin_timestamp, 'D'),
          _st_left($assign->begin_time_actual, 2) . ':' . _st_right($assign->begin_time_actual, 2),
          _st_left($assign->end_time_actual, 2) . ':' . _st_right($assign->end_time_actual, 2),
          sprintf('%02d:%02d', $ihours, $imins),
          _st_format_sim_name($assign->sim_name, $assign->device_id_internal),
        );
        if ( $cutbill ) {
          $row_data[] = _st_format_system_date($assign->updated_date, 'm/d/Y');
        }

        $table_rows[] = array('data' => $row_data);
        $i++;

      }
    }
		$content = '<div id="sch-customer-detail-div">';
		$content .= theme( 'table', array(
			'header' => $table_header,
			'rows' => $table_rows,
			'empty' => t('None'),
		));
		$content .= '</div>';
		
		return $content;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_detail_report() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}

/*
 *	report_summary_month()
 *
 */
function report_monthly_summary($view_month = '', $view_year = '', $show_form_only = True) {
	
	if ( !user_access('view manage menu') ) {
    drupal_set_message( t('Unauthorized Access.  Permission is required.'));
		drupal_goto('');
		return '';	
	}		
	
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	drupal_add_js(drupal_get_path('module', 'sabreScheduler') . '/js/sabreScheduler.report.summary.js');
	
	global $base_url;
	global $theme;
	$content = '';
	
	
	// if not specified, use the current month and year
	if ( $view_month == '' ) {
		$view_month = date('F');
	}
	if ( $view_year == '' ) {
		$view_year = date('Y');
	}
	
	$sub_title =  t($view_month) . ' ' . $view_year;
	$print_page_heading = 
									'<div class="sch-print-header">' . 
										//'<img src="' . $base_url . '/sites/all/themes/' . $theme . '/images/logo.png" />' . 
										'<div class="sch-page-title">' .	drupal_get_title() . '</div>' . 
										'<div class="sch-page-subtitle">' . $sub_title . '</div>' .
									'</div><br />';
	
	

  $content .= (!$show_form_only) ? $print_page_heading : '<br />';
	
	$form_elems = drupal_get_form('monthly_summary_form', $view_month, $view_year, $show_form_only);
	$content .= render($form_elems);
	
	
	if ( !$show_form_only ) {
		$content .= _get_monthly_summary_report($view_month, $view_year);
	}
	
	return $content;
}


/*
 *	monthly_summary_form()
 *
 */
function monthly_summary_form($form, $form_state, $view_month = '', $view_year = '', $show_form_only = True) {
	
	global $base_url;
	$month_list = new MonthList();
	$year_list = new YearList();
	
	$goto_url = 'reports/summary/monthly';
	
	$hidden = '';
	if ( $show_form_only ) {	$hidden = ' style="visibility:hidden;" '; }
	
	$month_array = $month_list->get(); // includes '- select -' option, need to remove this to calc next/prev month
	array_shift($month_array);
	
	$href_prev_month = _st_array_key_relative($month_array, $view_month, -1);
	$href_prev_year = ((int)$view_year);

	if ( ($href_prev_month === False) ) {
		$href_prev_month = 'December';
		$href_prev_year--;
	}
	$href_next_month = _st_array_key_relative($month_array, $view_month, 1);
	$href_next_year = ((int)$view_year);
	if ( ($href_next_month === False) || ($href_next_month == 'January') ) {
		$href_next_month = 'January';
		$href_next_year++;
	}
		
	$form['report_box'] = array(
		'#type' => 'fieldset',
		'#title' => t('Settings'),
		'#attributes' => array('id' => 'sch-report-box')
	);
	
	$form['report_box']['form_table_begin'] = array(
		'#markup' => '<div id="sch-grid-view-form">' .
								 '<table class="qms-plain-table" style="vertical-align:bottom;width:95%;height:5em;"><tr>',
	);
		
	

	$form['report_box']['go_left'] = array(
		'#markup' => 
			'<td style="vertical-align:bottom;width:4em;">' . 
		  '<a ' . $hidden . 'href="' . url($goto_url . '/' . $href_prev_month . '/' . $href_prev_year )  . '">' .
		  '<img class="sch-grid-arrow" src="' . $base_url . QMS_IMAGES_DIR . 'go_left.png' . '" />' .
		  '</a></td>',
	);

	
	$form['report_box']['view_month'] = array(
		'#type' => 'select',
		'#title' => t('View Month'),
		'#options' => $month_list->get(),
		'#default_value' => $view_month,
		'#required' => False,
		'#attributes' => array('id' => 'sch-view-month-select'),
		'#prefix' => '<td style="vertical-align:bottom;width:10em;">',
		'#suffix' => '</td>',
	);
	$form['report_box']['view_year'] = array(
		'#type' => 'select',
		'#title' => t('View Year'),
		'#options' => $year_list->get(),
		'#default_value' => (int)$view_year,
		'#required' => False,
		'#attributes' => array('id' => 'sch-view-year-select'),
		'#prefix' => '<td style="vertical-align:bottom;">',
		'#suffix' => '</td>',
	);
	
	$form['report_box']['go_to'] = array(
		'#type' => 'button',
		'#default_value' => ( $show_form_only ? t('Submit') : t('GO')  ),
		'#attributes' => array('class' => array('sch-btn'),
													 'id' => 'sch-btn-submit'),
		'#prefix' => '<td style="vertical-align:bottom;width:7em;">',
		'#suffix' => '</td>',

	);
	
	if ( !$show_form_only ) {
		$form['report_box']['view_today'] = array(
			'#type' => 'button',
			'#default_value' => t('Today'),
			'#attributes' => array('class' => array('sch-btn'),
														 'id' => 'sch-btn-view-today'),
			'#prefix' => '<td style="vertical-align:bottom;width:7em;">',
			'#suffix' => '</td>',

		);
	}


	$form['report_box']['go_right'] = array(
		'#markup' => 
			'<td style="vertical-align:bottom;text-align:center;width:5em;">' .
			'<a ' . $hidden . 'href="' .  url($goto_url . '/' . $href_next_month . '/' . $href_next_year)  . '">' .
			'<img class="sch-grid-arrow" src="' . $base_url . QMS_IMAGES_DIR . 'go_right.png' . '" />' .
			'</a></td>',
	);

		
	$form['report_box']['form_table_end'] = array(
		'#markup' => '</tr></table></div>',
	);
	
	$form['report_box']['href_base'] = array(
		'#type' => 'textfield',
		'#default_value' => url($goto_url),
		'#attributes' => array('class' => array('qms-hidden'),
													 'id' => 'sch-report-href-base'),
	);
	
	
	return $form;
}


/*
 *		_get_monthly_summary_report()
 *
 *		retrieves a list of hours
 *			grouped by simulator
 *			grouped by customer
 *      within the date range
 *    			dates are expected in unix timestamp format
 * 	 returns:  array of objects
 */

function _get_monthly_summary_report($view_month, $view_year) {
	try {
		
		$content = '';
    $now = _st_modify_timestamp(0);
		
		if ( !strlen($view_month) || !strlen($view_year) ) { return $content; }
		
		$begin_date = 'first day of ' . $view_month . ' ' . $view_year . ' 00:00:00';
		$begin_date_ts = _st_modify_timestamp($now, $begin_date);
		$end_date = 'last day of ' . $view_month . ' ' . $view_year . ' 23:59:59';
		$end_date_ts = _st_modify_timestamp($now, $end_date);
		
		$table_header = array( 
			array( 'data' => t('Simulator'), 'class' => array('sch-tbl-summary-sims') ),
			array( 'data' => t('Customer'), 'class' => array('sch-tbl-summary-customers') ),
			array( 'data' => t('Hours'), 'class' => array('sch-tbl-summary-hours') ),
		);
		$table_rows = array();
		
		$i = 0;
		
		// include cut_bill'ed assignments for this report
		
		$sql = "SELECT sim.simulator_id, sim.sim_name, sim.device_id_internal, 
                   c.customer_id, c.customer, SUM(a.total_time) as `sum_time` 
					  FROM 	 {sch_assignments} a, {sch_schedules} sch, {sch_customers} c, {sch_simulators} sim 
					  WHERE	 a.schedule_id = sch.schedule_id 
					  AND		 a.customer_id = c.customer_id 
					  AND		 sch.simulator_id = sim.simulator_id 
					  AND		 a.begin_timestamp >= :bdr 
					  AND		 a.begin_timestamp <= :edr 
						AND	   a.cut_bill = 0 
					  GROUP BY sch.simulator_id, a.customer_id 
					  ORDER BY sim.sim_name, sim.device_id_internal, c.customer";
					
		
				
		$results = db_query($sql, array(':bdr' => $begin_date_ts, ':edr' => $end_date_ts ));
		
		$last_sim_id = 0;
		$last_sim_name = '';
		$subtotal = 0;
		$grand_total = 0;
		$i = 0;
		
		if ( $results->rowCount() ) {
			foreach($results as $row) {
				
				if ( $i && ($last_sim_id != $row->simulator_id)) {
					$row_data = array(
						'',
						array('data' => t('Total for') . ' ' . $last_sim_name, 
                  'class' => array('sch-tbl-summary-subtotal')),
						array('data' => sprintf('%0.1f', $subtotal / (60 * 60)), 
                  'class' => array('sch-tbl-summary-subtotal')),
					);
					$table_rows[] = array('data' => $row_data);
					$subtotal = 0;
				}
        
        $sim_name = _st_format_sim_name($row->sim_name, $row->device_id_internal);
				
				
				$row_data = array(
					// only print the sim name if it's different than the one before
					array('data' => (($last_sim_id != $row->simulator_id) ? $sim_name : ''), 
                'class' => array('sch-tbl-summary-sims')) ,
					$row->customer,
					array('data' => sprintf('%0.1f', $row->sum_time / (60 * 60)), 
                'class' => array('sch-tbl-summary-hours')),
				);
				$table_rows[] = array('data' => $row_data);
				
				$subtotal += $row->sum_time;
				$grand_total += $row->sum_time;
				$last_sim_id = $row->simulator_id;
				$last_sim_name = $sim_name;
				$i++;
			}
			
			if ( $i ) {
				$row_data = array(
					'',
					array('data' => t('Total for') . ' ' . $last_sim_name, 
                'class' => array('sch-tbl-summary-subtotal')),
					array('data' => sprintf('%0.1f', $subtotal / (60 * 60)), 
                'class' => array('sch-tbl-summary-subtotal')),
				);
				$table_rows[] = array('data' => $row_data);
			}	
					
		}
		$row_data = array(
			'',
			array('data' => t('GRAND TOTAL'), 'class' => array('sch-tbl-summary-grand-total')),
			array('data' => sprintf('%0.1f', $grand_total / (60 * 60)), 'class' => array('sch-tbl-summary-grand-total')),
		);
		$table_rows[] = array('data' => $row_data);
		
		$content = '<div id="sch-monthly-summary-div">';
		$content .= theme( 'table', array(
			'header' => $table_header,
			'rows' => $table_rows,
			'empty' => t('None'),
		));
		$content .= '</div>';
		
													
		return $content;
	}
	catch (Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_summary_report() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	} 
	
}

/*
 *    report_schedule_by_month_excel_export ()
 * 
 *    Derived from 'schedule_grid_display' that builds the main schedule grid
 * 
 *    IN:       $simulator_id, 
 *              $customer_id, 
 *              $view_month ['January|February|March|...],
 *              $view_year [4-digit year (string)]
 *    RETURN:   Schedule Grid display, single page, by month
 */

/*
function report_schedule_by_month_excel_export($simulator_id, $customer_id = 0, 
                                                $view_month = '', $view_year = '')  {
  
  if (!$simulator_id) {
    drupal_set_message(t('Error: Invalid simulator id.'));
    drupal_goto('schedules');
    return;
  }
  
  drupal_add_js('(function($) {
										Drupal.behaviors.schViewPrint = {
											attach: function(context, settings) {
												$(".qms-print", context).click(function() {
                          window.print();
                          return false;
                        });
											}
										}
									}(jQuery));', 'inline');

  // if not specified, use the current month and year
  if ($view_month == '') {
    $view_month = date('F');
  }
  if ($view_year == '') {
    $view_year = date('Y');
  }

  _build_schedule_report_excel_export($simulator_id, $customer_id, 
                                                 $view_month, $view_year);
  
  //$form_elems = drupal_get_form('schedule_excel_report_form');
  //$content .= render($form_elems);

  
}
 * */
 

/*
 *  report_schedule_excel_export_form()
 * 
 * 
 */

function report_schedule_excel_export_form($form, $form_state, 
                        $simulator_id, $schedule_id, $customer_id, $view_month = '', $view_year = '') {
  
  $month_list = new MonthList();
  $year_list = new YearList();
  
  // if not specified, use the current month and year
  if ($view_month == '') {
    $view_month = date('F');
  }
  if ($view_year == '') {
    $view_year = date('Y');
  }
  
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

	if( !strlen($goto_url) || ($goto_url == current_path()) ) {
		$goto_url = 'schedule/grid/' . $simulator_id . '/' . $schedule_id . '/' . $customer_id . '/' . 
                                  $view_month . '/' . $view_year;
	}
  
  
  
  $form['settings'] = array(
		'#type' => 'fieldset',
		'#title' => t('Export Settings'),
		'#attributes' => array('id' => 'sch-report-settings-div'),
	);
  
  $form['settings']['begin_table'] = array (
    '#markup' => '<table class="qms-plain-table" style="width:85%"><tr>',
  );
  
  $form['settings']['from_month'] = array(
      '#type' => 'select',
      '#title' => t('From Month'),
      '#options' => $month_list->get(MonthList::NO_SELECT_OPT),
      '#default_value' => $view_month,
      '#required' => False,
      '#attributes' => array('id' => 'sch-from-month-select'),
      '#prefix' => '<td style="width:5em;">',
      '#suffix' => '</td>',
  );
  
  
  $form['settings']['from_year'] = array(
      '#type' => 'select',
      '#title' => t('Year'),
      '#options' => $year_list->get(YearList::NO_SELECT_OPT),
      '#default_value' => (int) $view_year,
      '#required' => False,
      '#attributes' => array('id' => 'sch-from-year-select'),
      '#prefix' => '<td style="width:5em;">',
      '#suffix' => '</td>',
  );
  
  $form['settings']['table_middle'] = array (
    '#markup' => '<td style="width:5em;">&nbsp;</td>',
  );
  
  $form['settings']['to_month'] = array(
      '#type' => 'select',
      '#title' => t('To Month'),
      '#options' => $month_list->get(MonthList::NO_SELECT_OPT),
      '#default_value' => $view_month,
      '#required' => False,
      '#attributes' => array('id' => 'sch-to-month-select'),
      '#prefix' => '<td style="width:5em;">',
      '#suffix' => '</td>',
  );
  
  
  $form['settings']['to_year'] = array(
      '#type' => 'select',
      '#title' => t('Year'),
      '#options' => $year_list->get(YearList::NO_SELECT_OPT),
      '#default_value' => (int) $view_year,
      '#required' => False,
      '#attributes' => array('id' => 'sch-to-year-select'),
      '#prefix' => '<td style="width:5em;">',
      '#suffix' => '</td>',
  );
  
  $form['settings']['end_table'] = array (
    '#markup' => '</tr></table>',
  );
  
  // buttons
	$form['settings']['actions'] = array('#type' => 'actions');
	$form['settings']['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
	);
  $form['settings']['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                url($goto_url) . '"; return false;'),
	);
  
  $form['simulator_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $simulator_id,
    '#attributes' => array('class' => array('qms-hidden'),
                            'id' => 'sch-simulator-id'),
  );
  
  $form['schedule_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $schedule_id,
    '#attributes' => array('class' => array('qms-hidden'),
                            'id' => 'sch-schedule-id'),
  );
  
  $form['customer_id'] = array(
    '#type' => 'textfield',
    '#default_value' => $customer_id,
    '#attributes' => array('class' => array('qms-hidden'),
                            'id' => 'sch-customer-id'),
  );
  
  
  // include table of previously exported reports (up to 7 days old)
  // for this user only
  
  $export_files_table = _get_excel_export_files_table();
  
  $form['export_files'] = array(
    '#markup' => $export_files_table,
  );
  
  
  
  return $form;
}

/*
 *  report_schedule_excel_export_form_validate()
 */

function report_schedule_excel_export_form_validate($form, $form_state) {
  
  $from_month = $form_state['values']['from_month'];
  $from_year = $form_state['values']['from_year'];
  $to_month = $form_state['values']['to_month'];
  $to_year = $form_state['values']['to_year'];
  $now = _st_modify_timestamp(0);
  
  $from_text = 'first day of ' . $from_month . ' ' . $from_year;
  $to_text = 'last day of ' . $to_month . ' ' . $to_year;

  $from_ts = _st_modify_timestamp($now, $from_text);
  $to_ts = _st_modify_timestamp($now, $to_text);
  
  if ( $from_ts > $to_ts ) {
    form_set_error('from_month', t('Invalid Report Date Range'));
  }
  
}

/*
 *  report_schedule_excel_export_form_submit()
 * 
 */
function report_schedule_excel_export_form_submit($form, $form_state) {
  
   
  $customer_id = (int)$form_state['values']['customer_id'];
  $simulator_id = (int)$form_state['values']['simulator_id'];
  $schedule_id = (int)$form_state['values']['schedule_id'];
  
  $from_month = $form_state['values']['from_month'];
  $from_year = $form_state['values']['from_year'];
  $to_month = $form_state['values']['to_month'];
  $to_year = $form_state['values']['to_year'];
  
  $from_month_year = $from_month . ' ' . $from_year;
  $to_month_year = $to_month . ' ' . $to_year;

  
  _build_schedule_report_excel_export($simulator_id, $schedule_id, $customer_id, 
                                     $from_month_year, $to_month_year);
  // we need to outmaneuver drupal_goto as it wants to force the redirect to
  // the destination path and we don't want that...yet
  $dest_url = '';
  
  if ( isset($_GET['destination']) ) {
    $dest_url = $_GET['destination'];
  }
  
  $_GET['destination'] = current_path();
  
  drupal_goto();
  
  $_GET['destination'] = $dest_url;
}


/*
 *  _build_schedule_report_excel_export()
 * 
 *  if no month or year specified, returns the report for the current month/year
 * 
 *  IN:       $simulator_id, 
 *            $customer_id, 
 *            $view_month ['January|February|March|...],
 *            $view_year [4-digit year (string)]
 *  RETURN:   Schedule Grid display, single page, by month
 */
function _build_schedule_report_excel_export($simulator_id, $schedule_id, $customer_id = 0, 
                                             $from_month_year, $to_month_year) {
  try {
    // schedule display
      
    
    module_load_include('inc', 'phpexcel', 'phpexcel');

    global $base_url;
    global $theme;
    
    // init the lookup class here for reference in the phpexcel hook function
    global $customer_colors;
    $customer_colors = new CustomerColorLookup();

    // get the schedule_sessions for this simulator schedule
    $simulator = (object) Null;
    $sessions = array();
    $schedule_id = 0;
    $time_blocks = array();
    $session_id = 0;
    $schedule_id = 0;
    $timezone = '';
    
    // MAIN EXCEL DATA array 
    // indexes [worksheet][row 1-based][col 0-based]
    $excel_data = array();

    
    $org_name = variable_get('organization_name', '');
    
    //$return_url = 'schedule/grid/' . $simulator_id . '/' . $customer_id;
    
    $simulator = _get_simulator($simulator_id);
    
    if ( Null == $simulator ) {
      drupal_set_message(t('Simulator Not Found'));
      //drupal_goto($return_url); // handle the return from the calling handliner
      return;
    }

    // $sessions array keyed by session_id
    $sessions = _get_sessions(0, $simulator_id, True);
    
    if ( !count($sessions) ) {
      drupal_set_message(t('Schedule Unavailable'));
      //drupal_goto($return_url); // handle the return from the calling handliner
      return;
    }
    
    $time_blocks = _split_sessions_into_hours($sessions);
    
    foreach($sessions as $sess) {
      
      $assignments[$session_id] = array();
      if (empty($schedule_id)) { $schedule_id = $sess['schedule_id']; }
      if (empty($timezone)) { $timezone = $sess['timezone']; }
    }
    $now = _st_modify_timestamp();
    
    $curr_month_year_ts = _st_modify_timestamp($now, 'first day of ' . $from_month_year);
    $to_month_year_ts = _st_modify_timestamp($now, 'last day of ' . $to_month_year);
    
    $bd_ts = _st_modify_timestamp($now, 'first day of ' . $from_month_year);
    $ed_ts = _st_modify_timestamp($now, 'last day of ' . $from_month_year);
   
    /*---------------- LOOP through the selected export months ------------*/
    while ( $curr_month_year_ts < $to_month_year_ts ) {
      
      $grid_begins = _format_timestamp($bd_ts, '00:00:00', $timezone);
      $grid_ends = _format_timestamp($ed_ts, '23:59:59', $timezone);
      
      
      // init variables
      $assignments = array();
      $exceptions = array();
    
      $date_row = array(); // only 1 date row for this, but this array is for each table cell
      $dow_row = array();
    
      $prev_year = '';
      $prev_month = '';
      $sess_ptr = 0;

      $year_text = '';
      $month_text = '';
      $month_and_year = '';
      $prev_date = 0;


      /*----------------- Query: Calendar Date ------------------*/
      
      $results_cal = _get_calendar_range($grid_begins, $grid_ends);

      foreach ($results_cal as $cal) {
        // determine what year should be displayed for this date
        if ( !strlen($month_text) ) {
          $year_text = _st_format_system_date($cal->calendar_date, 'Y');
          $month_text = _st_format_system_date($cal->calendar_date, 'F');
          $month_and_year = $month_text . ' ' . $year_text;
          $n_view_month = _st_format_system_date($cal->calendar_date, 'n');
          $n_view_year = _st_format_system_date($cal->calendar_date, 'Y');
          $dow_row[0] = ' ';
          $date_row[0] = ' ';
        }

        if ($prev_date <> $cal->calendar_date) {
          $day = _st_format_system_date($cal->calendar_date, 'j');

          $dow_row[$day] = _st_format_system_date($cal->calendar_date, 'l'); // full dow name
          $date_row[$day] = _st_format_system_date($cal->calendar_date, 'j-M');
          $prev_date = $cal->calendar_date;
        }
      }
      unset($results_cal);


      /*-------------------  Query: Assignments -------------------*/
      $assignments = _get_assignments($grid_begins, $grid_ends, 0, $simulator_id);

      /*-------------------  Query: Exceptions -------------------*/
      
      $exceptions = _get_exceptions($grid_begins, $grid_ends, $timezone, $simulator_id);
      

      //------------------ BUILD the Excel Export Schedule Report ----------------------------

  
      $wksheet = $month_text;
      $day_offset = 0;


      for( $date_ptr=0; $date_ptr < 2; $date_ptr++ ) {


        // Loop through this twice - 1x for each half of the month
        if ( 0 == $date_ptr ) {
          $date_start = 1;
          $date_end = 15;
          $eRow = 0;
          $day_offset = 0;
        }
        else {
          $date_start = 16;
          $date_end = count($date_row)-1;
          $eRow = 40;
          $day_offset = 15;
        }



        //---------------- output:  WorkSheet Title -------------------------
        $excel_data[$wksheet][$eRow++][0] = 
          strtoupper($org_name) . ' ' . t('SCHEDULE PLAN') . ' - ' . 
                                        strtoupper($month_text) . ' ' . $year_text;
        $excel_data[$wksheet][$eRow++][0] = 
                t('SIMULATOR ') . $simulator->sim_name . '-' . $simulator->device_id_internal;
        $excel_data[$wksheet][$eRow++][0] = t('Days') . ' ' . $date_start . '-' . $date_end;

        // print the report date under the title & toward the right
        // date goes in a separate cell so that it can be highlighted in a
        // preferred color
        //Cols L(11) & M(12)
        // since we can't just plop spreadsheet cells wherever
        // need to add filler cells before the cols we are putting real data into
        for ($f=0; $f<11; $f++) {
          $excel_data[$wksheet][$eRow][$f] = '';
        }
        $excel_data[$wksheet][$eRow][11] = t('Modified') . ':';
        $excel_data[$wksheet][$eRow][12] = _st_format_system_date('now', 'j-M-Y');
        // col 13 gets merged with this one
        $excel_data[$wksheet][$eRow++][14] = ' '; // blank spacer 
        $excel_data[$wksheet][$eRow++][0] = ' '; // blank spacer 


        //---------------- output:  Day of Week & Dates -------------------------

        $excel_data[$wksheet][$eRow][0] = '';
        $excel_data[$wksheet][$eRow+1][0] = '';

        for($day=$date_start; $day<=$date_end; $day++) {
          // for some reason, needs an extra space padded column after the last col
          $excel_data[$wksheet][$eRow][$day-$day_offset] = $dow_row[$day];
          $excel_data[$wksheet][$eRow+1][$day-$day_offset] = $date_row[$day];
        }


        $eRow+=2;

        $processed = array();

        //---------------- output:  Sessions -------------------------

        foreach($time_blocks as $session_id => $tb_sess) {

          $session_hours = 1;
          $sess = $sessions[$session_id];

          $bt = (int)$sess['begin_time'];
          $et = (int)$sess['end_time'];
          if ( $bt > $et ) { $et += 2400; }


          $session_hours = ($et - $bt)/100;

          $s_time_range = sprintf('%02d:%02d - %02d:%02d',  
                                  $bt/100, $bt%100, 
                                  (int)$sess['end_time']/100, (int)$sess['end_time']%100);

          // we tag the front of the session with the number of rows/hours it should span
          // this is later parsed and stripped out in the PHPExcel export hook before it
          // makes its way into the spreadsheet cell
          $excel_data[$wksheet][$eRow][0] = $session_hours . '|' . 
                  $sess['session_name'] . "\n" . $s_time_range;


          foreach ($tb_sess as $tb) {



            $s_begin_hour = sprintf('%04d', $tb->begin_hour);
            $s_end_hour = sprintf('%04d', $tb->end_hour);


            for($day=$date_start; $day<=$date_end; $day++) {

              if ( !isset($excel_data[$wksheet][$eRow][0])) {
                $excel_data[$wksheet][$eRow][0] = ' ';
              }

              // ------- output: SCHEDULE ITEMS for each hour of each day -------

              $blocked = False;
              $assign_text = '';
              $start_ts = 0;
              $total_time = 0;


              $begin_sess_ts = _format_timestamp_parts($n_view_year, $n_view_month, $day, 
                                                  $sess['begin_time'], $timezone);
              $end_sess_ts = _format_timestamp_parts($n_view_year, $n_view_month, 
                                 (((int)$sess['begin_time'] > (int)$sess['end_time'])? $day+1 : $day), 
                                 $sess['end_time'], $timezone);

              $begin_hour_ts = _format_timestamp_parts($n_view_year, $n_view_month, $day, 
                                  $s_begin_hour, $timezone);
              $end_hour_ts = _format_timestamp_parts($n_view_year, $n_view_month, 
                                 (($tb->begin_hour > $tb->end_hour)? $day+1 : $day), 
                                 $s_end_hour, $timezone);

              $total_session_time = round(($end_sess_ts - $begin_sess_ts) / (60*60));

//              if ( ($day == 7) && ($session_id == 2)) {
//                $debug = 1;
//              }

              // -----------------------------------
              // Check the $processed[] array to see if 
              // the whole session has been processed and filled, don't continue to 
              // check for assignments or exceptions if its not open
              //------------------------------------


              // Assignments
              if ( isset($assignments[$tb->session_id][$day]) &&
                   !isset($processed[$session_id][$day][0]) ) {
                $assign_text = _check_for_assignment_excel(
                                              $assignments[$tb->session_id][$day], 
                                              $customer_id,
                                              $begin_hour_ts, $end_sess_ts, 
                                              $start_ts, $total_time);

                if ( strlen($assign_text) ) {

                  $total_time = round($total_time / (60*60));
                  if ( $total_time == $total_session_time ) {
                    $processed[$session_id][$day][0] = $total_time;
                  }
                  else {
                    if ( !isset($processed[$session_id][$day][1])) {
                      $processed[$session_id][$day][1] = $total_time; 
                    }
                  }

                  if ( !isset($excel_data[$wksheet][$eRow][$day-$day_offset]) ) {
                    $excel_data[$wksheet][$eRow][$day-$day_offset] = "";
                  }

                  if (($begin_hour_ts <= $start_ts) && ( $start_ts < $end_hour_ts) ) {
                    if ( $total_time > 1 ) {
                      $excel_data[$wksheet][$eRow][$day-$day_offset] = $total_time . "|";
                    }
                    $excel_data[$wksheet][$eRow][$day-$day_offset] .= $assign_text;
                  }
                  //$excel_data[$wksheet][$eRow][$day-$day_offset] .= $assign_text;
                }
              }

              // Exceptions
              if ( isset($exceptions[$day]) && 
                   !isset($processed[$session_id][$day][0]) ) {

                $blocked = _check_for_exception_excel($exceptions[$day], $begin_hour_ts, $end_sess_ts,
                                              $start_ts, $total_time);

                if ($blocked) {

                  $total_time = round($total_time / (60*60));
                  if ( $total_time == $total_session_time ) {
                    $processed[$session_id][$day][0] = $total_time;
                  }
                  else {
                    if ( !isset($processed[$session_id][$day][1])) {
                      $processed[$session_id][$day][1] = $total_time;
                    }
                  }

                  if ( !isset($excel_data[$wksheet][$eRow][$day-$day_offset]) ) {
                    $excel_data[$wksheet][$eRow][$day-$day_offset] = "";
                  }
                  if (($begin_hour_ts <= $start_ts) && ( $start_ts < $end_hour_ts) ) {
                    if ( $total_time > 1 ) {
                      $excel_data[$wksheet][$eRow][$day-$day_offset] = $total_time . "|";
                    }
                    if ( $customer_id ) {
                      $excel_data[$wksheet][$eRow][$day-$day_offset] .= "***";
                    }
                    else {
                      $excel_data[$wksheet][$eRow][$day-$day_offset] .= "MAINT";
                    }
                  }

                  //$excel_data[$wksheet][$eRow][$day-$day_offset] .= "MAINT";
                }
              }


              // Open
              // no assignments and not blocked 
              // this will only happen if there are no assignments or exceptions
              // for the whole session
              if ( !strlen($assign_text) && !$blocked ) {
                $total_time = (int)$total_session_time;
                $excel_data[$wksheet][$eRow][$day-$day_offset] = " ";
                if ( $total_time && ($begin_hour_ts == $begin_sess_ts) ) {
                  $excel_data[$wksheet][$eRow][$day-$day_offset] = $total_time . "| ";
                }
              }
              
            } // for ($day) loop

            $eRow++;
          } // END -- foreach($tb)
        } //END -- foreach($tb_sess)

        //------------- output:  Trailing Day of Week & Dates -------------------

        $excel_data[$wksheet][$eRow][0] = ' ';
        $excel_data[$wksheet][$eRow+1][0] = ' ';

        for($day=$date_start; $day<=$date_end; $day++) {
          // for some reason, needs an extra space padded column after the last col
          $excel_data[$wksheet][$eRow][$day-$day_offset] = $dow_row[$day];
          $excel_data[$wksheet][$eRow+1][$day-$day_offset] = $date_row[$day];
        }

        $eRow+=2;
        // need to add filler rows between date groups
        // Part 2 of the month begins at row=40
        for ($f=$eRow; $f<40; $f++) {
          $excel_data[$wksheet][$f][0] = ' ';
        }

      }  //END -- for ($date_ptr)
      
      //$curr_month_year_ts = strtotime('+1 month', $curr_month_year_ts);
      $curr_month_year_ts = _st_modify_timestamp($curr_month_year_ts, '+1 month');

      // we need to convert $curr_month_year_ts back to Month Year text
      // in order to get relative date (last day of ) to calculate correctly
      $bd_ts = $curr_month_year_ts;
      $ed_text = _st_format_system_date($curr_month_year_ts, 'F Y');
      
      $ed_ts = _st_modify_timestamp($now, 'last day of ' . $ed_text);
      
    } // LOOP - Month Year pointer
    
    /*--------------- Customer Info ------------------------------*/
    $customer_code = _get_customer_code($customer_id);
    if ( strlen($customer_code) ) { $customer_code .= '_'; }
    
    $month_range = $from_month_year;
    if ( $from_month_year != $to_month_year ) {
      $month_range .= '-' . $to_month_year;
    }
    $month_range = str_replace(" ", "_", $month_range) . '_';
    
    
    /*--------------- create the EXCEL File ----------------------*/
    
    $headers = array();  // not using this, formatting our own as they are complex
    $options = array('ignore_headers' => True, 'format' => 'xls');

    $export_uri = 'private://' . SCH_FILE_EXPORT_EXCEL_DIR;

    if ( !file_prepare_directory($export_uri, FILE_CREATE_DIRECTORY)) { 
      drupal_set_message(t('Error:  File Directory'));
      //drupal_goto($return_url); // handle the return from the calling handler
      return;
    }

    $file_timestamp = REQUEST_TIME;

    $dir = file_stream_wrapper_get_instance_by_uri($export_uri)->realpath();

    $file_name = $simulator->sim_name . '-' . $simulator->device_id_internal . '_' . 
                $customer_code . 
                $month_range .
                _st_format_system_date($file_timestamp, 'YmdHis') . 
                '.xls';
    $file_path = "$dir/$file_name";
    $file_uri = "$export_uri/$file_name";
    
   
    $result = phpexcel_export($headers, $excel_data, $file_path, $options);
    if ( PHPEXCEL_SUCCESS == $result ) {
      drupal_set_message(t('Success!'));
      
      _save_export_file_info($file_uri, $file_name, $file_timestamp);
    }
    else {
      drupal_set_message(t('Error'));
    }
    
    
    //drupal_goto($return_url);
    
    
  } 
  catch (Exception $e) {
    watchdog(SCH_SCHEDULER, '_build_schedule_report_excel_export() ' . $e->getMessage(), 
            array(), WATCHDOG_ERROR);
  }
}




/*
 *    PHPExcel HOOK FUNCTION (works with phpexcel module & PHPExcel library)
 *    Handles cell styling for Excel Export report
 */
function sabreScheduler_phpexcel_export($op, &$data, &$phpexcel, $options, 
                                        $column = NULL, $row = NULL) {
  $styleArray = array();
  global $customer_colors;
  
  
  switch($op) {
    case 'pre cell':
      /*
       *  Before the cell is created.  
       *  It can be styled here and the data may be altered
       *  Though styling is best handled in 'post cell'
       */
      if ( strlen(trim($data)) &&
           ( (((4 < $row) && ($row < 40)) || (44 < $row)) )) {
        $chr = strpos($data, '|');
        if ( ($chr !== False) ) {
          $merge = (int)_st_left($data, $chr + 1);
          $data = substr($data, $chr+1);
          if ( $merge > 0 ) {
            // convert col into ascii char
            $char = (($column < 26) ? ($column + 65) : ($column + 65 - 25));
            $col_char = chr($char);  
            // set excel coordinate range for merge of rows in column
            $cell_coord = $col_char . $row . ':' . 
                          $col_char . ($row + $merge - 1);
            $phpexcel->mergeCells($cell_coord);
            
            $styleArray = array(
              'borders' => array(
                'outline' => array(
                  'style' => PHPExcel_Style_Border::BORDER_THIN,
                  'color' => array('argb' => PHPExcel_Style_Color::COLOR_BLACK),
                ),
              ),
            );
            
            $phpexcel->getStyle($cell_coord)->applyFromArray($styleArray);
            
          }
        }
      }
    case 'post cell':
      /*
       *  After the cell is created.  
       *  It can be styled here, but the data cannot be altered at this point
       */
      switch($row) {
        //-------------- TITLE AREA : Rows 1-3 --------------
        //case 0:
        case 1:
        case 2:
        case 3:
        case 41:
        case 42:
        case 43:
        
          $styleArray = array(
            'font' => array(
              'bold' => TRUE,
              'size' => '18',
            ),
            'alignment' => array(
              'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            ),
          );

          
          if ( 0 == $column ) {
            $phpexcel->mergeCells('A' . $row . ':P' . $row);
          }
          break;
          
        case 4: 
        case 44:
          //-------- REPORT DATE SUBTITLE ----------
          
          $styleArray = array(
            'font' => array(
              'bold' => TRUE,
              'size' => '12',
            ),
          );
          if ( 11 == $column ) {
            $styleArray['alignment']['horizontal'] = 
                    PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
          }
          else if ( 12 == $column ) {
            $styleArray['alignment']['horizontal'] = 
                    PHPExcel_Style_Alignment::HORIZONTAL_RIGHT;
            $styleArray['fill'] = array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('argb' => PHPExcel_Style_Color::COLOR_YELLOW),
              );
            // merge 2 cols for the 'Modified' date
            $phpexcel->mergeCells('M' . $row . ':N' . $row);
          }
          break;
        
        default:
          $has_data = (strlen(trim($data)) > 0);
          if ( (0 == $column) && $has_data ) {
            //----------------- SESSION SIDE HEADING -----------------------
            $styleArray = array(
              'font' => array(
                'bold' => TRUE,
                'size' => '9',
              ),
              'fill' => array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('argb' => PHPExcel_Style_Color::COLOR_YELLOW),
              ),
              'borders' => array(
                'outline' => array(
                  'style' => PHPExcel_Style_Border::BORDER_THIN,
                  'color' => array('argb' => PHPExcel_Style_Color::COLOR_BLACK),
                ),
              ),
              'alignment' => array(
                'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
                'wrap' => True,
              ),
            );
          }
          else if (0 < $column) {
            //----------------- SESSION ASSIGNMENT COLORS --------------------
            // default settings
            $styleArray = array(
              'font' => array(
                'bold' => TRUE,
                'size' => '9',
                'color' => array('argb' => PHPExcel_Style_Color::COLOR_WHITE),
              ),
              'borders' => array(
                'outline' => array(
                  'style' => PHPExcel_Style_Border::BORDER_THIN,
                  'color' => array('argb' => PHPExcel_Style_Color::COLOR_BLACK),
                ),
              ),
              'alignment' => array(
                'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
              ),
            );
            
            $cust_code = strtoupper(_st_left($data, 5));

            if ( $customer_colors->isValid($cust_code) ) {
              //----------------- Customer Cell ------------------
              $styleArray['fill'] = array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('argb' => $customer_colors->getFillColor($cust_code)),
              );
              $styleArray['font']['color'] = 
                  array('argb' => $customer_colors->getFontColor($cust_code));
            }
            else if ( $has_data ) {
              //----------------- Day of Week & Date Rows ------------------
              $styleArray['borders']['outline'] = array(
                  'style' => PHPExcel_Style_Border::BORDER_THIN,
                  'color' => array('argb' => PHPExcel_Style_Color::COLOR_BLACK),
                );
              $styleArray['font']['color'] = 
                  array('argb' => PHPExcel_Style_Color::COLOR_BLACK);
            }
            else {
              $styleArray['fill'] = array(
                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                'color' => array('argb' => 'FFCCCCCC'),
              );
            }

          }
          else {
            //----------------- Day of Week & Date Rows ------------------
//            $styleArray['borders']['outline'] = array(
//                'style' => PHPExcel_Style_Border::BORDER_THIN,
//                'color' => array('argb' => PHPExcel_Style_Color::COLOR_BLACK),
//              );
            $styleArray['font']['color'] = 
                    array('argb' => PHPExcel_Style_Color::COLOR_BLACK);
          }
          break;
    }
    // $phpexcel object is the current worksheet
    $phpexcel->getStyleByColumnAndRow($column,$row)->applyFromArray($styleArray);
        
  }

}
  


/*
 *  _save_export_file_info()
 * 
 * 
 */
function _save_export_file_info($file_uri, $file_name, $file_timestamp) {
  try {
    
    global $user;
    
    $file_id = db_insert('sch_export_files')
              ->fields(array(
                  'user_id' => $user->uid,
                  'file_uri' => $file_uri,
                  'file_name' => $file_name,
                  'file_timestamp' => $file_timestamp,
              ))->execute();
    return $file_id;
  }
  catch (Exception $e) {
    watchdog(SCH_SCHEDULER, '_save_export_file_info() ' . $e->getMessage(), 
            array(), WATCHDOG_ERROR);
  }
}


/*
 * 
 * 
 * 
 */

/*
 *	_get_excel_export_files_table()
 *
 *	retrieves the export files for the past 7 days
 */

function _get_excel_export_files_table()  {
  
  try {
	
    $content = '';
    global $user;
    
    $table_rows = array();
    $table_headers = array(array('data' => t('Exported Files (Past 7 Days)'), 
                                 'class' => 'qms-files-tbl-col1'),
                           array('data' => t('Exported By'), 
                                 'class' => 'qms-files-tbl-col2'),
                          );
    
    $past7days = _st_modify_timestamp(0, '-7 days');

    $query = db_select('sch_export_files', 'ef');
    $query->innerJoin('users', 'u', 'ef.user_id = u.uid');
    //$query->condition('ef.user_id', $user->uid);
    $query->condition('ef.file_timestamp', $past7days, '>=');
    $query->fields('ef', array('file_id', 'file_name', 'file_timestamp'))
          ->fields('u', array('name'));
    $query->orderBy('ef.file_timestamp', 'DESC');
    
    $result = $query->execute();

    foreach ( $result as $f ) {	
      $table_rows[] = array( 
        'data' => array( 
          l( t($f->file_name), 
             "excel/file/download/" . $f->file_id,
             array('attributes' => array('target'=>'_blank')) ), 
          $f->name . ' - ' . _st_format_system_date($f->file_timestamp, 'short'),
        ) );		
    }  
    
    // create table
    $content = '<div id="sch-files-tbl-div">';
    $content .= theme( 'table', array(
      'header' => $table_headers,
      'rows' => $table_rows,
      'empty' => t('None'),
    ));
    $content .= '</div>';

    return $content;
  }
  catch (Exception $e) {
    watchdog(SCH_SCHEDULER, '_get_excel_export_files_table() ' . $e->getMessage(), 
            array(), WATCHDOG_ERROR);
  }
}


/*
 *	discrepancy_file_download()
 *
 *  implements hook_file_download()
 */

function excel_file_download($file_id) {
  
  try {

	$file_name = '';
	
	$sql = "SELECT file_name " .
				 "FROM {sch_export_files} " .
				 "WHERE file_id = :fid";
	$results = db_query($sql, array(':fid' => $file_id));
	if ( !$results->rowCount() ) {
		drupal_set_message(t('Oops!  Something went wrong.  Unable to find file.'));
		return;		
	}
	$file_name = $results->fetchField();
	
	// use the local file path, not the file URI which is saved in the table

	$private_path = variable_get('file_private_path', QMS_PRIVATE_FILES_DIR ) . '/';
	$file_path = $private_path . SCH_FILE_EXPORT_EXCEL_DIR . '/' . $file_name;
	
	_st_return_requested_file($file_path);
  }
  catch (Exception $e) {
    watchdog(SCH_SCHEDULER, 'excel_file_download() ' . $e->getMessage(), 
            array(), WATCHDOG_ERROR);
  }
}




/*
 *    report_schedule_by_month ()
 * 
 *    Derived from 'schedule_grid_display' that builds the main schedule grid
 * 
 *    IN:       $simulator_id, 
 *              $customer_id, 
 *              $view_month ['January|February|March|...],
 *              $view_year [4-digit year (string)]
 *    RETURN:   Schedule Grid display, single page, by month
 */

function report_schedule_by_month($simulator_id, $customer_id = 0, $view_month = '', $view_year = '')  {
  
  if (!$simulator_id) {
    drupal_set_message(t('Error: Invalid simulator id.'));
    drupal_goto('schedules');
    return;
  }
  
  drupal_add_js('(function($) {
										Drupal.behaviors.schViewPrint = {
											attach: function(context, settings) {
												$(".qms-print", context).click(function() {
                          window.print();
                          return false;
                        });
											}
										}
									}(jQuery));', 'inline');

  // if not specified, use the current month and year
  if ($view_month == '') {
    $view_month = date('F');
  }
  if ($view_year == '') {
    $view_year = date('Y');
  }

  $content = _build_schedule_report($simulator_id, $customer_id, $view_month, $view_year);
  
  $form_elems = drupal_get_form('report_form');
  $content .= render($form_elems);

  return $content;
}

/*
 * report_form()
 * 
 * Appends buttons to bottom of page and returns to $_GET['destination'] setting 
 * when 'Done' button clicked
 * 
 */

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

/*
 * status_display_form_submit()
 * 
 */
function report_form_submit($form, $form_state) {
  $destination = drupal_get_destination();
	$goto_url = $destination['destination'];

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


/*
 *  _build_schedule_report()
 * 
 *  if no month or year specified, returns the report for the current month/year
 * 
 *  IN:       $simulator_id, 
 *            $customer_id, 
 *            $view_month ['January|February|March|...],
 *            $view_year [4-digit year (string)]
 *  RETURN:   Schedule Grid display, single page, by month
 */
function _build_schedule_report($simulator_id, $customer_id = 0, $view_month = '', $view_year = '') {
    try {
    // schedule display

    global $base_url;
    global $theme;

    // get the schedule_sessions for this simulator schedule
    $sessions = array();
    $assignments = array();
    $exceptions = array();
    $schedule_id = 0;
    
    $session_id = 0;
    $schedule_id = 0;
    
    $date_count = 0;
    $record_count = 0;
    $years = '';
    $months = '';
    $date_row = array(); // only 1 date row for this, but this array is for each table cell
    $dow_row = array();
    
    $prev_year = '';
    $prev_month = '';
    $sess_ptr = 0;
    
    $year_text = '';
    $month_text = '';
    $month_and_year = '';
    $n_view_month = 0;
    $n_view_year = '';
    $content = '';
    $timezone = '';
    
    
    

    // $sessions array keyed by session_id
    $sessions = _get_sessions(0, $simulator_id, True);
    
    if ( !count($sessions) ) {
      $content  = '<div id="sch-grid-div">';
      $content .= '<br class="clearBoth" />[' . t('Schedule Unavailable') . ']';
      $content .= '</div>';
      return $content;
    }
    
    
    $time_blocks = _split_sessions_into_hours($sessions, True);
    
    foreach($sessions as $sess) {
      
      $assignments[$session_id] = array();
      if (!$schedule_id) { $schedule_id = $sess['schedule_id']; }
      if (empty($timezone)) { $timezone = $sess['timezone']; }
    }
    
    $now = _st_modify_timestamp();

    /*----------------- Set Grid Date Range -------------------*/
    $bd_ts = _st_modify_timestamp($now, 'first day of ' . $view_month . ' ' . $view_year);
    $ed_ts = _st_modify_timestamp($now, 'last day of ' . $view_month . ' ' . $view_year);

    $grid_begins = _format_timestamp($bd_ts, '00:00:00', $timezone);
    $grid_ends = _format_timestamp($ed_ts, '23:59:59', $timezone);


    /*----------------- Query: Calendar Date ------------------*/
    
    $results_cal = _get_calendar_range($grid_begins, $grid_ends);

    $date_count = 0;
    $date_group = 0;
    $prev_date = 0;
    
    foreach ($results_cal as $cal) {
      // determine what year should be displayed for this date
      if ( !$date_count ) {
        $year_text = _st_format_system_date($cal->calendar_date, 'Y');
        $month_text = _st_format_system_date($cal->calendar_date, 'M');
        $month_and_year = '<div class="sch-grid-month-span">' . $month_text . ' ' . $year_text . '</div>';
        $n_view_month = date('n', $cal->calendar_date);
        $n_view_year = date('Y', $cal->calendar_date);
      }
      
      if ($prev_date <> $cal->calendar_date) {
        $date_count++;
        $dow_row [$date_count] = _st_format_system_date($cal->calendar_date, 'D');
        $date_row[$date_count] = _st_format_system_date($cal->calendar_date, 'n/j');
        $prev_date = $cal->calendar_date;
      }
    }

    /*-------------------  Query: Assignments -------------------*/
    
    $assignments = _get_assignments($grid_begins, $grid_ends, 0, $simulator_id);


    /*-------------------  Query: Exceptions -------------------*/
    
    $exceptions = _get_exceptions($grid_begins, $grid_ends, $timezone, $simulator_id);


    $return_url = 'schedule/grid/' . $simulator_id . '/' . $schedule_id . '/' . $customer_id . '/' . 
                        $view_month . '/' . $view_year;
    $content = '<div id="sch-grid-div">';
    $content .= '<div id="sch-return-url" class="qms-hidden">' . $return_url . '</div>';

   
    //----------------------- BUILD the SCHEDULE Table ---------------------------------
     
    // OUTPUT:  Month and Year subheading
    $content .= '<h3>' . $month_and_year . '</h3>';
    
    
    // BEGIN TABLE
    $content .= '<table class="sch-grid-table">';
    

    //------------------- output:  DATE Headings -----------------

    // this prints a blank first cell at the top left corner
    $content .= '<thead><tr><th class="sch-time-col">' . $year_text . '</th>';
    
    foreach($dow_row as $dow) {
      $content .= '<th class="sch-date-col">' . $dow . '</th>';
    }
    
    $content .= '</tr><tr><th class="sch-time-col">' . $month_text . '</th>';
    foreach($date_row as $date) {
      $content .= '<th class="sch-date-col">' . $date . '</th>';
    } 
    $content .= '</tr></thead><tbody>';
        
    
    // ------------------- output: SCHEDULE ITEMS for each hour of each day
    $prev_sess_id = 0;
    
    
    foreach($time_blocks as $tb) {
      
      $sess = $sessions[$tb->session_id];
      $new_row = ($prev_sess_id <> $tb->session_id ) ? '<tr class="sch-session-row">' : '<tr>';
      $prev_sess_id = $tb->session_id; 
      
      $s_begin_hour = sprintf('%04d', $tb->begin_hour);
      $s_end_hour = sprintf('%04d', $tb->end_hour);
      
      $content .= $new_row;
      
      
      // output:  TIME BLOCK row
      $content .= '<th>' . 
                    sprintf('%02d:%02d - %02d:%02d', 
                      $tb->begin_hour/100, $tb->begin_hour%100, 
                      $tb->end_hour/100, $tb->end_hour%100) . 
                  '</th>';
      

      for ($day = 1; $day <= $date_count; $day++) {
        $blocked = False;
        $assign_text = '';
        
        $begin_ts = _format_timestamp_parts($n_view_year, $n_view_month, $day, $s_begin_hour, $timezone);
        $end_ts = _format_timestamp_parts($n_view_year, $n_view_month, 
                                      (($tb->begin_hour > $tb->end_hour)? $day+1 : $day),
                                      $s_end_hour, $timezone);

        if ( isset($exceptions[$day]) ) {
          $blocked = _check_for_exception($exceptions[$day], $begin_ts, $end_ts);
        }
        
    
        
        if ( isset($assignments[$tb->session_id][$day]) ) {
          $assign_text = _check_for_assignment($assignments[$tb->session_id][$day], $begin_ts, $end_ts);
        }
        
        if ( strlen($assign_text) ) {
          $content .= '<td>' . $assign_text . '</td>';
        }
        else if ($blocked) {
          $content .= '<td>' . ' ***' . '</td>';
        }
        else { // open
          $content .= '<td>&nbsp;</td>';
        }

      } // for ($day) loop
     

      $content .= '</tr>';
      
    } //END -- foreach($time_block)
    
            
    $content .= '<tbody></table><br class="clearBoth" />';
    
    
    return $content;
    
  } 
  catch (Exception $e) {
    watchdog(SCH_SCHEDULER, '_build_schedule_report() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
}



/*
 *  _split_sessions_into_hours($sessions)
 * 
 *  returns an array of hour time_blocks
 *  $sort_by_hour == True, orders by start hour of time block
 *  $sort_by_hour == False, default sort by session_id
 * 
 */
function _split_sessions_into_hours($sessions, $sort_by_hour = False) {
  
  $time_blocks = array();
  
  foreach($sessions as $sess) {
    
    $session_id = $sess['schedule_session_id'];
    
      
    // break session time down into hourly segments
    $et = (int)$sess['end_time'];
    $bt = (int)$sess['begin_time'];
    $iend_time = $et;
    $beg_hour = $bt;
    $end_hour = 0;
    $i = 0;

    if ( $bt > $et )  {
      // this session overlaps into next day, accommodate that
      $iend_time += 2400;
    }


    // walk through the session time range to break it into blocks
    while ($beg_hour <= ($iend_time - 100)) {

      // end on the session end_time if it doesn't break evenly into hours
      $end_hour = (($beg_hour + 100) < $iend_time) ?  ($beg_hour + 100) : ($iend_time); 


      // index the timeblock array by the beg_hour & store the rest
      $tb = new stdClass();
      $tb->session_id = $session_id;

      $tb->begin_hour = (($bt > $et) && ($beg_hour >= 2400)) ? $beg_hour - 2400 : $beg_hour;
      //$tb->end_hour = (($bt > $et) && ($end_hour > 2400)) ? $end_hour - 2400 : $end_hour;
      if ( ($bt > $et) && ($end_hour > 2400) ) {
        if ( ($end_hour > 2400) && ($end_hour < 2500) ) {
          $tb->end_hour = 2400;
          $beg_hour = 2400;
        }
        else {
          $tb->end_hour = $end_hour - 2400;
          $beg_hour = $end_hour;
        }

      }
      else {
        $tb->end_hour = $end_hour;
        $beg_hour = $end_hour;
      }

      if ($sort_by_hour) {
        $time_blocks[$tb->begin_hour] = $tb;
      }
      else {
        $time_blocks[$tb->session_id][$tb->begin_hour] = $tb;
      }

      $i++;
      if ( $i == 10 ) {
        $debug = 1;
        break;
      }
    }
  }
  // sort by the array key
  ksort($time_blocks);
  return $time_blocks;
}


/*
  *	_check_for_assignment()
  *
  *	Not really a validator
  *  For the provided assignment array & time range, does an assignment occupy the time range?
  *  
  *  IN: assignment array
  *      $begin_ts, $end_ts (time range to check for assignment) 
  */

function _check_for_assignment($assignments = array(), $begin_ts = 0, $end_ts = 0,
                               &$total_time = 0) {

  // expects the timestamp range and assignment array have been provided
  // doesn't retrieve them

  // assignment array passed are only assignment items for a specific day & session.

  $assign_text = '';
  $total_time = 0;

  if ( !$begin_ts || !$end_ts || !count($assignments)  ) { 
    return $assign_text; 
  }

  // bump the seconds by 1 in either direction to avoid problems with perceived overlap (by seconds)
  $begin_range_ts = $begin_ts + 1;
  $end_range_ts = $end_ts - 1;


  // CHECK ASSIGNMENTS

  // step through all of the assignments provided

  foreach ($assignments as $assign) {

    $total_time = _date_diff_seconds($assign->begin_timestamp,
                                     $assign->end_timestamp);

    //check the assignment begin & end times against the timerange
    if ( ((int)$assign->begin_timestamp <= $begin_range_ts) && 
         ($end_range_ts <= (int)$assign->end_timestamp) ) {
      // assignment falls in the middle of the time range
      $assign_text = $assign->customer_code;  
    }
    else if ( ($begin_range_ts <= (int)$assign->begin_timestamp ) && 
              ((int)$assign->end_timestamp <= $end_range_ts ) ) {
      // assignment completely contained by the time range
      $assign_text = $assign->customer_code;  
    }
    else if ( ($begin_range_ts <= (int)$assign->begin_timestamp) && 
              ((int)$assign->begin_timestamp < $end_range_ts ) && 
              ( $end_range_ts <= $assign->end_timestamp ) ) {
      // assignment overlaps middle to end of session
      //$assign_text = $assign->customer_code;
      $assign_text = '&nbsp;&nbsp;/';
    }
    else if ( ((int)$assign->begin_timestamp <= $begin_range_ts) && 
              ($begin_range_ts < (int)$assign->end_timestamp )  &&
              ( $assign->end_timestamp <= $end_range_ts) ) {
      // assignment overlaps beginning to middle of session	
      //$assign_text = $assign->customer_code;
      $assign_text = '&nbsp;&nbsp;/';
    }
  } // End - Foreach Loop

  return $assign_text;
}

/*
  *	_check_for_assignment_excel()
  *
  *	 Not really a validator
  *  For the provided assignment array & time range, does an assignment occupy the time range?
  *  Customized for Excel Export within the context of Excel cell merging and session times
  *  
  *  IN: assignment array
  *      $begin_ts, $end_ts (time range to check for assignment) 
  *   OUT: $start_ts (when within the time range the assignment begins
  *        $total_time (duration of the assignment within the time range)
  *   RETURN:  $assign_text (customer code if an assignment exists for this time range)
  */

function _check_for_assignment_excel($assignments = array(), 
                               $customer_id = 0,
                               $begin_ts = 0, $end_ts = 0,
                               &$start_ts = 0, &$total_time = 0) {

  // expects the timestamp range and assignment array have been provided
  // doesn't retrieve them

  // assignment array passed are only assignment items for a specific day & session.

  $assign_text = '';
  $start_ts = 0;
  $total_time = 0;

  if ( !$begin_ts || !$end_ts || !count($assignments)  ) { 
    return $assign_text; 
  }

  // bump the seconds by 1 in either direction to avoid problems with perceived overlap (by seconds)
  $begin_range_ts = $begin_ts + 1;
  $end_range_ts = $end_ts - 1;


  // CHECK ASSIGNMENTS

  // step through all of the assignments provided
  foreach ($assignments as $assign) {
    

      //check the assignment begin & end times against the timerange
      if ( ((int)$assign->begin_timestamp <= $begin_range_ts) && 
           ($end_range_ts <= (int)$assign->end_timestamp) ) {
        // assignment falls in the middle of the time range
        if ( !$customer_id || 
             ($customer_id && ($customer_id == $assign->customer_id)) ) {
          $assign_text = $assign->customer_code;  
        }
        else {
          $assign_text = '***';
        }
        $start_ts = $begin_ts;
        $total_time = round(_date_diff_seconds($begin_ts,$end_ts));
        break;
      }
      else if ( ($begin_range_ts <= (int)$assign->begin_timestamp ) && 
                ((int)$assign->end_timestamp <= $end_range_ts ) ) {
        // assignment completely contained by the time range
        if ( !$customer_id || 
             ($customer_id && ($customer_id == $assign->customer_id)) ) {
          $assign_text = $assign->customer_code;  
        }
        else {
          $assign_text = '***';
        }
        $start_ts = (int)$assign->begin_timestamp;
        $total_time = round(_date_diff_seconds($start_ts,
                                         $assign->end_timestamp));
        if ( $start_ts == $begin_ts ) { break; }
      }
      else if ( ($begin_range_ts <= (int)$assign->begin_timestamp) && 
                ((int)$assign->begin_timestamp < $end_range_ts ) && 
                ( $end_range_ts <= $assign->end_timestamp ) ) {
        // assignment overlaps middle to end of time range
        if ( !$customer_id || 
             ($customer_id && ($customer_id == $assign->customer_id)) ) {
          $assign_text = $assign->customer_code;  
        }
        else {
          $assign_text = '***';
        }
        //$assign_text = '&nbsp;&nbsp;/';
        $start_ts = (int)$assign->begin_timestamp;
        $total_time = round(_date_diff_seconds((int)$assign->begin_timestamp, 
                                               $end_ts));
      }
      else if ( ((int)$assign->begin_timestamp <= $begin_range_ts) && 
                ($begin_range_ts < (int)$assign->end_timestamp )  &&
                ( $assign->end_timestamp <= $end_range_ts) ) {
        // assignment overlaps beginning to middle of time range	
        if ( !$customer_id || 
             ($customer_id && ($customer_id == $assign->customer_id)) ) {
          $assign_text = $assign->customer_code;  
        }
        else {
          $assign_text = '***';
        }
        //$assign_text = '&nbsp;&nbsp;/';
        $start_ts = (int)$assign->begin_timestamp;
        $total_time = round(_date_diff_seconds($begin_ts, 
                                               (int)$assign->end_timestamp));
        break;
      }
  } // End - Foreach Loop

  return $assign_text;
}


/*
 *	_check_for_exception()
 *
 *	Not for validation
 *  For the provided exception array & time range, does an exception occupy the time range?
 *  
 *  IN: exceptions array
 *      $begin_ts, $end_ts (time range to check for assignment) 
 *  RETURN:  True (if exception)
 *           False (no exception)
 */

function _check_for_exception($exceptions = array(), $begin_ts = 0, $end_ts = 0, 
                               &$total_time = 0) {

  // we are dealing with hour time ranges for this

  if ( !$begin_ts || !$end_ts || !count($exceptions)  ) { 
    return false; 
  }

  // bump the seconds by 1 in either direction to avoid problems with perceived overlap (by seconds)
  $begin_range_ts = $begin_ts + 1;
  $end_range_ts = $end_ts - 1;


  // CHECK EXCEPTIONS
  $has_except = False;
  $total_time = 0;

  // step through all of the assignments provided
  $i = 0;
  foreach ($exceptions as $except) {

    $total_time = _date_diff_seconds($except->begin_timestamp, 
                                           $except->end_timestamp);
    

    //check the  begin & end times 
    if ( ($except->begin_timestamp <= $begin_range_ts) && 
         ($end_range_ts <= $except->end_timestamp) ) {
      // $except falls in the middle of the time range
      if ( !$except->allow_override ) {
        $has_except = True;
      }
    }
    else if ( ($begin_range_ts <= $except->begin_timestamp ) && 
              ($except->end_timestamp <= $end_range_ts ) ) {
      // $except completely contained by the time range
      if ( !$except->allow_override ) {

        $has_except = True;
      }
    }
    else if ( ($begin_range_ts <= $except->begin_timestamp) && 
              ($except->begin_timestamp < $end_range_ts ) && 
              ( $end_range_ts <= $except->end_timestamp ) ) {
      // $except overlaps middle to end of session
      if ( !$except->allow_override ) {
        $percent = round(($end_ts - $except->begin_timestamp) / 
                  ($end_ts - $begin_ts), 2) * 100;
        if ( $percent >= 25 ) {
          $has_except = True;
        }
      }
    }
    else if ( ($except->begin_timestamp <= $begin_range_ts) && 
              ($begin_range_ts < $except->end_timestamp )  &&
              ( $except->end_timestamp <= $end_range_ts) ) {
      // $except overlaps beginning to middle of session	
      if ( !$except->allow_override ) {
        $percent = round(($except->end_timestamp - $begin_ts) / 
                  ($end_ts - $begin_ts), 2) * 100;
        if ( $percent >= 25 ) {
          $has_except = True;
        }
      }
    }
    $i++;
  } // End - Foreach Loop

  return $has_except;
}


/*
 *	_check_for_exception_excel()
 *
 *	Not for validation
 *  For the provided exception array & time range, does an exception occupy the time range?
 *  Customized for the Excel Exported Report where the grid is defined in hour intervals, but
 *  cells will be merged for full sessions
 *  
 *  IN: exceptions array
 *      $begin_ts, $end_ts (time range of session) 
 *  OUT: $start_ts (when during the session the exception actual begins,
 *                  may be the beginning or later in the session time range)  
 *      $total_time (duration of the exception within the session block
 *  RETURN:  True (if exception)
 *           False (no exception)
 */

function _check_for_exception_excel($exceptions = array(), $begin_ts = 0, $end_ts = 0, 
                               &$start_ts = 0, &$total_time = 0) {

  // we are dealing with hour time ranges for this

  if ( !$begin_ts || !$end_ts || !count($exceptions)  ) { 
    return false; 
  }

  // bump the seconds by 1 in either direction to avoid problems with perceived overlap (by seconds)
  $begin_range_ts = $begin_ts + 1;
  $end_range_ts = $end_ts - 1;


  // CHECK EXCEPTIONS
  $has_except = False;
  $start_ts = 0;
  $total_time = 0;

  // step through all of the assignments provided
  foreach ($exceptions as $except) {
    
    
      //check the  begin & end times 
      if ( ($except->begin_timestamp <= $begin_range_ts) && 
           ($end_range_ts <= $except->end_timestamp) ) {
        // time range is completely overlapped by the exception
        if ( !$except->allow_override ) {
          $has_except = True;
          $start_ts = $begin_range_ts;
          $total_time = round(_date_diff_seconds($begin_ts, $end_ts));
          
        }
      }
      else if ( ($begin_range_ts <= $except->begin_timestamp ) && 
                ($except->end_timestamp <= $end_range_ts ) ) {
        // $except completely contained by the time range
        if ( !$except->allow_override ) {
          $has_except = True;
          $start_ts = $except->begin_timestamp;
          $total_time = round(_date_diff_seconds($except->begin_timestamp, 
                                                 $except->end_timestamp));
        }
      }
      else if ( ($begin_range_ts <= $except->begin_timestamp) && 
                ($except->begin_timestamp < $end_range_ts ) && 
                ( $end_range_ts <= $except->end_timestamp ) ) {
        // $except overlaps middle to end of session
        if ( !$except->allow_override ) {
          $percent = round(($end_range_ts - $except->begin_timestamp) / 
                    ($end_range_ts - $begin_range_ts), 2) * 100;
          if ( $percent >= 10 ) {
            $has_except = True;
            $start_ts = $except->begin_timestamp;
            $total_time = round(_date_diff_seconds($except->begin_timestamp, 
                                                 $end_ts));
            
          }
        }
      }
      else if ( ($except->begin_timestamp <= $begin_range_ts) && 
                ($begin_range_ts < $except->end_timestamp )  &&
                ( $except->end_timestamp <= $end_range_ts) ) {
        // $except overlaps beginning to middle of session	
        if ( !$except->allow_override ) {
          $percent = round(($except->end_timestamp - $begin_range_ts ) / 
                    ($end_range_ts - $begin_range_ts), 2) * 100;
          if ( $percent >= 10 ) {
            $has_except = True;
            $start_ts = $begin_range_ts;
            $total_time = round(_date_diff_seconds($begin_ts, 
                                                   $except->end_timestamp));
          }
        }
      }
  } // End - Foreach Loop

  return $has_except;
}

  
  
/*
 * report_elogs()
 */
function report_elogs($customer_id = 0, $report_type = 0, 
                      $begin_date = '', $end_date = '', 
                      $show_form_only = True) {
	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
		return '';
  }
  
  if ( '0' == $begin_date ) { $begin_date = ''; }
  if ( '0' == $end_date ) { $end_date = ''; }
  $subtitle = '';
  $year = date('Y');
  
  if ( !strlen($begin_date) && !strlen($end_date )) {
    $subtitle = $year;
  }
  else if ( !strlen($begin_date) ) {
    $ed = _st_right($end_date, 5);
    $ed = str_replace('-', '/', $ed) . '/' . $year;
    $subtitle = '1/1/' . $year . ' - ' . $ed;
  }
  else if ( !strlen($end_date) ) {
    $bd = _st_right($begin_date, 5);
    $bd = str_replace('-', '/', $bd) . '/' . $year;
    $subtitle = $bd . ' - ' . '12/31/' . $year;
  }
  
  $content = '';
  
  
  $print_page_heading = 
									'<div class="sch-print-header">' . 
										'<div class="sch-page-title">' .	drupal_get_title() . '</div>' . 
                    '<div class="sch-page-subtitle">' .	$subtitle . '</div>' . 
									'</div>';
	
	
  
  $content .= (!$show_form_only) ? $print_page_heading  : '';

  $form_elems = drupal_get_form('elog_report_form', $customer_id, 
                                                         $report_type,
                                                         $begin_date,
                                                         $end_date);
	$content .= render($form_elems);

  if ( !$show_form_only ) {
    // if no customer or date_range provided, return all elogs for the current year only.
    
    if ( 1 == $report_type ) {
      // elog session report
      $content .= _get_elog_session_report_list($customer_id, 
                                                $begin_date, 
                                                $end_date);
    }
    else if ( 2 == $report_type ) {
      $content .= _get_elog_quality_report_list($customer_id, 
                                                $begin_date, 
                                                $end_date);
    }
  }

	
	return $content;
}
  
  
  
/*
 * 	elog_report_form()
 * 	display form to get user input of search parameters
 *  IN:  $args  -- array of arguments passed into the report
 *                'customer_id'
 *                'report_type'
 *                'begin_date'
 *                'end_date'
 *                'show_form_only' => True | False

 */

function elog_report_form($form, $form_state, 
                          $customer_id = 0, $report_type = 0, 
                          $begin_date = '', $end_date = '') {
	
		
    drupal_add_library('system','ui.dialog');
    drupal_add_library('system','ui.datepicker');
    drupal_add_js(drupal_get_path('module', 'sabreScheduler') . 
                                      '/js/sabreScheduler.report.elogs.js');


    //------------ BUILD SEARCH FORM ------------------
		global $base_url;

		//$simulator_list = new SimulatorList();
    $customer_list = new CustomerList();
    //$session_list = new SessionNameList();
		

		$form['search'] = array(
			'#type' => 'fieldset',
			'#title' => t('Report Settings'),
			'#collapsible' => True,
			'#collapsed' => False,
			'#attributes' => array('id' => array('sch-report-settings-div'),
                             'style' => 'padding-left:20px;'),
		);
		
    

		$form['search']['customer'] = array(
			'#type' => 'select',
			'#title' => t('Customer'),
			'#options' => $customer_list->getAll(CustomerList::INCL_ALL),
			'#default_value' => $customer_id,
			'#attributes' => array('class' => array('qms-select'),
														'id' => 'sch-customer-list'),
      '#prefix' => '<div style="float:left;">',
      //'#suffix' => '</div>',
		);
    
    $report_type_options = array(
      '0' => '- ' . t('Select') . ' -',
      '1' => t('Session Report'),
      '2' => t('Quality Report'),
    );
    
    $form['search']['report_type'] = array(
			'#type' => 'select',
			'#title' => t('Report Type'),
			'#options' => $report_type_options,
			'#default_value' => $report_type,
			'#attributes' => array('class' => array('qms-select'),
														'id' => 'sch-report-type-list'),
      //'#prefix' => '<div style="float:left;">',
      '#suffix' => '</div>',
		);

		
		
//		$form['search']['search_date_label'] = array(
//			'#markup' => '<div style="float:left;clear:right;padding-left:40px;">',
//                    //'<h4>' . t('Report Date Range') . '</h4>',
//		);
		


		$form['search']['from_date'] = array(
			'#type' => 'date_popup',
			'#title' => t('From Date'),
			'#size' => 10,
			'#date_format' => 'm-d-Y',	
      '#default_value' => $begin_date,
			'#attributes' => array('style' => array('float:left', 'width:50px'),
															'id' => 'sch-from-date',
															'class' => array('qms-date-picker')),
			'#prefix' => '<div style="display:inline-block;text-align:left;padding-left:40px;">',
		);

		$form['search']['to_date'] = array(
			'#type' => 'date_popup',
			'#title' => t('To Date'),
			'#size' => 10,
			'#date_format' => 'm-d-Y',
      '#default_value' => $end_date,
			'#attributes' => array('style' => array('float:left', 'clear:right', 'width:50px'),
															'id' => 'sch-to-date',
																'class' => array('qms-date-picker')),
			'#suffix' => '</div><br class="clearBoth" />',
		);
    
    


		//--------------------------------------------
		// Adds a simple submit button that refreshes the form and clears its contents 
		// -- this is the default behavior for forms.
		$form['search']['actions'] = array('#type' => 'actions');
		$form['search']['actions']['submit'] = array(
			'#type' => 'button',
			'#value' => t('Submit'),
      '#name' => 'submit',
			'#attributes' => array('id' => 'sch-btn-submit',
															'sch-url' => url('reports/elogs'),
                              'style' => 'font-weight:bold;'),
		);
    $form['search']['actions']['clear'] = array(
      '#type' => 'button',
      '#value' => t('Clear'),
      '#attributes' => array('class' => array('sch-clear', 'qms-btn-extra'),
                             'id' => 'sch-btn-clear'),
      /*
      '#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="sch-popup-dialog"></div>',
		);
		
		

		return $form;
}


/*
 * _get_elog_session_report_list()
 *
 */

function _get_elog_session_report_list($customer_id = 0, $begin_date = '', $end_date = '') {
	try{
		
		$begin_ts = 0;
		$end_ts = 0;
    $simulator_list = new SimulatorList();

    
    define('ELOG_FLIGHT_ROLE_INSTRUCTOR', 3);
    define('ELOG_FLIGHT_ROLE_PILOT2', 2);
    define('ELOG_FLIGHT_ROLE_PILOT1', 1);
    
    $year = date('Y');
		
    // if no date range supplied, or a partial date range, only get elogs for this year
    $begin_ts = ( !strlen($begin_date) ? 
                    _st_format_system_timestamp($year . '-01-01 00:00:00') : 
                    _st_format_system_timestamp($begin_date . ' 00:00:00') );
    
    $end_ts = ( !strlen($end_date) ? 
                    _st_format_system_timestamp($year . '-12-31 23:59:59') : 
                    _st_format_system_timestamp($end_date . ' 23:59:59') );
    
	
		$table_header = array( 
      array( 'data' => t('Date'), 'class' => array('sch-tbl-elog-date') ),
			array( 'data' => t('EL No.'), 'class' => array('sch-tbl-elog-no') ),
			array( 'data' => t('Start'), 'class' => array('sch-tbl-elog-begintime') ),
			array( 'data' => t('End'), 'class' => array('sch-tbl-elog-endtime') ),
      array( 'data' => t('Simulator'), 'class' => array('sch-tbl-elog-sim') ),
      array( 'data' => t('Instructor'), 'class' => array('sch-tbl-elog-instructor') ),
      array( 'data' => t('Student 1'), 'class' => array('sch-tbl-elog-pilot1') ),
      array( 'data' => t('Student 2'), 'class' => array('sch-tbl-elog-pilot2') ),
		);
    $table_rows = array();
    
    
    $query = db_select('sch_elogs', 'e');
    $query->innerJoin('sch_assignments', 'a', 'a.assignment_id = e.assignment_id');
    $query->innerJoin('sch_customers', 'c', 'c.customer_id = a.customer_id');
    $query->innerJoin('sch_schedules', 'sch', 'sch.schedule_id = a.schedule_id');
    
    
    if ( $customer_id ) {
      $query->condition('a.customer_id', $customer_id);
    }
    $query->condition('a.begin_timestamp', $begin_ts, '>=');
    $query->condition('a.end_timestamp', $end_ts, '<=');
    
    
    $query->fields('e', array('elog_id', 'el_no'))
          ->fields('a', array('assignment_id', 'customer_id', 
                              'begin_timestamp', 'end_timestamp'))
          ->fields('c', array('customer'))
          ->fields('sch', array('simulator_id', 'timezone'));
          
    
    $query->orderBy('customer')->orderBy('simulator_id')->orderBy('a.begin_timestamp');
    
    $results = $query->execute();
    
    $i = 0;
    $last_customer_id = 0;
    $content = '<div id="qms-report-div">';
    $customer_name = '';
    $row_data = array();
    $crew = array();
    
    if ( $results->rowCount() ) {
      
      $elog_results = $results->fetchAll();
      
      foreach ($elog_results as $row) {
        
        $query = db_select('sch_elog_crew', 'ec');
        $query->leftJoin('sch_flight_roles', 'fr', 
                          'ec.flight_role_1_id = fr.flight_role_id');
        $query->condition('ec.elog_id', $row->elog_id);
        $query->condition('ec.flight_role_1_id', 3, '<=');
        $query->fields('ec', array('lname', 'fname', 'flight_role_1_id'));
        $query->orderBy('ec.flight_role_1_id', 'desc');
        $results = $query->execute();
        
        if ( $results->rowCount() ) {
          $crew = $results->fetchAll();
        }
        
    
        //$query->condition('fr.flight_role_1_id', ELOG_FLIGHT_ROLE_INSTRUCTOR);  
        // instructor
        
        if ( $i && ($row->customer_id <> $last_customer_id) ) {
          $content .= '<h3>' . $customer_name . '</h3>';
          $content .= theme( 'table', array(
            'header' => $table_header,
            'rows' => $table_rows,
            'empty' => t('None'),
          ));
          $content .= '<br />';
          
          $table_rows = array();
        }
        
        $row_data = array(
          _st_format_schedule_date($row->begin_timestamp, 'n/j/Y', $row->timezone),
          $row->el_no,
          _st_format_schedule_date($row->begin_timestamp, 'H:i', $row->timezone),
          _st_format_schedule_date($row->end_timestamp, 'H:i', $row->timezone),
          $simulator_list->getName($row->simulator_id), // returns a formatted name
          '',  // crew will popuplate in these fields
          '',  // otherwise blank
          '',
        );
        
        for($c=0; $c<3; $c++) {
          
          if ( isset($crew[$c]) ) {
            $crew_name = $crew[$c]->lname . 
                        (strlen($crew[$c]->fname) ? ', ' . $crew[$c]->fname : '' );
            
            if ( (int)$crew[$c]->flight_role_1_id == ELOG_FLIGHT_ROLE_INSTRUCTOR ) {
              $row_data[5] = $crew_name;
            }
            else if ( (int)$crew[$c]->flight_role_1_id == ELOG_FLIGHT_ROLE_PILOT1 ) {
              $row_data[6] = $crew_name;
            }
            else if ( (int)$crew[$c]->flight_role_1_id == ELOG_FLIGHT_ROLE_PILOT2 ) {
              $row_data[7] = $crew_name;
            }
          }
        }
        //ksort($row_data);
        unset($crew);
        
        $table_rows[] = array('data' => $row_data);
        $last_customer_id = $row->customer_id;
        $customer_name = $row->customer;
				$i++;
      }
      
      if ( $last_customer_id ) {
        $content .= '<h3>' . $customer_name . '</h3>';
        $content .= theme( 'table', array(
          'header' => $table_header,
          'rows' => $table_rows,
          'empty' => t('None'),
        ));
        $content .= '<br />';
      }
    }
    if ( !$i ) {
      $content .= theme( 'table', array(
        'header' => $table_header,
        'rows' => $table_rows,
        'empty' => t('None'),
      ));
      $content .= '<br />';
    }
    $content .= '</div>';
		
	
		return $content;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_elog_session_report_list() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}


/*
 * _get_elog_quality_report_list()
 *
 */

function _get_elog_quality_report_list($customer_id = 0, $begin_date = '', $end_date = '') {
	try{
		
		$begin_ts = 0;
		$end_ts = 0;
    $simulator_list = new SimulatorList();

    $year = date('Y');
		
    // if no date range supplied, or a partial date range, only get elogs for this year
    $begin_ts = ( !strlen($begin_date) ? 
                    _st_format_system_timestamp($year . '-01-01 00:00:00') : _st_format_system_timestamp($begin_date . ' 00:00:00') );
    
    $end_ts = ( !strlen($end_date) ? 
            _st_format_system_timestamp($year . '-12-31 23:59:59') : _st_format_system_timestamp($end_date . ' 23:59:59') );
    
	
		$table_header = array( 
      array( 'data' => t('Date'), 'class' => array('sch-tbl-elog-date') ),
      array( 'data' => t('Customer'), 'class' => array('sch-tbl-elog-customer') ),
      array( 'data' => t('Simulator'), 'class' => array('sch-tbl-elog-simulator') ),
			array( 'data' => t('Session'), 'class' => array('sch-tbl-elog-session') ),
      array( 'data' => t('Rating'), 'class' => array('sch-tbl-elog-rating') ),
      array( 'data' => t('Comments'), 'class' => array('sch-tbl-elog-comments') ),
			//array( 'data' => t('Start'), 'class' => array('sch-tbl-elog-begintime') ),
			//array( 'data' => t('End'), 'class' => array('sch-tbl-elog-endtime') ),
      //array( 'data' => t('Instructor'), 'class' => array('sch-tbl-elog-instructor') ),
		);
    $table_rows = array();
    
    
    $query = db_select('sch_elogs', 'e');
    $query->innerJoin('sch_assignments', 'a', 'a.assignment_id = e.assignment_id');
    $query->innerJoin('sch_customers', 'c', 'c.customer_id = a.customer_id');
    $query->innerJoin('sch_schedules', 'sch', 'sch.schedule_id = a.schedule_id');
    $query->innerJoin('sch_schedule_sessions', 'ss', 
                                  'ss.schedule_session_id = a.schedule_session_id');
    $query->innerJoin('sch_session_names', 'sn', 
                                  'sn.session_name_id = ss.session_name_id');
    
    
    if ( $customer_id ) {
      $query->condition('a.customer_id', $customer_id);
    }
    $query->condition('a.begin_timestamp', $begin_ts, '>=');
    $query->condition('a.end_timestamp', $end_ts, '<=');
    
    
    $query->fields('e', array('elog_id', 'el_no', 'sim_quality_rating', 'log_text'))
          ->fields('a', array('assignment_id', 'customer_id', 
                              'begin_timestamp', 'end_timestamp'))
          ->fields('sn', array('session_name'))
          ->fields('c', array('customer'))
          ->fields('sch', array('simulator_id'));
          
    
    $query->orderBy('customer')->orderBy('simulator_id')->orderBy('a.begin_timestamp');
    
    $results = $query->execute();
    
    $i = 0;
    $last_customer_id = 0;
    $content = '<div id="qms-report-div">';
    $customer_name = '';
    $row_data = array();
    $crew = array();
    
    if ( $results->rowCount() ) {
      
      foreach($results as $row) {
        
        $quality = '';
        
        switch ($row->sim_quality_rating) {  
          case 1: $quality = t('Deficient'); break;
          case 2: $quality = t('Unsatisfactory'); break;
          case 3: $quality = t('Satisfactory'); break;
          case 4: $quality = t('Good'); break;
          case 5: $quality = t('Excellent'); break;
          default: 
            break;
        }
        
        $row_data = array(
          _st_format_system_date($row->begin_timestamp, 'n/j/Y'),
          $row->customer,
          $simulator_list->getName($row->simulator_id),
          $row->session_name . ': <br>' . 
            _st_format_system_date($row->begin_timestamp, 'H:i') . ' - ' . 
            _st_format_system_date($row->end_timestamp, 'H:i'),
          $quality,
          trim(nl2br(_st_convert_symbols($row->log_text))),
        );
        
        $table_rows[] = array('data' => $row_data);
        $last_customer_id = $row->customer_id;
        $customer_name = $row->customer;
				$i++;
      }
      
      if ( $last_customer_id ) {
        $content .= '<h3>' . $customer_name . '</h3>';
        $content .= theme( 'table', array(
          'header' => $table_header,
          'rows' => $table_rows,
          'empty' => t('None'),
        ));
        $content .= '<br />';
      }
    }
    if ( !$i ) {
      $content .= theme( 'table', array(
        'header' => $table_header,
        'rows' => $table_rows,
        'empty' => t('None'),
      ));
      $content .= '<br />';
    }
    $content .= '</div>';
		
	
		return $content;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_elog_quality_report_list() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}



/*
 * report_customer_sessions()
 *
 */
function report_customer_sessions($customer_id = 0, $begin_date = '', $end_date = '', 
                      $show_form_only = True) {
	if ( user_access('view manage menu') == FALSE ) {
    drupal_set_message( t('Unauthorized:  Permission is required'), 'status');
		return '';
  }
  
  if ( '0' == $begin_date ) { $begin_date = ''; }
  if ( '0' == $end_date ) { $end_date = ''; }
  $subtitle = '';
  $year = date('Y');
  
  if ( !strlen($begin_date) && !strlen($end_date) ) {
    $subtitle = $year;
  }
  else if ( !strlen($begin_date) ) {
    $ed = _st_right($end_date, 5);
    $ed = str_replace('-', '/', $ed) . '/' . $year;
    $subtitle = '1/1/' . $year . ' - ' . $ed;
  }
  else if ( !strlen($end_date) ) {
    $bd = _st_right($begin_date, 5);
    $bd = str_replace('-', '/', $bd) . '/' . $year;
    $subtitle = $bd . ' - ' . '12/31/' . $year;
  }
  
  $content = '';
  
  
  $print_page_heading = 
									'<div class="sch-print-header">' . 
										'<div class="sch-page-title">' .	drupal_get_title() . '</div>' . 
                    '<div class="sch-page-subtitle">' .	$subtitle . '</div>' . 
									'</div>';
	
	
  
  $content .= (!$show_form_only) ? $print_page_heading  : '';

  $form_elems = drupal_get_form('customer_sessions_report_form', $customer_id, $begin_date, $end_date);
	$content .= render($form_elems);

  if ( !$show_form_only ) {
    // if no customer or date_range provided, return all elogs for the current year only.
    $content .= _get_customer_sessions_list($customer_id, $begin_date, $end_date);
  }

	
	return $content;
}
  
  
  
/*
 * 	customer_sessions_report_form()
 * 	display form to get user input of search parameters
 *
 */

function customer_sessions_report_form($form, $form_state, 
                                    $customer_id = 0, $begin_date = '', $end_date = '') {
	
		
    drupal_add_library('system','ui.dialog');
    drupal_add_library('system','ui.datepicker');
    drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');

    drupal_add_js(drupal_get_path('module', 'sabreScheduler') .  '/js/sabreScheduler.report.cust.sess.js');


    //------------ BUILD SEARCH FORM ------------------
		global $base_url;

		//$simulator_list = new SimulatorList();
    $customer_list = new CustomerList();
    //$session_list = new SessionNameList();
		

		$form['search'] = array(
			'#type' => 'fieldset',
			'#title' => t('Report Settings'),
			'#collapsible' => True,
			'#collapsed' => False,
			'#attributes' => array('id' => array('sch-report-settings-div'),
                             'style' => 'padding-left:20px;'),
		);
		
    

		$form['search']['customer'] = array(
			'#type' => 'select',
			'#title' => t('Customer'),
			'#options' => $customer_list->getAll(CustomerList::INCL_ALL),
			'#default_value' => $customer_id,
			'#attributes' => array('class' => array('qms-select'),
														'id' => 'sch-customer-list'),
      '#prefix' => '<div style="float:left;">',
      '#suffix' => '</div>',
		);
    
    /*
    $form['search']['include_unavailable'] = array(
			'#type' => 'checkbox',
			'#title' => t('Include Unavailable Sessions'),
			'#default_value' => 0,
			'#attributes' => array('id' => 'sch-include-unavailable-chk'),
      //'#prefix' => '<div style="float:left;">',
      '#suffix' => '</div>',
		);
     * 
     */

		
		
//		$form['search']['search_date_label'] = array(
//			'#markup' => '<div style="float:left;clear:right;padding-left:40px;">',
//                    //'<h4>' . t('Report Date Range') . '</h4>',
//		);
		


		$form['search']['from_date'] = array(
			'#type' => 'date_popup',
			'#title' => t('From Date'),
			'#size' => 10,
			'#date_format' => 'm-d-Y',	
      '#default_value' => $begin_date,
			'#attributes' => array('style' => array('float:left', 'width:50px'),
															'id' => 'sch-from-date',
															'class' => array('qms-date-picker')),
			'#prefix' => '<div style="display:inline-block;text-align:left;padding-left:40px;">',
		);

		$form['search']['to_date'] = array(
			'#type' => 'date_popup',
			'#title' => t('To Date'),
			'#size' => 10,
			'#date_format' => 'm-d-Y',
      '#default_value' => $end_date,
			'#attributes' => array('style' => array('float:left', 'clear:right', 'width:50px'),
															'id' => 'sch-to-date',
																'class' => array('qms-date-picker')),
			'#suffix' => '</div><br class="clearBoth" />',
		);
    
    


		//--------------------------------------------
		// Adds a simple submit button that refreshes the form and clears its contents 
		// -- this is the default behavior for forms.
		$form['search']['actions'] = array('#type' => 'actions');
		$form['search']['actions']['submit'] = array(
			'#type' => 'button',
			'#value' => t('Submit'),
      '#name' => 'submit',
			'#attributes' => array('id' => 'sch-btn-submit',
															'sch-url' => url('reports/customer/sessions'),
                              'style' => 'font-weight:bold;'),
		);
    $form['search']['actions']['clear'] = array(
      '#type' => 'button',
      '#value' => t('Clear'),
      '#attributes' => array('class' => array('sch-clear', 'qms-btn-extra'),
                             'id' => 'sch-btn-clear'),
      
      '#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="sch-popup-dialog"></div>',
		);
		
		

		return $form;
}


/*
 * _get_customer_sessions_list()
 *
 */

function _get_customer_sessions_list($customer_id = 0, $begin_date = '', $end_date = '') {
	try{
		
		$begin_ts = 0;
		$end_ts = 0;
    $simulator_list = new SimulatorList();

    
    $year = date('Y');
		
    // if no date range supplied, or a partial date range, only get elogs for this year
    $begin_ts = ( !strlen($begin_date) ? 
                    _st_format_system_timestamp($year . '-01-01 00:00:00') : _st_format_system_timestamp($begin_date . ' 00:00:00') );
    
    $end_ts = ( !strlen($end_date) ? 
                    _st_format_system_timestamp($year . '-12-31 23:59:59') : _st_format_system_timestamp($end_date . ' 23:59:59') );
    
	
		$table_header = array( 
      array( 'data' => t('Date'), 'class' => array('sch-tbl-elog-date') ),
			array( 'data' => t('Start'), 'class' => array('sch-tbl-elog-begintime') ),
			array( 'data' => t('End'), 'class' => array('sch-tbl-elog-endtime') ),
      array( 'data' => t('Simulator'), 'class' => array('sch-tbl-elog-simulator') ),
		);
    $table_rows = array();
    
    //--------- Get Assignments/Bookings ---------------
    $query = db_select('sch_assignments', 'a');
		$query->innerJoin('sch_schedules', 'sch', 'a.schedule_id = sch.schedule_id');
		$query->innerJoin('sch_simulators', 'si', 'sch.simulator_id = si.simulator_id');
		//$query->innerJoin('sch_session_types', 't', 'a.session_type = t.session_type');
		$query->innerJoin('sch_customers', 'c', 'a.customer_id = c.customer_id');
		//$query->leftJoin('sch_groups', 'g', 'a.group_id = g.group_id');
		//$query->innerJoin('sch_users', 'u', 'c.customer_id = u.customer_id');

    if ( $customer_id ) {
      $query->condition('a.customer_id', $customer_id);
    }
		$query->condition('a.cut_bill', 0); // do not include cut_bill'ed assignments
		$query->condition('a.begin_timestamp', $begin_ts, '>=');
		$query->condition('a.begin_timestamp', $end_ts, '<=');
    
		$query->fields('a', array('assignment_id', 'begin_timestamp', 'end_timestamp', 
                              'customer_id', 'group_id', 'session_type'))
            ->fields('si', array('simulator_id', 'sim_name', 'device_id_internal'))
            ->fields('sch', array('schedule_id', 'timezone'))
						//->fields('t', array('session_type_desc'))
						->fields('c', array('customer'));
						//->fields('g', array('group_name'));
    
    $query->orderBy('c.customer')->orderBy('simulator_id')->orderBy('a.begin_timestamp');

    
    $results = $query->execute();
    
    $i = 0;
    $last_customer_id = 0;
    $last_simulator_id = 0;
    
    $sim_class = '';
    $content = '<div id="qms-report-div">';
    $customer_name = '';
    $row_data = array();
    
    if ( $results->rowCount() ) {
      
      
      foreach ($results as $row) {
        
        if ( $i && ($row->customer_id <> $last_customer_id) ) {
          $content .= '<h3>' . $customer_name . '</h3>';
          $content .= theme( 'table', array(
            'header' => $table_header,
            'rows' => $table_rows,
            'empty' => t('None'),
          ));
          $content .= '<br />';
          
          $table_rows = array();
        }
       
        
        $row_data = array(
          _st_format_schedule_date($row->begin_timestamp, 'n/j/Y', $row->timezone),
          _st_format_schedule_date($row->begin_timestamp, 'H:i', $row->timezone),
          _st_format_schedule_date($row->end_timestamp, 'H:i', $row->timezone),
          $simulator_list->getName($row->simulator_id), // formatted name
        );
        
        if ( $last_simulator_id && ($row->simulator_id <> $last_simulator_id) ) {
          $sim_class = 'sch-sim-divider';
        }
        else {
          $sim_class = 'sch-sim';
        }
        
        $table_rows[] = array('data' => $row_data, 
                              'class' => array($sim_class));
        $last_customer_id = $row->customer_id;
        $last_simulator_id = $row->simulator_id;
        $customer_name = $row->customer;
				$i++;
      }
      
      if ( $last_customer_id ) {
        $content .= '<h3>' . $customer_name . '</h3>';
        $content .= theme( 'table', array(
          'header' => $table_header,
          'rows' => $table_rows,
          'empty' => t('None'),
        ));
        $content .= '<br />';
      }
    }
    if ( !$i ) {
      $content .= theme( 'table', array(
        'header' => $table_header,
        'rows' => $table_rows,
        'empty' => t('None'),
      ));
      $content .= '<br />';
    }
    
    //------------------------- for ALL Customers: Append Exceptions ------------------------
    if ( !$customer_id ) {
      
      $results_except = _get_exceptions($begin_ts, $end_ts, '', 0, True);
      
      $table_rows = array();

      $i = 0;
      if ( $results_except->rowCount() ) {
      
        foreach ($results_except as $row) {
          
          $sim_name = (($row->simulator_id) ? 
                       $simulator_list->getName($row->simulator_id) : 
                       t('All Simulators'));
          
          $row_data = array(
            _st_format_system_date($row->begin_timestamp, 'n/j/Y'),
            _st_format_system_date($row->begin_timestamp, 'H:i'),
            _st_format_system_date($row->end_timestamp, 'H:i'),
            $sim_name, // formatted name
          );

          if ( $i  && ($row->simulator_id <> $last_simulator_id)) {
            $sim_class = 'sch-sim-divider';
          }
          else {
            $sim_class = 'sch-sim';
          }

          $table_rows[] = array('data' => $row_data, 
                                'class' => array($sim_class));
          //$last_customer_id = $row->customer_id;
          $last_simulator_id = $row->simulator_id;
          $i++;
        }
      }
      $content .= '<h3>' . t('Maintenance Exceptions') . '</h3>';
      $content .= theme( 'table', array(
        'header' => $table_header,
        'rows' => $table_rows,
        'empty' => t('None'),
      ));
      $content .= '<br />';
    }
    
    $content .= '</div>';
		
	
		return $content;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_customer_sessions_list() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
	
}



