<?php

/*
 *	Preventative Maintenance record functions for sabreQMS module
 */




/*
 *	prev_maint_display()
 *
 *  parms:  accepts a simulator_id for cases when refreshing a display after an add or edit
 *	returns:  Displays the first prev maint display screen with a dropdown simulator list
 *
 */

function prev_maint_display($simulator_id = '') {
	
	if (user_access('view admin lists') == False) {
		return;
	}
	
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.prevmaint.js');	
	
	// build initial display
  $form_elems = drupal_get_form('prev_maint_sim_list_form', $simulator_id);
	$content = render($form_elems);
	$content .= _prev_maint_simulator_schedule($simulator_id, False);
	
	return $content;
}


/*
 *	prev_maint_callback()
 *
 *	Callback handler for prev maint display
 *  When user selects a simulator from the list, refreshes the schedule display for that simulator
 *
 */

function prev_maint_callback($simulator_id = '') {
	return _prev_maint_simulator_schedule($simulator_id, True);
}


/*
 *	prev_maint_sim_list_form()
 *
 *  overloads:  hook_form()
 *
 *	Displays a simulator dropdown list as a form
 */

function prev_maint_sim_list_form($form, $form_state, $simulator_id = '') {
	
	// Get list of simulators to display -- active + inactive
	global $simulator_list;
	//$simulator_list = new SimulatorList();
	
	$form['simulator_id'] = array(
		'#type' => 'select',
		'#title' => t('Select a Simulator') . ' ( * =' . t('inactive') . ')',
		'#options' => $simulator_list->get(),
		'#prefix' => '<div id="pm-simulator-div">',
		'#suffix' => '</div>',
		'#attributes' => array( 'id' => 'pm-sim-list',
														'qms-url' => url('qmssettings/prevmaintlist')),
		'#default_value' => $simulator_id,
	);
	
	
	return $form;
}

/*
 *	prev_maint_simulator_schedule()
 *
 *	Displays a div with tables for the simulator schedule items
 */

function _prev_maint_simulator_schedule($simulator_id = 0, $bCallback = False) {

	$bAllowAdmin = user_access('administer sabreQMS');
	
	// WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
	$ckeditor_activated  = variable_get(QMS_VAR_WYSIWYG_EDITOR, 1);  // if not set, default to ON
	

	$daily_header = array( 
		array( 'data' => 'Daily' ),
	);
	$weekly_header = array( 
		array( 'data' => 'Weekly' ),
	);
	$monthly_header = array( 
		array( 'data' => 'Monthly' ),
	);
	
	if ( $bAllowAdmin == True ) {
		$daily_header[] = array(
			'data' => 'Admin',
			'class' => 'qms-table-opts',
		);
		$weekly_header[] = array(
			'data' => 'Admin',
			'class' => 'qms-table-opts',
		);
		$monthly_header[] = array(
			'data' => 'Admin',
			'class' => 'qms-table-opts',
		);
		
	}
	
	$daily_rows = array();
	$weekly_rows = array();
	$monthly_rows = array();

	$d = $w = $m = 0;
	
	if ( $simulator_id > 0 ) {
	
		$sql = 'SELECT prev_maint_id, pm_text, frequency, repeat_count, repeats_on, 
            start_pm_datetime, next_pm_datetime, preflight 
						FROM {qms_prev_maint} p 
					  WHERE simulator_id = :sid ORDER BY frequency, prev_maint_id';
		$result = db_query($sql, array(':sid' => $simulator_id ));

		
		foreach ($result as $row) {
			$repeat_phrase = '';
			switch($row->frequency) {
				case 'D':	
          $repeat_phrase = 
                ( $row->repeat_count == 1 )  ? ' Day' : $row->repeat_count . ' Days'; 
          $repeat_phrase .= ($row->preflight ? '  [' . t('Preflight') . ']' : '');
          break;
				case 'W':	
          $repeat_phrase = 
                ( $row->repeat_count == 1 )  ? ' Week' : $row->repeat_count . ' Weeks'; 
          break;
				case 'M':	
          $repeat_phrase = 
                ( $row->repeat_count == 1 )  ? ' Month' : $row->repeat_count . ' Months'; 
          break;
				default: break;
			}

			$pm_header = '<div class="qms-pm-header"><table class="qms-pm-table" width="40%">' . 
										'<tr><td width="20%">Repeat Every:</td><td>' . $repeat_phrase . '</td></tr>' . 
										( strlen($row->repeats_on) ? 
                        '<tr><td>Repeats On:</td><td>' . $row->repeats_on . '</td></tr>' : '') . 
										'<tr><td>Starts On:</td><td>' . _st_format_date($row->start_pm_datetime, 'short' ) . '</td></tr>' . 
										'<tr><td>Next Discrepancy:</td><td>' . _st_format_date($row->next_pm_datetime, 'short' ) . '</td></tr>' . 
										'</table></div>';
										
			$pm_text = '';
			if ( $ckeditor_activated ) {
				$pm_text .= _st_convert_symbols($row->pm_text);
			}	
			else {
				$pm_text .= nl2br(_st_convert_symbols($row->pm_text));
			}	
			
		
			$row_data = array( $pm_header . $pm_text );
			
			if ( $bAllowAdmin ){
				$row_data[] = _st_generate_options('prevmaint', $simulator_id . '/' . $row->prev_maint_id);
			}
		
				
			if ( $row->frequency == 'D' ) {
				$daily_rows[] = array('data' => $row_data);
				$d++;
			}
			else if ( $row->frequency == 'W' ) {
				$weekly_rows[] = array('data' => $row_data);			
				$w++;
			}
			else if ( $row->frequency == 'M' ) {
				$monthly_rows[] = array('data' => $row_data);
				$m++;
			}
			
		}
	}
	
 	if ( !$d || !$w || !$m  ) {
		$row_data = array('None');
	
		if ( $bAllowAdmin == True ) {
			$row_data[] = array(' ');
		}
		
		if ( !$d ) $daily_rows[] = array('data' => $row_data);
		if ( !$w ) $weekly_rows[] = array('data' => $row_data);
		if ( !$m ) $monthly_rows[] = array('data' => $row_data);
	}

	// Get the simulator preventative maintenance schedule
	$content = '';
	$content .= '<div id="pm-schedule-div">';

	if ( $simulator_id > 0 ) {
		// only show these if a simulator is selected
		if ( $bAllowAdmin )
		{
			$content .= l( t('Add Item'), 'prevmaint/add/' . $simulator_id, array('class' => 'prevmaint_add') );
			//$content .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp';
		}
		// add report function here
		//$content .= l( t('Create Report'), "#");
	}
	else {
		// placeholder
		$content .= '&nbsp';
	}
	
	$content .= theme( 'table', array(
		'header' => $daily_header,
		'rows' => $daily_rows,
	));
	$content .= theme( 'table', array(
		'header' => $weekly_header,
		'rows' => $weekly_rows,
	));
	$content .= theme( 'table', array(
		'header' => $monthly_header,
		'rows' => $monthly_rows,
	));
		
	$content .= '</div>';
	
	if ( $bCallback ) {
		// if doing an ajax callback return content and die otherwise whole page renders
		// in the <div> area rather than just the table data
		die($content);
	}

	return $content;
	
}




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

function prev_maint_form($form, $form_state, $simulator_id = 0, $prev_maint_id = 0) {

	if ( user_access('administer sabreQMS') == FALSE ) {
    return drupal_set_message( t('Unauthorized Access.  Administrator access required'));
  }

	if ( $simulator_id == 0 && $prev_maint_id == 0 ) {
    drupal_set_message(t('Oops!  Something seems to have gone wrong.  Simulator not found.'));
		drupal_goto('qmssettings/prevmaintlist');
		return;
  }		

	$pm_item = (object) Null;

	if ( $prev_maint_id > 0 ) {   // Edit existing record
		
		// get the record
		$sql = "SELECT simulator_id, pm_text, frequency, start_pm_datetime, 
									repeat_count, repeats_on, next_pm_datetime, preflight 
						FROM {qms_prev_maint} p 
						WHERE prev_maint_id = :pmid";
		$result = db_query($sql, array(':pmid' => $prev_maint_id));
		
		$pm_item = $result->fetchObject();
		
		if ( !isset($pm_item->simulator_id) ) {
	    drupal_set_message(t('Oops!  Something seems to have gone wrong.  Preventative Maintenance schedule item not found.'));
			drupal_goto('qmssettings/prevmaintlist');
			return;
	  }		
		
		$simulator_id = $pm_item->simulator_id;
	}
	
	// javascript loaded in the after_build function
	$form['#after_build'][] = 'prev_maint_form_after_build';
	

	// Simulator Name for display
	global $simulator_list;
	$form['sim_name'] = array(
		'#markup' => '<h2>' . $simulator_list->getName($simulator_id) . '</h2><br />',
	);
	
	// =================== PM Schedule =======================
	
	$form['pm_frequency'] = array(
		'#type' => 'fieldset',
		'#title' => t('Schedule'),
	);
	
	$form['pm_frequency']['begin_col1_div'] = array(
		'#markup' => '<div id="qms-pm-col1">'
	);
	
	$form['pm_frequency']['frequency'] = array(
		'#type' => 'select',
		'#title' => t('Frequency'),
		'#options' => array( 
										'0' => t('- Select -'),
										'D' => t('Daily'),
										'W' => t('Weekly'),
										'M' => t('Monthly'),
									),
		'#default_value' =>  (($prev_maint_id > 0) ? $pm_item->frequency : 0),
		'#attributes' => array('id' => 'qms-frequency',
													 'class' => array('qms-select')),
	);
	
	$form['pm_frequency']['repeat_count'] = array(
		'#type' => 'textfield',
		'#title' => t('Repeat Every'),
		'#size' => 3,
		'#maxlength' => '2',					
		'#default_value' => (($prev_maint_id > 0) ? $pm_item->repeat_count : 1), 
		'#required' => True,   
		'#attributes' => array(	'id' => 'qms-pm-repeat-count',
														'class' => array('qms-numeric')),
		'#suffix' => '<span id="qms-pm-repeat-interval"></span>',
	);
	
	$form['pm_frequency']['start_datetime'] = array(
		'#type' => 'date_popup',
		'#title' => t('Start Schedule'),
		'#size' => 14,
		'#date_format' => 'm-d-Y H:i',						// displayed format
			//default value has to be in this format
		'#default_value' => (($prev_maint_id > 0) ? _st_format_date($pm_item->start_pm_datetime, 'short') : _st_format_date(0, 'custom', 'Y-m-d H:i')), 
		'#required' => True,   // if no date entered, returns NULL
		// do not specify an 'id' attribute, interferes with datepicker function
		'#attributes' => array('class' => array('qms-date-picker')),
	);
	
	$form['pm_frequency']['end_col1_div'] = array(
		'#markup' => '</div>'
	);
	
	$form['pm_frequency']['begin_col2_div'] = array(
		'#markup' => '<div id="qms-pm-col2" style="float:left;clear:right;">'
	);
	
	
	
	$form['pm_frequency']['repeat_on_dow'] = array(
		'#type' => 'container',
		'#attributes' => array(	'id' => 'qms-repeat-on-dow'),
	);
	
	$dow_array = array();
	if ( isset( $pm_item->repeats_on) ) {
		$dow_array = explode(",", $pm_item->repeats_on);
	}
  
  $form['pm_frequency']['daily_preflight'] = array(
		'#type' => 'checkbox',
		'#title' => t('Preflight'),
		'#default_value' =>  (($prev_maint_id > 0) ? $pm_item->preflight : False ),
		//'#attributes' => array('id' => 'qms-pm-daily-preflight'),
	);
	
	$form['pm_frequency']['repeat_on_dow']['days_of_week'] = array(
		'#type' => 'checkboxes',
		'#title' => t('Repeat On Days'),
		'#options' => array( 
										'Su' => t('Sun'),
										'M' => t('Mon'),
										'Tu' => t('Tues'),
										'W' => t('Weds'),
										'Th' => t('Thurs'), 
										'F' => t('Fri'), 
										'Sa' => t('Sat'), 
									),
		'#default_value' =>  (($prev_maint_id > 0) ? $dow_array : array()),
		'#attributes' => array('id' => 'qms-pm-dow'),
	);
	
	$form['pm_frequency']['repeat_on_dom'] = array(
		'#type' => 'container',
		'#attributes' => array(	'id' => 'qms-repeat-on-dom'),
	);
	
	
	$form['pm_frequency']['repeat_on_dom']['days_of_month'] = array(
		'#markup' => '<label>Repeat On Dates</label><div id="qms-pm-days-of-month"></div>',
	);
	
	$form['pm_frequency']['end_col2_div'] = array(
		'#markup' => '</div>'
	);
	
	$form['pm_frequency']['repeat_on_list'] = array(
		'#type' => 'textfield',
		'#default_value' =>  (($prev_maint_id > 0) ? $pm_item->repeats_on : array()),
		'#attributes' => array('id' => 'qms-repeat-on-list',
														'class' => array('qms-hidden-field')),
	);
	
	
	// =================== CKEDITOR:  pm_text =======================
	
	$text_settings = array(
		'name' => 'pm_text',
		'title' => t('Preventative Maintenance - Discrepancy Report Text'),
		'text' =>	(($prev_maint_id > 0) ? $pm_item->pm_text : ''),
		'required' => True,
		'disabled' => False,
	);
	 
	_st_add_text_editor($form, $text_settings);
	

			
	
	$form['simulator_id'] = array(
		'#type' => 'textfield',
		'#value' => $simulator_id,
		'#attributes' => array(	'id' => 'qms-simulator-id',
														'class' => array('qms-hidden-field')),
	);	
	
	$form['prev_maint_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $prev_maint_id,
		'#attributes' => array(	'id' => 'qms-prev-maint-id',
														'class' => array('qms-hidden-field')),
	);					
	
	$form['pm_schedule_changed'] = array(
		'#type' => 'textfield',
		'#value' => '',
		'#attributes' => array(	'id' => 'qms-pm-schedule-changed',
														'class' => array('qms-hidden-field')),
	);	
				
	
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
    '#attributes' => array('class' => array('qms-btn-submit')),
	);
  $form['actions']['done'] = array(
		'#type' => 'button',
		'#value' => t('Done'),
		'#attributes' => array('class' => array('qms-btn-done', 'qms-btn-extra'),
                           'onclick' => 'window.location="' . 
                                            url('qmssettings/prevmaintlist/' . $simulator_id) . 
                                         '"; return false;'),
  );

	return $form;
}

/*------ AFTER BUILD FUNCTION --------
*	 functions called, as it implies, after the form is built
*  this is necessary when custom javascript and/or css files are added as needed
*  at the page level for forms that go through validation with hook_form_validate()
*  Otherwise, if a form fails validation, the page/form is reloaded for the user to correct
*  but the accompanying javascript & css is not reloaded with it. 
*  when $form['#after_build][] is used, the external scripts will be reloaded properly.
*/

/* 
 * prev_maint_form_after_build()
 *
 */

function prev_maint_form_after_build($form, &$form_state)
{
	drupal_add_library('system','ui.datepicker');
	drupal_add_library('system','ui.dialog');
	//drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/jquery.ui.core.js');
	//drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/jquery.ui.datepicker.js');
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/vendor/jquery-ui.multidatespicker.js');
  
  //_st_add_js_timezone();
  $sabreTools = drupal_get_path('module', 'sabreTools');
	drupal_add_js($sabreTools . '/js/sabreTools.lib.js');
	drupal_add_js($sabreTools . '/js/sabreTools.ckeditor.js');
	
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.prevmaintform.js');
	
	// WYSIWYG EDITOR??  Is this feature enabled allowing for the editor
	if ( isset( $form['ckeditor_module_path'])  ) {		
		global $base_url;
		drupal_add_js( $base_url . QMS_CKEDITOR_PATH_CONFIG);
		// need to specify preprocess == false otherwise 'Aggregate Javascript' setting in drupal 
		// causes ckeditor not to load properly
		// adding scope to footer speeds up the page load
		drupal_add_js( $base_url . QMS_CKEDITOR_LIB, array('type' => 'file', 'scope' => 'footer', 'preprocess' => FALSE));
	}
		
	return $form;
}

/*
 *	prev_maint_form_validate()  
 *
 *  overloads:  hook_form_validate()
 *
 *	Validates form after it is submitted
 */

function prev_maint_form_validate($form, $form_state) {

	$freq = $form_state['values']['frequency'];
	$repeat_count = (int)$form_state['values']['repeat_count'];
	$repeat_on_list = trim($form_state['values']['repeat_on_list']);  // list of days of week or dates of month on which to repeat
	switch ($freq) {
		case 'D':
			if (( $repeat_count < 0 ) || ( 6 < $repeat_count )) {
				form_set_error('repeat_count', 
					t('For "Daily" frequency, please select a repeat interval from 1 to 6 or use the "Weekly" frequency setting.'));
			}
			break;
		case 'W':
			if (( $repeat_count < 0 ) || ( 3 < $repeat_count )) {
				form_set_error('repeat_count', 
					t('For "Weekly" frequency, please select a repeat interval from 1 to 3 or use the "Monthly" frequency setting.'));
			}
			if ($repeat_on_list == "") {
				form_set_error('days_of_week', 
					t('For the "Weekly" frequency setting, please select at least one day of the week.'));
			}
			break;
		case 'M':
			if (( $repeat_count < 0 ) || ( 12 < $repeat_count )) {
				form_set_error('repeat_count', 
					t('For "Monthly" frequency, please select a repeat interval from 1 to 12.'));
			}
			if ($repeat_on_list == "") {
				form_set_error('days_of_month', 
					t('For the "Monthly" frequency setting, please select at least one day of the month.'));
			}
			break;
		case '0':
		default:
			form_set_error('frequency', t('Please select the preventative maintenance frequency.'));
	}
	
	// add seconds to make it DATE_ISO format:  'YYYY-MM-DD HH24:MI:SS'
	// date_opened may not always be present if the element is display only due to permission restrictions
	$start_datetime = '';
	$istate_datetime = 0;
	if ( isset($form_state['values']['start_datetime']) ) {
		$start_datetime = $form_state['values']['start_datetime'];
		$istart_datetime = _st_format_timestamp($start_datetime);  
		$itoday = _st_format_timestamp(date("Y-m-d")  . ' 00:00:01');
		
		if ( $istart_datetime == 0 ) {
			form_set_error('start_datetime', t('Start Schedule is a required field'));
		}
		else if ( $istart_datetime < $itoday ) {
			form_set_error('start_datetime', t('Start Schedule date must not be before today'));
		}
	}
	
	if ( trim( $form_state['values']['pm_text_editor_value'] ) == '' ) {
		form_set_error('qms_pm_text', t('Preventative Maintenance Discrepancy Text is a required field'));
	}
	
}

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

function prev_maint_form_submit($form, $form_state) {
	$pm_item = (object) NULL;
	
	$prev_maint_id = (int)$form_state['values']['prev_maint_id'];
	if ($prev_maint_id == 0) {  // NEW
		$pm_freq = $form_state['values']['frequency'];
	}
	else {
		$pm_item->prev_maint_id =  $prev_maint_id;
	}
	$pm_item->frequency = trim($form_state['values']['frequency']);
	$pm_item->simulator_id = (int) $form_state['values']['simulator_id'];
  $pm_item->preflight = (int)$form_state['values']['daily_preflight'];
	$pm_item->pm_text = _st_clean_ckeditor_text($form_state['values']['pm_text_editor_value'], QMS_TEXTAREA_MAX);
	$pm_item->repeat_count = (int)$form_state['values']['repeat_count'];
	$pm_item->repeats_on = trim($form_state['values']['repeat_on_list']);
	$start_datetime = $form_state['values']['start_datetime'] . ':00';
	$pm_item->start_pm_datetime = _st_format_timestamp($start_datetime);
		
	// Calculate the next_pm_datetime
	$pm_item->next_pm_datetime = _calc_next_pm_schedule_date( $pm_item->frequency,
																												$pm_item->repeat_count,
																												$pm_item->repeats_on,
																												$start_datetime, $bStartingNew = True);
	
	if  ( $prev_maint_id == 0 )  {  
		// new record
		// Table:  {qms_prev_maintenance}
		
		// write a prev maint record for each frequency with the same pm_text
		// skip the frequencies with a zero setting
		drupal_write_record('qms_prev_maint', $pm_item);
	}
	else {
		// update existing
		// Table:  {qms_prev_maintenance}
		// just updating a specific pm item with a set frequency
		drupal_write_record('qms_prev_maint', $pm_item, 'prev_maint_id');
	}
	
	drupal_goto('qmssettings/prevmaintlist/' . $pm_item->simulator_id);
}

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

function prev_maint_delete_confirm($form, $form_state, $prev_maint_id) {
	
	if ( user_access('administer sabreQMS') == FALSE ) {
    drupal_set_message( t('Unauthorized Access.  Administrator access required.'));
		drupal_goto('qmssettings/prevmaintlist');
		return;	
  }

	$prev_maint_id = check_plain($prev_maint_id);
	
	// Get record by id
	$sql = "SELECT simulator_id, pm_text, frequency FROM {qms_prev_maint} p WHERE prev_maint_id = :pmid";
	$result = db_query($sql, array(':pmid' => $prev_maint_id));
	
	$pm_item = $result->fetchObject();
	
	$form['prev_maint_id'] = array(
		'#type' => 'value',
		'#value' => $prev_maint_id,
	);
	
	$form['simulator_id'] = array(
		'#type' => 'value',
		'#value' => $pm_item->simulator_id,
	);	
	
	$form['pm_text'] = array(
		'#type' => 'value',
		'#value' => substr($pm_item->pm_text, 0, 20),
	);
	
	$freq_text = '';
	switch ( $pm_item->frequency ) {
		case 'D': $freq_text = 'Daily'; break;
		case 'W': $freq_text = 'Weekly'; break;
		case 'M': $freq_text = 'Monthly'; break;
	}
	
	$form['frequency'] = array(
		'#type' => 'value',
		'#value' => $freq_text,
	);
  
  $title = t('Delete Maintenance Item') . '?';
  $question = t('Are you sure you want to delete?') . 
              '<h2>' . $freq_text . '</h2>' . 
              '<p>' . substr($pm_item->pm_text, 0, 200) . '...' . '</p><br />' . 
              t('This action cannot be undone.');
  $goto_if_canceled = 'qmssettings/prevmaintlist/' . $pm_item->simulator_id;
  $yes_btn = 	t('Delete');
  $no_btn = t('Cancel');
	
  // force this here to avoid a problem with routing if cancelled
  //$_GET['destination'] = $goto_if_canceled;
  
  return confirm_form($form, $title,	$goto_if_canceled, $question, 
                      $yes_btn, $no_btn);
  
}

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

function prev_maint_delete_confirm_submit($form, $form_state) {
	
	$redirect_link = '';
	
	if ( $form_state['values']['confirm']) {
		$prev_maint_id = $form_state['values']['prev_maint_id'];
		$pm_text = $form_state['values']['pm_text'];
		$frequency = $form_state['values']['frequency'];
		$redirect_link = 'qmssettings/prevmaintlist/' . $form_state['values']['simulator_id'];
	
		// delete from database
		$num_rows = db_delete('qms_prev_maint')
								->condition('prev_maint_id', $prev_maint_id, '=')
								->execute();
	
		$msg = '';					
		if ( $num_rows != 1 ) {
			$msg = 'Oops!  Unable to delete record "' . $pm_text . '".';
			drupal_set_message(t($msg));
			drupal_goto($redirect_link);
			return;
		}
	
		$msg = 'Preventative Maintenance record for ' . 
            $frequency . ' has been deleted.';
		drupal_set_message(t($msg));
		
	}
	
	drupal_goto($redirect_link);
}


/* --------------------------------------------------------------------------------------
 *	_calc_next_pm_schedule_date()     ---- DATE PREDICTION
 *
 *	@param:
 *		frequency:			D | W | M   				--> daily weekly or monthly
 *		repeat_count:		numeric							--> repeat every n (days, weeks, or months)
 *		repeats_on:													--> weekly or monthly only
 *			weekly:				Su,M,Tu,W,Th,F,Sa
 *			monthly:			1,2,3,4,5..31
 *		start_date:			'yyyy-mm-dd hh:mm:ss' or unix timestamp  --> calculate from this date
 *		start_new:			True | False					--> this is a new schedule starting (true), otherwise repeating an existing (false)
 *	@return:
 *		new next_date		date in unixtime		--> next predicted date in the schedule
 */

function _calc_next_pm_schedule_date( $frequency, $repeat_count, $repeats_on, $start_date, $start_new = False) {
	
	$new_date = 0;
  $calc_from_date = '';
  $icalc_from_date = 0;
  
  if (is_integer($start_date)) {
    $icalc_from_date = $start_date;
    $calc_from_date = _st_format_date($icalc_from_date, 'iso');
  } else if (is_string($start_date)) {
    $calc_from_date = $start_date;
    $icalc_from_date = _st_format_timestamp($calc_from_date);
  }

	
	//-------------------- DAILY --------------------
	if ( $frequency == 'D' ) {	
    
    $new_date = $icalc_from_date;
    
    if (!empty(REQUEST_TIME)) {
      // new date is in the past, in the event cron failed at some point, try again
      do {
        $new_date = _st_modify_timestamp($new_date, '+' . $repeat_count . ' days');
      } while($new_date <= REQUEST_TIME);
    }
//    echo "New Date: " . _st_format_date($new_date). "\n";
//    echo "REQUEST_TIME:  " . _st_format_date(REQUEST_TIME). "\n";
//    return $new_date;

	}
	//-------------------- WEEKLY --------------------
	else if ( $frequency == 'W' ) {
		
		// build reference array of days of week and flag the days to be repeated on
		// zero-based to match getdate() referencing
    
		$days_of_week = array(
			'Su' => 'Sunday',
			'M' => 'Monday',
      'Tu' => 'Tuesday',
      'W' => 'Wednesday',
      'Th' => 'Thursday',
      'F' => 'Friday',
      'Sa' => 'Saturday',
    );
    
    $day_of_week = $days_of_week[$repeats_on];

		
    $new_date = $icalc_from_date;
    
    if (!empty(REQUEST_TIME)) {
      // new date is in the past, in the event cron failed at some point, try again
      do {
        $new_date = _st_modify_timestamp($new_date, '+' . $repeat_count . ' weeks');
      } while($new_date <= REQUEST_TIME);
      // make sure its on the right day of week
      $new_date = _st_modify_timestamp($new_date, $day_of_week.' this week');
      
      $date_part = _st_format_date($new_date, 'custom', 'Y-m-d');
      $time_part = _st_format_date($icalc_from_date, 'custom', 'H:i:s');
      
      $assemb_date = $date_part . ' ' . $time_part;
      $new_date = _format_timestamp($assemb_date);
    }
    
	}
	//-------------------- MONLTHLY --------------------
	
	else if ( $frequency == 'M' ) {
		
		// build reference array for days of month to repeat on		
		// contains 0-based reference to dates in month when PM is repeated
		$repeat_on_days = explode(",", $repeats_on);	
		$days_of_month = array();
		
		for ( $i=1; $i <= 31; $i++ ) {
			$days_of_month[$i] = False;		// init all to false
		}
		for ( $i=0; $i < count($repeat_on_days); $i++ ) {
			$days_of_month[(int)$repeat_on_days[$i]] = True;		// init the repeat_on days in the month array to be True
		}
			
		$calc_date_array = getdate($icalc_from_date);  // get the date structure for the date we are starting from
		$start_dom = $calc_date_array['mday'];
    
//    echo "Start DOM: $start_dom\n";
    
    $dom = $start_dom;
    
    $repeat_day_count = count($repeat_on_days);
//    echo "Repeat Day Count: $repeat_day_count\n";
//    print_r($repeat_on_days);
    if ((int)$dom >= (int)$repeat_on_days[$repeat_day_count-1]) {
      $dom = (int)$repeat_on_days[0];
    } else {
      foreach ($repeat_on_days as $mday) {
        if ($dom < $mday) {
          $dom = $mday;
          break;
        }
      }
    }
   
		
		// do the calculation for the new date
		$add_days = $dom - 1;  // decrement 1 to allow for 'first day of' calculation
		$d = 'first day of ' . $calc_from_date;
		$new_date = _st_format_timestamp($d);
    
    //echo "First Day of Month: " . _st_format_date($new_date). "\n";
    
    if (!empty(REQUEST_TIME)) {
      // new date is in the past, in the event cron failed at some point, try again
      do {
        $new_date = _st_modify_timestamp($new_date, '+' . $repeat_count . ' months');
        //echo "New Date: " . _st_format_date($new_date). "\n";
      } while($new_date <= REQUEST_TIME);
    }
    
    $new_date = _st_modify_timestamp($new_date, '+' . $add_days . ' days');
		
	}
  
  // DEBUG
  //echo "New Date: " . _st_format_date($new_date). "\n";

	return $new_date;
}





