<?php

/**
 *		sabreScheduler Module for plugin to Drupal 7 Framework
 *
 *		Common utility functions for Sabre Scheduler
 *
 *    directly include into code files as needed
*/

/* 
 * _get_user_name()
 *
 *	returns:  returns in this order of priority
 *						(1) sch_users.full_name, if found
 *						(2) user.name, if found
 *  					(3) empty string, if (1) or (2) not found or user_id=0
 *						
 */
function _get_user_name($user_id) {
	
	try{
	
		if ( (int)$user_id == 0 ) {
			return '';
		}
		
		$flag = '';
		$sql = "SELECT full_name FROM {sch_users} WHERE user_id = :uid";
		$result = db_query($sql, array(':uid' => $user_id));
		if ( $result->rowCount() == 0 ) {
			// nothing found ?? try the users table as an alternate

			$sql = "SELECT name FROM {users} WHERE uid = :uid";
			$result = db_query($sql, array(':uid' => $user_id));

			if ( $result->rowCount() == 0 ) {
				return '[not found]';
			}
			$flag = "*";  //flag indicator that the user is NOT an employee
		}
		return ( $result->fetchField() . $flag );	
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_user_name() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}




/*
 *	_st_format_record_timestamp_table($record, $type)
 *
 *	Accepts these report objects:  customer
 *	Formats the created + updated timestamps and user info into a table for display
 */
/*
function _st_format_record_timestamp_table($record, $type = '')  {
	$ts_table = '';
	$created_row = '';
	$updated_row = '';  // this may not always be visible
	
	if ( $record->created_by_user || $record->created_date ) {
		$email = _st_get_user_email($record->created_by_user);  // this may return '' if created_by_user==0
		$user_link = ( strlen($email) ? l(_get_sch_user_name($record->created_by_user), 'mailto:' . $email) : _get_sch_user_name($record->created_by_user) );
		$created_row = '<tr><td style="width:10%">' . t('Created') . ':  </td><td>' . 
										( $record->created_by_user ? $user_link . ', ' : t('Scheduler') . ', ' ) . 
										( $record->created_date ? format_date($record->created_date) : '') . '</td></tr>';
	}
	else {
		$created_row = '<tr><td style="width:15%">&nbsp;</td><td>&nbsp;</td></tr>';
	}
	if ( $record->updated_by_user || $record->updated_date ) {
		$email = _st_get_user_email($record->updated_by_user);  // this may return '' if created_by_user==0
		$user_link = ( strlen($email) ? l(_get_sch_user_name($record->updated_by_user), 'mailto:' . $email) : _get_sch_user_name($record->updated_by_user) );
		
		$updated_row = '<tr><td style="width:10%">' . t('Updated') . ':  </td><td>' . 
										( $record->updated_by_user ? $user_link . ', ' : t('Scheduler') . ', ') . 
										( $record->updated_date ? format_date($record->updated_date) : '')  . '</td></tr>';
	}
		
	$ts_table = '<div class="qms-desc"><table class="qms-plain-table" style="font-size:95%">' . 
									$created_row . $updated_row . '</table></div><hr />';
	return $ts_table;
}
 */

/*
 *	_format_schedule_dates()
 *
 *	Accepts $schedule record
 *	Formats the begin_date + end_date schedule dates for display
 */

function _format_schedule_dates($schedule)  {
	$date_table = '';
	$begin_date_row = '';
	$end_date_row = '';  // this may not always be visible
	
	$begin_date_row = '<tr><td style="width:10%">' . t('Begin Date') . ':  </td><td>' . 
									( $schedule->begin_date ? 
                      _st_format_system_date($schedule->begin_date, 'm-d-Y') : '') . '</td></tr>';
	$end_date_row = '<tr><td style="width:10%">' . t('End Date') . ':  </td><td>' . 
									( $schedule->end_date ? 
                      _st_format_system_date($schedule->end_date, 'm-d-Y') : '[None]')  . '</td></tr>';
		
	$date_table = '<div class="qms-desc"><table class="qms-plain-table" style="font-size:95%">' . 
									$begin_date_row . $end_date_row . '</table></div><hr />';
	return $date_table;
}

function _get_scheduler_cache_name($cache_name_const) {
	global $user;
	$name = '';
	
	switch ($cache_name_const) {
		// this group is the shared cache across all QMS users
		case SCH_CUSTOMER_LIST:
		case SCH_MONTH_LIST:
		//case SCH_YEAR_LIST:
		case SCH_SESSION_TYPE_LIST:
    case SCH_SESSION_NAME_LIST:
    case SCH_FLIGHT_ROLES_LIST:
    case SCH_INTERVAL_LIST:
		case SCH_EXCEPTIONS_SEARCH_FORM:
    case SCH_ELOGS_SEARCH_FORM:
			$name = $cache_name_const;
			break;
		case SCH_USER_CLIPBOARD:
			$name = $cache_name_const . '_' . $user->uid;
			break;
		default:		// this is to handle user-specific cache, such as searches
			$name = $cache_name_const . '_' . $user->uid . '_' . $user->sid;
	}
	return $name;
}


function _clear_scheduler_cache($cache_name_const) {
	$name = '';
	
	switch ($cache_name_const) {
		case SCH_CUSTOMER_LIST:
		case SCH_MONTH_LIST:
		//case SCH_YEAR_LIST:
		case SCH_SESSION_TYPE_LIST:
    case SCH_SESSION_NAME_LIST:
    case SCH_FLIGHT_ROLES_LIST:
    case SCH_INTERVAL_LIST:
		case SCH_EXCEPTIONS_SEARCH_FORM:
    case SCH_ELOGS_SEARCH_FORM:
			$name = $cache_name_const;
			cache_clear_all($name, 'cache', TRUE); 
			break;
		case SCH_USER_CLIPBOARD:  // stored in variable
			break;
		default:
			global $user;
			$name = $cache_name_const . '_' . $user->uid . '_' . $user->sid;
			cache_clear_all($name, 'cache', TRUE); 
	}
	
}

function _format_date_parts($year, $month, $day) {
    // pad single digit months/days with a leading zero for consistency (aesthetics)
    // and format the date as desired: YYYY-MM-DD by default

    if (strlen($month) == 1) {
        $month = "0". $month;
    }
    if (strlen($day) == 1) {
        $day = "0". $day;
    }
    $date = $year ."-". $month ."-". $day;
    return $date;
}


/*
 *		_format_session_date()
 *		IN:  date string m-d-Y, time (string) in 'hhmm' | 'hh:mm' | 'hh:mm:ss' format
 *		OUT: unixtimestamp with the provided time
 */

function _format_session_date($date = '', $time = '0000', $timezone = '', $modify = '', $format='Y-m-d H:i:s') {
  //echo "$ts; $time; $timezone; $modify<br/>\n";
  
  try {
    if (empty($timezone)) { $timezone = _st_get_timezone(False); }

    $h = 0;
    $m = 0;
    $s = 0;

    if ( (strlen($time) == 4) || (strlen($time) == 5) ) {
      $h = (int) _st_left($time, 2);
      $m = (int) _st_right($time, 2);
    } else if ( strlen($time) == 8 ) {
      $a = explode(':', $time);
      $h = (isset($a[0]) ? (int) $a[0] : 0);
      $m = (isset($a[1]) ? (int) $a[1] : 0);
      $s = (isset($a[2]) ? (int) $a[2] : 0);
    }

    $dt = DateTime::createFromFormat('m-d-Y', $date);
    $dt->setTimezone(new DateTimeZone($timezone));
    $dt->setTime($h,$m,$s);
            
    //$dt = new DateTime('now', new DateTimeZone($timezone), $dt);
    //echo "_format_timestamp: $ts<br />\n";
//    $dt->setTimestamp((int)$ts);
//    $dt->setTime($h, $m, $s);
    if (!empty($modify)) {
      $dt->modify($modify);
    }
  
    return $dt->format($format);
  
  } catch (Exception $e) {
    echo "Exception";
    var_dump($e->getTraceAsString());
    watchdog(SCH_SCHEDULER, '_format_session_date() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
} 

/*
 *		_format_timestamp()
 *		IN:  unix timestamp GMT, time (string) in 'hhmm' | 'hh:mm' | 'hh:mm:ss' format
 *		OUT: unixtimestamp with the provided time
 */

function _format_timestamp($ts, $time = '0000', $timezone = '', $modify = '') {
  //echo "$ts; $time; $timezone; $modify<br/>\n";
  
  try {
    if (empty($timezone)) { $timezone = _st_get_timezone(False); }

    $h = 0;
    $m = 0;
    $s = 0;

    if ( (strlen($time) == 4) || (strlen($time) == 5) ) {
      $h = (int) _st_left($time, 2);
      $m = (int) _st_right($time, 2);
    } else if ( strlen($time) == 8 ) {
      $a = explode(':', $time);
      $h = (isset($a[0]) ? (int) $a[0] : 0);
      $m = (isset($a[1]) ? (int) $a[1] : 0);
      $s = (isset($a[2]) ? (int) $a[2] : 0);
    }

    $dt = new DateTime('now', new DateTimeZone($timezone));
    //echo "_format_timestamp: $ts<br />\n";
    $dt->setTimestamp((int)$ts);
    $dt->setTime($h, $m, $s);
    if (!empty($modify)) {
      $dt->modify($modify);
  }
  
	return $dt->getTimestamp();
  
  } catch (Exception $e) {
    echo "Exception";
    var_dump($e->getTraceAsString());
    watchdog(SCH_SCHEDULER, '_format_timestamp() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
} 

/*
 *		_format_timestamp_parts()
 *		IN:  unix timestamp GMT, time (string) in 'hhmm' format
 *		OUT: unixtimestamp with the provided time
 */

function _format_timestamp_parts($yr, $mon, $day, $time = '0000', $timezone = '') {
  if (empty($timezone)) { $timezone = _st_get_timezone(); }
  
	$hh = _st_left($time, 2);
	$mm = _st_right($time, 2);
  
  $dt = new DateTime('now', new DateTimeZone($timezone));
  $dt->setDate($yr, $mon, $day);
  $dt->setTime($hh,$mm,0);
  
	return $dt->getTimestamp();
} 


/*
 *		_format_cal_date()
 *		IN:  unix timestamp GMT, time (string) in 'hhmm' | 'hh:mm' | 'hh:mm:ss' format
 *		OUT: unixtimestamp with the provided time
 */

function _format_cal_date($idate, $time) {
	
	$new_date = '';
  
  /*
   *  Drupal format_date has a bug which mishandles dates near the
   *  DST changeover in March & November ... switch to PHP date() function
   *  for correct handling
   */
  
  $base_date = _st_format_system_date($idate, 'Y-m-d');
	$time_len = strlen($time);
	
	if ( !$time_len ) {
		// no time submitted
		$new_date = $base_date . ' 00:00:00';
	} 
	else if ( (4 == $time_len) || (5 == $time_len) ) {
		$hh = _st_left($time, 2);
		$mm = _st_right($time, 2);
		$new_date = sprintf('%s %s:%s:01', $base_date, $hh, $mm);
	}
	else {
		$new_date = $base_date . ' ' . $time;
	}
	
	return $new_date;
}



/* 
 * _get_calendar_dates()
 *
 *	returns:  the dates in the provided unix timestamp date range
 *						
 */
function _get_calendar_dates($begin_date_range, $end_date_range) {
	
	try{
		
		$date_list = array();
	
		if ( !$begin_date_range || !$end_date_range ) {
			return $date_list;
		}
		
		$query = db_select('sch_calendar', 'c');	
		$query->condition('calendar_date', $begin_date_range, '>=');
		$query->condition('calendar_date', $end_date_range, '<=');
		$query->fields('c', array('calendar_date'));
		$results = $query->execute();
		
		if ( $results->rowCount() ) {
			$date_list = $results->fetchCol();
		}
		return $date_list;	
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '_get_calendar_dates() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}



/*
 * 
 *  _calc_repeat_days()
 * 
 *  IN: $begins,        // begin date of the base interval (ISO date format)
 *      $ends,          // end date of the base interval (ISO date format)
 *      $end_on_date    // last day the interval repeats (ISO date format)
 *  RETURN:   number of days in the interval
 */


function _calc_repeat_days($begins, $ends, $end_on_date, $timezone) {
  
  // get the time portion only
  $begin_time = _st_right($begins, 8);
  $end_time = _st_right($ends, 8);
  
  // convert to timestamps to do the math
  $begins_ts = _st_format_schedule_timestamp($begins, $timezone);
  $ends_ts = _st_format_schedule_timestamp($ends, $timezone);
  $base_interval = ($ends_ts - $begins_ts);
  $days = ceil(($base_interval / SCH_ONE_TS_DAY));
  if ( $days < 1 ) { $days = 1; } // failsafe, but shouldn't happen
  
  $eod_text = _st_left($end_on_date, 10) . ' ' . $begin_time;
  $eod_ts = _st_format_schedule_timestamp($eod_text, $timezone);
  
  $num = round((($eod_ts - $begins_ts) / ($days * SCH_ONE_TS_DAY))) + 1;
  
  return $num;
}

function _add_day_ts($timestamp, $ndays = 1) {
  //$d = date('Y-m-d H:i:s', $timestamp);
  $dt = new DateTime;
  $dt->setTimestamp($timestamp);
  //$dt->setTimezone(new DateTimeZone('GMT'));
  //$d = $dt->format('Y-m-d H:i:s');
  $interval = '';
  
  if ( $ndays < 0) {
    $interval = '-';
  }
  else {
    $interval = '+';
  }
  $interval .= abs($ndays) . ' day';
  if ( ($ndays > 1) || ($ndays < -1)) { 
    $interval .= 's'; 
  }
  $dt->modify($interval);
  return $dt->getTimestamp();
}

/*
 *  _date_diff_seconds($begints, $endts)
 * 
 *  IN: $begints,             // begin date timestamp
 *      $endts,               // end date timestamp
 *  RETURN:   $total_seconds  // number of seconds in the interval
 * 
 * -->accommodates DST -- requires PHP 5.3 or greater 
 */

function _date_diff_seconds($begints, $endts) {
  
  return _st_date_diff_seconds($begints, $endts);
  /*
  $date1 = new DateTime();
  //$date1->setTimezone(new DateTimeZone('GMT'));
  $date1->setTimestamp($begints);
  
  $date2 = new DateTime();
  //$date2->setTimezone(new DateTimeZone('GMT'));
  $date2->setTimestamp($endts);
  
  $interval = date_diff($date2, $date1);
  
  $total_seconds = ($interval->days*86400) + 
                   ($interval->h*3600) + 
                   ($interval->i*60) + 
                   $interval->s;
  return $total_seconds;
   * 
   */
}

/*
 *  _DT_date_diff_seconds($begints, $endts)
 * 
 *  IN: $begints,             // DateTime object
 *      $endts,               // DateTime object
 *  RETURN:   $total_seconds  // number of seconds in the interval
 * 
 * -->accommodates DST -- requires PHP 5.3 or greater 
 */

function _DT_date_diff_seconds($begins_dt, $ends_dt) {
  
  $interval = date_diff($ends_dt, $begins_dt);
  
  $total_seconds = ($interval->days*86400) + 
                   ($interval->h*3600) + 
                   ($interval->i*60) + 
                   $interval->s;
  return $total_seconds;
}


/* 
 * _get_schedule_timezone()
 *
 */
function _get_schedule_timezone($schedule_id = 0) {
	
	try{
		
    if (!empty($_ENV['schedule_timezone'])) { return $_ENV['schedule_timezone']; }
    
		if ( !$schedule_id) {
			return _st_get_timezone(False);
		}
    
		
		$query = db_select('sch_schedules', 's');	
		$query->condition('schedule_id', $schedule_id, '=');
		$query->fields('s', array('timezone'));
		$timezone = $query->execute()->fetchField();
    
    _set_schedule_timezone($timezone);
    return $timezone;
	}
	catch(Exception $e) {
		watchdog(SCH_SCHEDULER, '__get_schedule_timezone() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
	}
}

/*
 *  _set_schedule_timezone()
 */
function _set_schedule_timezone($tz) {
  $_ENV['schedule_timezone'] = $tz;
}

/*
 *  _get_calendar_range()
 */
function _get_calendar_range($begin_ts, $end_ts) {
  try {
    if (!$begin_ts || !$end_ts) { return False; }
    $query = db_select('sch_calendar', 'c');
    $query->fields('c', array('calendar_date'));
    $query->condition('calendar_date', $begin_ts, '>=');
    $query->condition('calendar_date', $end_ts, '<=');
    $query->orderBy('c.calendar_date', 'ASC');

    $results_cal = $query->execute()->fetchAll();
    
    return $results_cal;
    
  } catch (Exception $ex) {
    watchdog(SCH_SCHEDULER, '_get_calendar_range() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
  }
    
}

/*
 *  Simulator Quality Rating
 */
function _get_sim_quality_desc($rating) {
  
	$rating_desc = '';
	
	switch ($rating) {
		case 1: $rating_desc = t('Deficient'); break;
		case 2: $rating_desc = t('Unsatisfactory'); break;
		case 3: $rating_desc = t('Satisfactory'); break;
		case 4: $rating_desc = t('Good'); break;
		case 5: $rating_desc = t('Excellent'); break;
	}
  
  return $rating_desc;
}