*/
if ($debug) {
	$timer['main_start'] = microtime(true);
}
/*if ($_GET) {
	show_var($_GET, '$_GET');
}*/
if ($_SERVER) {
	$refer_outer = explode('&', substr($_SERVER['HTTP_REFERER'], strpos($_SERVER['HTTP_REFERER'], '?') + 1));
	$refer_inner = array();
	foreach ($refer_outer AS $refer) {
		$refer = explode('=', $refer);
		$refer_inner[$refer[0]] = $refer[1];
	}
	d($refer_inner);
	if (isset($refer_inner['page']) && isset($refer_inner['event_id']) && isset($refer_inner['id'])) {
		$next_event_id = getNextEventId($refer_inner['event_id'], $refer_inner['page']);
		if ($next_event_id !== false) {
			header('Location: ' . APP_PATH_WEBROOT . "DataEntry/index.php?pid=$project_id&id=" . urlencode($refer_inner['id']) . "&event_id=$next_event_id&page={$refer_inner['page']}");
		} else {
			d($next_event_id);
		}
	} else {
		echo "<h1>You must first select a subject and a form to use this plugin.</h1>";
	}
}
if ($debug) {
	$timer['main_end'] = microtime(true);
	$init_time = benchmark_timing($timer);
	echo $init_time;
}
/**
 * @param $subject_id
 * @param $debug
 * determine completeness of all survey-containing events
 */
function events_completion($subject_id, $debug) {
	if (isset($subject_id)) {
		global $Proj, $project_id;
		$today = date("Y-m-d");
		$fields = array();
		$arms = get_arms(array_keys($Proj->eventsForms));
		$baseline_event_id = $Proj->firstEventId;
		$enrollment_event_id = getNextEventId($baseline_event_id);
		$tx_duration = get_single_field($subject_id, $project_id, $enrollment_event_id, 'dm_suppdm_actarmdur', null);
		$tx_first_event = array_search_recursive($tx_duration . ' Weeks', $arms) !== false ? array_search_recursive($tx_duration . ' Weeks', $arms) : null;
		$survey_event_ids = isset($tx_first_event) ? array_merge(array($baseline_event_id), $Proj->getEventsByArmNum($arms[$tx_first_event]['arm_num'])) : array($baseline_event_id);
		foreach ($survey_event_ids AS $survey_event_id) {
			$survey_event_name = $Proj->getUniqueEventNames($survey_event_id);
			$survey_prefix = substr($survey_event_name, 0, strpos($survey_event_name, '_'));
			$fields[] = $survey_prefix . '_completed';
			$fields[] = $survey_prefix . '_date';
			$fields[] = $survey_prefix . '_startdate';
			$fields[] = $survey_prefix . '_deadline';
		}
		$data = REDCap::getData('array', $subject_id, $fields, $baseline_event_id);
		foreach ($survey_event_ids AS $survey_event_id) {
			$data_event_name = $Proj->getUniqueEventNames($survey_event_id);
			$prefix = substr($data_event_name, 0, strpos($data_event_name, '_'));
			$is_t_complete = is_t_complete($subject_id, $survey_event_id);
			$t_complete = $is_t_complete ? '1' : '0';
			foreach ($data[$subject_id] AS $data_event_id => $data_event) {
				foreach ($data_event AS $key => $value) {
					/**
					 * derive intra-event timing variables
					 */
					switch ($key) {
						case $prefix . '_completed':
							update_field_compare($subject_id, $project_id, $data_event_id, $t_complete, $value, $key, $debug);
							break;
						case $prefix . '_date':
							if ($value == '' && $is_t_complete) {
								update_field_compare($subject_id, $project_id, $data_event_id, $today, $value, $key, $debug);
							}
							break;
						default:
							break;
					}
				}
			}
			/**
			 * derive inter-event timing variables
			 */
			$complete_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_completed', null);
			$start_date_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_startdate', null);
			$deadline_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_deadline', null);
			$missed_value = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_missed', null);
			$t_missed = $complete_value == '0' && $today > $deadline_value && isset($deadline_value) && $deadline_value != '' ? '1' : '0';
			switch ($prefix) {
				case 't1':
					$t_base_date = get_single_field($subject_id, $project_id, $baseline_event_id, $prefix . '_date', null);
					$t_start_date = $t_base_date;
					$t_deadline_date = add_date($t_base_date, 89);
					break;
				default:
					$t_base_date = get_single_field($subject_id, $project_id, $enrollment_event_id, 'dm_rfstdtc', null);
					$t_start_date = add_date($t_base_date, ($arms[$data_event_name]['day_offset'] - $arms[$data_event_name]['offset_min']));
					$t_deadline_date = add_date($t_base_date, ($arms[$data_event_name]['day_offset'] + $arms[$data_event_name]['offset_max']) - 1);
					break;
			}
			update_field_compare($subject_id, $project_id, $baseline_event_id, $t_complete, $complete_value, $prefix . '_completed', $debug);
			update_field_compare($subject_id, $project_id, $baseline_event_id, $t_missed, $missed_value, $prefix . '_missed', $debug);
			if (isset($t_base_date) && $t_base_date != '') {
				update_field_compare($subject_id, $project_id, $baseline_event_id, $t_start_date, $start_date_value, $prefix . '_startdate', $debug);
				update_field_compare($subject_id, $project_id, $baseline_event_id, $t_deadline_date, $deadline_value, $prefix . '_deadline', $debug);
			}
		}
	}
}
require_once $base_path . '/plugins/includes/functions.php';
require_once APP_PATH_DOCROOT . '/Config/init_project.php';
require_once APP_PATH_DOCROOT . '/ProjectGeneral/header.php';
/**
 * if data was submitted here...
 */
if ($_GET && $_POST) {
    if ($debug) {
        show_var($_GET, 'GET');
        show_var($_POST, 'POST');
    }
    /**
     * initialize variables
     */
    $project = new Project();
    $next_event_id = getNextEventId($_GET['event_id'], $_GET['page']);
    $original_action = APP_PATH_WEBROOT . "DataEntry/index.php?pid={$_GET['pid']}&event_id={$_GET['event_id']}&page={$_GET['page']}";
    $redirect_url = APP_PATH_WEBROOT . "DataEntry/index.php?pid={$_GET['pid']}&event_id={$next_event_id}&page={$_GET['page']}";
    /**
     * conditionally modify post and redirect
     */
    //	if ($_POST['submit-action'] == 'submit-btn-savenextevent' && $next_event_id !== false) {
    //		$_POST['save-and-redirect'] = $redirect_url;
    //	}
    //	header('Location: ' . $original_action);
    /**
     * construct and render proxy form
     */
    $form_contents = '';
    foreach ($_POST as $field => $value) {
        $form_contents .= RCView::input(array('type' => 'hidden', 'name' => $field, 'value' => $value));
        error_log("ERROR: hook_terms array in " . __FILE__ . " not loaded.");
    }
}
/**
 * set up autocomplete
 */
$file = $base_path . '/hooks/resources/autocomplete.php';
if (file_exists($file)) {
    require_once $file;
} else {
    error_log("ERROR: {$file} in " . __FILE__ . " not loaded.");
}
/**
 * Save and go to Next Event for this Form button
 */
$next_event_id = getNextEventId($event_id, $instrument);
// get the next event_id
if ($Proj->validateFormEvent($instrument, $next_event_id)) {
    // if it's a valid event_id
    /**
     * inject new input button
     */
    $redirect_url = APP_PATH_WEBROOT . "DataEntry/index.php?pid={$project_id}&id={$record}&event_id={$next_event_id}&page={$instrument}";
    ?>
	<script src="<?php 
    echo '/hooks/resources/js/functions.js';
    ?>
"></script>
	<script type="text/javascript">
		var redirectURL = "<?php 
    echo $redirect_url;