/**
 * restricted use
 */
$allowed_pids = array('38');
REDCap::allowProjects($allowed_pids);
/**
 * do stuff
 */
if ($debug) {
    if (!is_form_locked($record, $instrument, $redcap_event_name)) {
        d(is_t_complete($record, $event_id), $redcap_event_name);
    }
    global $Proj, $project_id;
    $today = date("Y-m-d");
    $fields = array();
    $arms = get_arms(array_keys($Proj->eventsForms));
    d($arms);
    $baseline_event_id = $Proj->firstEventId;
    $tx_duration = get_single_field($record, $project_id, $baseline_event_id, 'trt_exdur', null);
    $tx_duration = substr($tx_duration, strpos($tx_duration, 'P') + 1, strlen($tx_duration) - 2);
    $tx_first_event = array_search_recursive($tx_duration . ' Weeks', $arms) !== false ? array_search_recursive($tx_duration . ' Weeks', $arms) : null;
    $survey_event_ids = $Proj->getEventsByArmNum($arms[$tx_first_event]['arm_num']);
    d($survey_event_ids);
    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';
        $fields[] = $survey_prefix . '_missed';
/**
 * @param $record
 * @param $debug
 * determine completeness of all survey-containing events
 */
function set_survey_completion($record, $debug)
{
	if (isset($record)) {
		global $Proj, $project_id;
		$today = date("Y-m-d");
		$fields = array();
		$arms = get_arms(array_keys($Proj->eventsForms));
		$baseline_event_id = $Proj->firstEventId;
		$trt = Treatment::getTrtInfo($record);
		/**
		 * use the selected duration ($trt['arm']) to set timings
		 */
		$tx_first_event = array_search_recursive($trt['arm'], $arms) !== false ? array_search_recursive($trt['arm'], $arms) : null;
		$survey_event_ids = isset($tx_first_event) ? $Proj->getEventsByArmNum($arms[$tx_first_event]['arm_num']) : null;
		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, '_'));
			/**
			 * derive inter-event timing variables
			 */
			$start_date_value = get_single_field($record, $project_id, $baseline_event_id, $prefix . '_startdate', null);
			$deadline_value = get_single_field($record, $project_id, $baseline_event_id, $prefix . '_deadline', null);
			/**
			 * for baseline surveys, reference date is randomization date. For all other survey events,
			 * reference date is dm_rfxstdtc, recorded treatment start date NOT dm_rfstdtc, the
			 * treatment start derived from the treatment med data
			 */
			$t_base_date = in_array($prefix, array('baseline', 'eot1year', 'eot3year')) ? $trt['rand_date'] : $trt['rfxstdtc'];
			if (isset($t_base_date) && $t_base_date != '') {
				$t_start_date = add_date($t_base_date, ($arms[$data_event_name]['day_offset'] - $arms[$data_event_name]['offset_min']));
				update_field_compare($record, $project_id, $baseline_event_id, $t_start_date, $start_date_value, $prefix . '_startdate', $debug);
				$t_deadline_date = add_date($t_base_date, ($arms[$data_event_name]['day_offset'] + $arms[$data_event_name]['offset_max']) - 1);
				update_field_compare($record, $project_id, $baseline_event_id, $t_deadline_date, $deadline_value, $prefix . '_deadline', $debug);
			}
		}
		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', $record, $fields, $baseline_event_id);
		/**
		 * switch to the scheduled arm to determine completion
		 * this is done to avoid subjects switching arms and orphaning surveys completed
		 * prior to duration change. This should (almost) never happen, but we still need to handle if it does
		 */
		$tx_first_event = array_search_recursive($trt['timing_arm'], $arms) !== false ? array_search_recursive($trt['timing_arm'], $arms) : null;
		$survey_event_ids = isset($tx_first_event) ? $Proj->getEventsByArmNum($arms[$tx_first_event]['arm_num']) : null;
		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($record, $survey_event_id);
			$t_complete = $is_t_complete ? '1' : '0';
			$complete_value = get_single_field($record, $project_id, $baseline_event_id, $prefix . '_completed', null);
			$deadline_value = get_single_field($record, $project_id, $baseline_event_id, $prefix . '_deadline', null);
			$t_missed = $complete_value == '0' && $today > $deadline_value && isset($deadline_value) && $deadline_value != '' ? '1' : '0';
			foreach ($data[$record] AS $data_event_id => $data_event) {
				foreach ($data_event AS $key => $value) {
					/**
					 * derive completion variables
					 */
					switch ($key) {
						case $prefix . '_completed':
							update_field_compare($record, $project_id, $data_event_id, $t_complete, $value, $key, $debug);
							break;
						case $prefix . '_date':
							if ($value == '' && $is_t_complete) {
								update_field_compare($record, $project_id, $data_event_id, $today, $value, $key, $debug);
							}
							break;
						case $prefix . '_missed':
							update_field_compare($record, $project_id, $data_event_id, $t_missed, $value, $key, $debug);
							break;
						default:
							break;
					}
				}
			}
		}
	}
}
/**
 * @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);
			}
		}
	}
}