<?php
$rsvp_options                 = '';
$rsvp_sub_options             = array();
$event_information            = array();
$admin_strings                = array();
$us_admin_strings             = array();
$rsvp_pro_frontend_strings    = array();
$us_rsvp_pro_frontend_strings = array();
$rsvp_pro_inline_attachments  = array();
$payment_gateways             = array();

if ( ( isset( $_GET['page'] ) && ( strToLower( $_GET['page'] ) == 'rsvp-pro-top-level' ) && isset( $_GET['action'] ) && ( strToLower( $_GET['action'] ) == 'export' ) ) ){
	add_action( 'init', 'rsvp_pro_admin_export', 20 );
}

if ( isset( $_GET['page'] ) && ( strtolower( $_GET['page'] ) === 'rsvp-pro-export-events' )
	 && isset( $_POST['action'] ) && ( strtolower( $_POST['action'] ) == 'do_event_export' ) ){
	add_action( 'init', 'rsvp_pro_admin_event_export', 20 );
}

if ( isset( $_GET['page'] ) && ( 'rsvp-pro-export-change-log' === strToLower( $_GET['page'] ) ) ){
	add_action( 'init', 'rsvp_pro_admin_export_change_log', 20 );
}

/**
 * Checks to see if there is an update for the plugin or not.
 */
function rsvp_pro_plugin_updater(){
	// retrieve our license key from the DB.
	$license_key = trim( rsvp_pro_get_option_license( 'rsvp_pro_license_key' ) );

	// Setup the updater.
	$rsvp_updater = new RSVP_PRO_SL_Plugin_Updater(
			RSVP_PRO_STORE_URL,
			RSVP_PRO_PLUGIN_FILE,
			array(
					'version'   => '4.4.22',        // current version number.
					'license'   => $license_key,    // license key (used get_option above to retrieve from DB).
					'item_name' => RSVP_PRO_ITEM_NAME,  // name of this plugin.
					'author'    => 'WPChill',  // author of this plugin.
			)
	);
}

add_action( 'admin_init', 'rsvp_pro_plugin_updater', 0 );

/**
 * Handles all of the RSVP Pro admin actions. This is the main driver for the admin area of the plugin.
 */
function rsvp_pro_admin_events(){
	global $wpdb;
	if ( ( wp_next_scheduled( 'rsvp_pro_reoccurring_events' ) === false ) ||
		 ( wp_next_scheduled( 'rsvp_pro_reminder_notifications' ) === false ) ||
		 ( wp_next_scheduled( 'rsvp_pro_attendee_list_notifications' ) === false ) ){
		rsvp_pro_scheduler();
	}

	$action = '';
	if ( isset( $_REQUEST['action'] ) && !empty( $_REQUEST['action'] ) ){
		$action = $_REQUEST['action'];
	}

	$table = $wpdb->prefix . 'rsvpEvents';
	if ( strcasecmp( $wpdb->get_var( "SHOW TABLES LIKE '$table'" ), $table ) != 0 ){
		update_option( 'rsvp_pro_db_version', 0 );
		rsvp_pro_database_setup();
	}

	if ( !isset( $_GET['eventID'] ) || !is_numeric( $_GET['eventID'] ) ||
		 ( ( $_GET['eventID'] <= 0 ) && ( $_GET['eventID'] != RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) ) ){
		$action = '';
	} else {
		$event_id = $_GET['eventID'];
	}

	if ( isset( $_POST['rsvp-bulk-action'] ) && ( $_POST['rsvp-bulk-action'] == 'mass_email' ) ){
		$action = 'mass_email';
	}

	if ( 'delete' === $action ){
		rsvp_pro_admin_delete_event( $event_id );
	} elseif ( 'attendees' === $action ) {
		if ( isset( $_POST['rsvp-bulk-action'] ) && ( 'export_show_form' === $_POST['rsvp-bulk-action'] ) ){
			rsvp_pro_admin_export_attendees_form( $event_id );
		} else {
			rsvp_pro_admin_guestlist( $event_id );
		}
	} elseif ( ( $action === 'modify_attendee' ) && isset( $_GET['eventID'] ) && ( ( $_GET['eventID'] > 0 ) || ( $_GET['eventID'] == RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) ) ) {
		rsvp_pro_admin_guest( $event_id );
	} elseif ( ( 'reset_attendee' === $action ) && isset( $_GET['eventID'] ) && ( $_GET['eventID'] > 0 ) ) {
		rsvp_pro_admin_reset_guest( $_GET['eventID'] );
	} elseif ( 'import' === $action ) {
		rsvp_pro_admin_import( $_GET['eventID'] );
	} elseif ( 'custom_questions' === $action ) {
		rsvp_pro_admin_questions( $_GET['eventID'] );
	} elseif ( 'modify_custom_question' === $action ) {
		rsvp_pro_admin_custom_question( $_GET['eventID'] );
	} elseif ( 'import_from_free' === $action ) {
		rsvp_pro_admin_import_from_free( $_GET['eventID'] );
	} elseif ( 'mass_email' === $action ) {
		rsvp_pro_admin_mass_email( $_GET['eventID'] );
	} elseif ( 'copy' === $action ) {
		rsvp_pro_admin_copy_event( $_GET['eventID'] );
	} elseif ( 'all_attendees' === $action ) {
		if ( isset( $_POST['rsvp-bulk-action'] ) && ( 'export_show_form' === $_POST['rsvp-bulk-action'] ) ){
			rsvp_pro_admin_export_attendees_form( $event_id );
		} else {
			rsvp_pro_admin_guestlist( $_GET['eventID'], true );
		}
	} elseif ( 'reminders' === $action ) {
		rsvp_pro_admin_reminders( $event_id );
	} elseif ( 'reminder-form' === $action ) {
		rsvp_pro_admin_reminder_form( $_GET['eventID'] );
	} elseif ( 'save_reminder' === $action ) {
		rsvp_pro_admin_reminder_save( $_GET['eventID'] );
	} elseif ( 'confirm_reset_all_attendees' === $action ) {
		rsvp_pro_admin_confirm_reset_all_attendees( $_GET['eventID'] );
	} elseif ( 'reset_all_attendees' === $action ) {
		rsvp_pro_admin_reset_all_guests( $_GET['eventID'] );
	} elseif ( 'delete_reminders' === $action ) {
		rsvp_pro_admin_reminder_delete( $_GET['eventID'] );
	} elseif ( 'change_log' === $action ) {
		rsvp_pro_admin_show_change_log( $event_id );
	} elseif ( 'export_attendee_form' === $action ) {
		rsvp_pro_admin_export_attendees_form( $event_id );
	} elseif ( 'message_logs' === $action ) {
		rsvp_pro_admin_message_logs( $event_id );
	} elseif ( 'delete_message_logs' === $action ) {
		rsvp_pro_admin_delete_message_logs();
		rsvp_pro_admin_message_logs( $event_id );
	} elseif ( 'view_message_log' === $action ) {
		rsvp_pro_admin_view_message_log( $event_id );
	} elseif ( 'send_attendee_list' === $action ) {
		rsvp_pro_send_attendee_list_notifications( $event_id, false );
		rsvp_pro_admin_eventList();
	} else {
		rsvp_pro_admin_eventList();
	}
}

/**
 * Sets the passcode for attendees if they are not set.
 *
 * @param int $event_id The Event ID that we want to update the passcodes for.
 */
function rsvp_pro_set_passcode( $event_id ){
	global $wpdb;

	rsvp_pro_install_passcode_field();
	$length = 6;

	if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_PASSWORD_LENGTH ) > 0 ){
		$length = rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_PASSWORD_LENGTH );
	}

	$sql       = 'SELECT id, passcode FROM ' . PRO_ATTENDEES_TABLE . ' WHERE passcode = \'\' AND rsvpEventID = %d';
	$attendees = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
	foreach ( $attendees as $a ){
		$wpdb->update(
				PRO_ATTENDEES_TABLE,
				array( 'passcode' => rsvp_pro_generate_passcode( $length ) ),
				array( 'id' => $a->id ),
				array( '%s' ),
				array( '%d' )
		);
	}
}

/**
 * Deletes an event.
 *
 * @param int $event_id The event ID we want to delete.
 */
function rsvp_pro_admin_delete_event( $event_id ){
	global $wpdb;

	$sql    = 'SELECT eventName FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
	$events = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
	if ( count( $events ) <= 0 ){
		rsvp_pro_admin_eventList();

		return;
	}

	if ( !rsvp_pro_admin_user_has_access_to_settings( $event_id ) ){
		rsvp_pro_admin_eventList();

		return;
	}

	if ( ( count( $_POST ) > 0 ) && ( wp_verify_nonce( $_POST['_wpnonce'], 'rsvp_delete_event' ) !== false ) ){
		check_admin_referer( 'rsvp_delete_event' );
		rsvp_pro_delete_event( $event_id );
		?>
		<div id="message" class="updated">
			<p class="updated"><?php echo rsvp_pro_get_admin_string( 'event_deleted' ); ?></p>
		</div>
		<?php
		rsvp_pro_admin_eventList();
	} else {
		?>
		<div class="wrap">
			<form name="deleteEvent" method="post">
				<?php wp_nonce_field( 'rsvp_delete_event' ); ?>
				<p><?php echo rsvp_pro_get_admin_string( 'delete_question' ); ?> <?php echo $events[0]->eventName; ?>
					?</p>
				<p class="submit">
					<input type="submit" class="button-primary" value="<?php esc_attr_e( 'Delete','rsvp-pro-plugin' ); ?>"/>
				</p>
			</form>
		</div>
		<?php
	}
}

/**
 * Shows the manage events form.
 */
function rsvp_pro_admin_manage_event(){
	global $wpdb;
	if ( isset( $_GET['id'] ) && !rsvp_pro_admin_user_has_access_to_settings( $_GET['id'] ) ){
		rsvp_pro_admin_eventList();

		return;
	}

	require_once 'admin/manage-event-form.inc.php';
}

/**
 * Handles the deletion of an event and related information.
 *
 * @param int $eventID The event ID we want to delete.
 */
function rsvp_pro_delete_event( $eventID ){
	global $wpdb;

	if ( is_numeric( $eventID ) && ( $eventID > 0 ) ){
		$wpdb->query(
				$wpdb->prepare(
						'DELETE ca.* FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' ca
										INNER JOIN ' . PRO_QUESTIONS_TABLE . ' cq ON cq.id = ca.questionID
										WHERE cq.rsvpEventID = %d',
						$eventID
				)
		);

		$wpdb->query(
				$wpdb->prepare(
						'DELETE ca.* FROM ' . PRO_QUESTION_ATTENDEES_TABLE . ' ca
										INNER JOIN ' . PRO_QUESTIONS_TABLE . ' cq ON cq.id = ca.questionID
										WHERE cq.rsvpEventID = %d',
						$eventID
				)
		);

		$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_QUESTIONS_TABLE . ' WHERE rsvpEventID = %d', $eventID ) );
		rsvp_pro_delete_attendee_from_event( $eventID );

		$wpdb->delete( PRO_EVENT_ATTENDEE_TABLE, array( 'rsvpEventID' => $eventID ) );

		$wpdb->delete( PRO_EVENT_ATTENDEE_TABLE, array( 'rsvpEventID' => $eventID ) );

		$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_MESSAGE_LOG_ATTENDEES . ' WHERE message_id IN ( SELECT id FROM ' . PRO_MESSAGE_LOG . ' WHERE rsvpEventID = %d )', $eventID ) );
		$wpdb->delete( PRO_MESSAGE_LOG, array( 'rsvpEventID' => $eventID ) );

		$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d', $eventID ) );

		$wpdb->query( $wpdb->prepare( 'UPDATE ' . PRO_EVENT_TABLE . ' SET parentEventID = 0 WHERE parentEventID = %d', $eventID ) );
	}
}

/**
 * Deletes all the attendees for a given event.
 *
 * @param int $event_id The event ID we want to delete.
 *
 * @since 2.4.2
 *
 */
function rsvp_pro_delete_attendee_from_event( $event_id ){
	global $wpdb;

	$wpdb->query(
			$wpdb->prepare(
					'DELETE aa.* FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . ' aa
		INNER JOIN ' . PRO_ATTENDEES_TABLE . ' a ON a.id = aa.attendeeID
		WHERE a.rsvpEventID = %d',
					$event_id
			)
	);

	$wpdb->query(
			$wpdb->prepare(
					'DELETE aa.* FROM ' . PRO_ATTENDEE_ANSWERS . ' aa
		 INNER JOIN ' . PRO_ATTENDEES_TABLE . ' a ON a.id = aa.attendeeID
		 WHERE a.rsvpEventID = %d',
					$event_id
			)
	);

	$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' WHERE rsvpEventID = %d', $event_id ) );

	$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_ATTENDEES_TABLE . ' WHERE rsvpEventID = %d', $event_id ) );
}


/**
 * Returns the possible fields someone can search on in the attendee list
 *
 * @param int $event_id The current event ID that we need get to the fields for
 *
 * @return array          A key/value pair for fields the key is the computer name and the value is the user-friendly
 *                        name
 */
function rsvp_pro_admin_get_search_fields( $event_id ){
	global $wpdb;

	$fields = array();

	// Populate the normal attendee fields
	$fields['firstName']  = rsvp_pro_get_frontend_string( 'first_name_label' );
	$fields['lastName']   = rsvp_pro_get_frontend_string( 'last_name_label' );
	$fields['rsvpStatus'] = rsvp_pro_get_frontend_string( 'rsvp_status_label' );
	$fields['note']       = rsvp_pro_get_frontend_string( 'note_label' );
	$fields['email']      = rsvp_pro_get_frontend_string( 'email_label' );
	$fields['suffix']     = rsvp_pro_get_frontend_string( 'suffix_label' );
	$fields['salutation'] = rsvp_pro_get_frontend_string( 'salutation_text' );
	$fields['nicknames']  = rsvp_pro_get_admin_string( 'nicknames_label' );

	// Populate the custom questions for this event
	$sql       = 'SELECT id, question FROM ' . PRO_QUESTIONS_TABLE . ' WHERE rsvpEventID = %d';
	$questions = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
	foreach ( $questions as $q ){
		$tmp_question = rsvp_pro_admin_prepare_custom_question_for_display( $q->question );

		$fields[ 'cq_' . $q->id ] = $tmp_question;
	}

	asort( $fields );

	return $fields;
}

/**
 * This takes the question from its raw state straight out of the database and prepares
 * it to be displayed in the admin area. That means removing slashes and truncating the text
 * if it is too long.
 *
 * @param String $raw_question The raw custom question that comes from the database.
 *
 * @return String               The prepared string.
 */
function rsvp_pro_admin_prepare_custom_question_for_display( $raw_question ){
	$question = strip_tags( stripslashes( $raw_question ) );

	if ( strlen( $question ) > 50 ){
		$question = substr( $question, 0, 50 ) . '...';
	}

	return $question;
}

function rsvp_pro_admin_message_variables( $eventID, $additionalTrCssClasses = '', $labelText = '' ){
	global $wpdb;
	?>
	<tr class="<?php echo $additionalTrCssClasses; ?>">
		<th scope="row">
			<?php
			if ( !empty( $labelText ) ){
				echo $labelText;
			} else {
				echo rsvp_pro_get_admin_string( 'available_placeholders_label' );
			}
			?>
		</th>
		<td>
			[[Salutation]]<br/>
			[[Suffix]]<br/>
			[[FirstName]]<br/>
			[[LastName]]<br/>
			[[Email]]<br/>
			[[RsvpStatus]]<br / />
			[[Passcode]]<br/>
			[[PrefillUrl]]<br/>
			[[EventUrl]]<br/>
			[[EventName]]<br/>
			[[EventStartDate]]<br/>
			[[EventEndData]]<br/>
			[[EventLocation]]<br/>
			[[EventDescription]]<br/>
			[[Attendee_Rsvp_Full_Info]]<br/>
			[[Note]]<br/>
			[[QR]] - <?php echo rsvp_pro_get_admin_string( 'qr_code_label' ); ?><br/>
			[[QR_PrefillUrl]] - <?php echo rsvp_pro_get_admin_string( 'qr_prefill_code_label' ); ?><br/>
			[[SubEvents]]...[[/SubEvents]] - <?php echo rsvp_pro_get_admin_string( 'individual_tags_label' ); ?><br/>
			[[AssociatedAttendees]]...[[/AssociatedAttendees]]
			- <?php echo rsvp_pro_get_admin_string( 'individual_tags_label' ); ?><br/>
			<?php
			$sql       = 'SELECT q.id, question FROM ' . PRO_QUESTIONS_TABLE . ' q
					JOIN ' . PRO_QUESTION_TYPE_TABLE . ' qt ON qt.id = q.questionTypeID
					WHERE q.rsvpEventID = %d OR q.rsvpEventID IN ( SELECT id FROM ' . PRO_EVENT_TABLE . ' WHERE parentEventID = %d )';
			$questions = $wpdb->get_results( $wpdb->prepare( $sql, $eventID, $eventID ) );
			foreach ( $questions as $q ){
				?>
				[[CustomQ_<?php echo $q->id; ?>]], [[CustomQuestion_<?php echo $q->id; ?>]], [[CustomQAnswer_<?php echo $q->id; ?>]] - <?php echo esc_html( stripslashes( $q->question ) ); ?>?
				<br/>
				<?php
			}
			?>
		</td>
	</tr>
	<?php
}

function rsvp_pro_admin_handle_copy_event( $eventID, $newEventName, $copyOverAttendees = false, $copySubEvents = false ){
	global $wpdb;

	$sql         = 'SELECT close_date, eventName, event_access, open_date,
		options, parentEventID, eventStartDate, eventEndDate, eventLocation,
		eventDescription, repeatStartDate, repeatEndDate, repeatFrequencyType,
		repeatFrequency, eventLength, eventLengthType, currentRepeatEndDate,
		open_date_timezone, open_date_time, close_date_time, attendee_list_sent_on,
		send_attendee_list, attendee_columns, eventStartDateTimezone, eventEndDateTimezone 
		FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
	$eventToCopy = $wpdb->get_row( $wpdb->prepare( $sql, $eventID ) );

	if ( $eventToCopy ){
		$wpdb->insert(
				PRO_EVENT_TABLE,
				array(
						'close_date'             => $eventToCopy->close_date,
						'open_date'              => $eventToCopy->open_date,
						'eventName'              => $newEventName,
						'event_access'           => $eventToCopy->event_access,
						'options'                => $eventToCopy->options,
						'eventStartDate'         => $eventToCopy->eventStartDate,
						'eventEndDate'           => $eventToCopy->eventEndDate,
						'eventLocation'          => stripslashes_deep( $eventToCopy->eventLocation ),
						'eventDescription'       => $eventToCopy->eventDescription,
						'repeatStartDate'        => $eventToCopy->repeatStartDate,
						'repeatEndDate'          => $eventToCopy->repeatEndDate,
						'repeatFrequencyType'    => $eventToCopy->repeatFrequencyType,
						'repeatFrequency'        => $eventToCopy->repeatFrequency,
						'eventLengthType'        => $eventToCopy->eventLengthType,
						'eventLength'            => $eventToCopy->eventLength,
						'currentRepeatEndDate'   => $eventToCopy->currentRepeatEndDate,
						'open_date_time'         => $eventToCopy->open_date_time,
						'close_date_time'        => $eventToCopy->close_date_time,
						'send_attendee_list'     => $eventToCopy->send_attendee_list,
						'attendee_columns'       => stripslashes_deep( $eventToCopy->attendee_columns ),
						'eventStartDateTimezone' => $eventToCopy->eventStartDateTimezone,
						'eventEndDateTimezone'   => $eventToCopy->eventEndDateTimezone,
				),
				array(
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%d',
						'%s',
						'%d',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
						'%s',
				)
		);

		$new_attendee_columns = array_filter( explode( ',', stripslashes( $eventToCopy->attendee_columns ) ) );
		$newEventId           = $wpdb->insert_id;

		if ( $newEventId > 0 ){
			$oldQuestionIdToNewId = array();
			// Copy over the custom questions...
			$sql       = 'SELECT id, `grouping`, permissionLevel, question, questionTypeID,
											 required, sortOrder, only_show_on_status, 
                                             ask_only_associated, required_text
								FROM ' . PRO_QUESTIONS_TABLE . ' WHERE rsvpEventID = %d';
			$questions = $wpdb->get_results( $wpdb->prepare( $sql, $eventID ) );
			if ( $questions ){
				foreach ( $questions as $q ){
					$wpdb->insert(
							PRO_QUESTIONS_TABLE,
							array(
									'grouping'            => $q->grouping,
									'permissionLevel'     => $q->permissionLevel,
									'question'            => stripslashes( $q->question ),
									'questionTypeID'      => $q->questionTypeID,
									'required'            => $q->required,
									'sortOrder'           => $q->sortOrder,
									'rsvpEventID'         => $newEventId,
									'only_show_on_status' => $q->only_show_on_status,
									'ask_only_associated' => $q->ask_only_associated,
									'required_text'       => $q->required_text,
							),
							array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' )
					);
					$newQuestionId                  = $wpdb->insert_id;
					$oldQuestionIdToNewId[ $q->id ] = $newQuestionId;

					$sql     = 'SELECT answer, defaultAnswer FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d';
					$answers = $wpdb->get_results( $wpdb->prepare( $sql, $q->id ) );
					if ( $answers ){
						foreach ( $answers as $a ){
							$wpdb->insert(
									PRO_QUESTION_ANSWERS_TABLE,
									array(
											'questionID'    => $newQuestionId,
											'answer'        => stripslashes( $a->answer ),
											'defaultAnswer' => $a->defaultAnswer,
									),
									array( '%d', '%s', '%s' )
							);
						}
					} // if($answers)...
				} // foreach($questions as...
			} // if($questions

			// Check to see if the new event has a custom question list for
			// the public attendee list and if so update to the new IDs
			$options                 = new Rsvp_Pro_Event_Options( $newEventId );
			$attendee_list_custom_qs = $options->get_attendeelist_custom_qs();
			if ( count( $attendee_list_custom_qs ) > 0 ){
				$new_attendeelist_custom_qs = array();
				foreach ( $oldQuestionIdToNewId as $old_qid => $new_qid ){
					if ( in_array( $old_qid, $attendee_list_custom_qs ) ){
						$new_attendeelist_custom_qs[] = $new_qid;
					}
				}

				$options->set_attendeelist_custom_qs( $new_attendeelist_custom_qs );
				$options->save_options();
			}

			// Update email templates for custom questions.
			$email_body           = $options->get_email_body();
			$attendee_list_format = $options->get_send_attendee_list_format();
			$export_columns       = $options->get_export_columns();
			foreach ( $oldQuestionIdToNewId as $old_qid => $new_qid ){
				// [[CustomQ_1]], [[CustomQuestion_1]], [[CustomQAnswer_1]]
				$email_body = str_ireplace(
						'[[CustomQ_' . $old_qid . ']]',
						'[[CustomQ_' . $new_qid . ']]',
						$email_body
				);
				$email_body = str_ireplace(
						'[[CustomQuestion_' . $old_qid . ']]',
						'[[CustomQuestion_' . $new_qid . ']]',
						$email_body
				);
				$email_body = str_ireplace(
						'[[CustomQAnswer_' . $old_qid . ']]',
						'[[CustomQAnswer_' . $new_qid . ']]',
						$email_body
				);

				$attendee_list_format = str_ireplace(
						'[[CustomQ_' . $old_qid . ']]',
						'[[CustomQ_' . $new_qid . ']]',
						$attendee_list_format
				);
				$attendee_list_format = str_ireplace(
						'[[CustomQuestion_' . $old_qid . ']]',
						'[[CustomQuestion_' . $new_qid . ']]',
						$attendee_list_format
				);
				$attendee_list_format = str_ireplace(
						'[[CustomQAnswer_' . $old_qid . ']]',
						'[[CustomQAnswer_' . $new_qid . ']]',
						$attendee_list_format
				);

				foreach ( $export_columns as $col ){
					if ( $col === 'export_custom_question_' . $old_qid ){
						$export_columns[ 'export_custom_question_' . $old_qid ] = 'export_custom_question_' . $new_qid;
					}
				}
			}
			$options->set_email_body( $email_body );
			$options->set_send_attendee_list_format( $attendee_list_format );
			$options->set_export_columns( $export_columns );
			$options->save_options();

			// Check to see if the new event has attendee list columns selected that are custom
			// questions that we need to replace with the new IDs
			foreach ( $oldQuestionIdToNewId as $old_qid => $new_qid ){
				if ( in_array( 'custom_question_' . $old_qid, $new_attendee_columns ) ){
					$new_attendee_columns[] = 'custom_question_' . $new_qid;
				}
			}

			// Save the attendee list to the table
			$wpdb->update(
					PRO_EVENT_TABLE,
					array(
							'attendee_columns' => implode( ',', $new_attendee_columns ),
					),
					array( 'id' => $newEventId ),
					array( '%s' ),
					array( '%d' )
			);

			if ( $copySubEvents ){
				$sql       = 'SELECT id, close_date, eventName, event_access, open_date, options, parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE parentEventID = %d';
				$subEvents = $wpdb->get_results( $wpdb->prepare( $sql, $eventID ) );
				foreach ( $subEvents as $se ){
					$wpdb->insert(
							PRO_EVENT_TABLE,
							array(
									'close_date'    => $se->close_date,
									'open_date'     => $se->open_date,
									'eventName'     => stripslashes( $se->eventName ) . ' - copy',
									'event_access'  => $se->event_access,
									'options'       => $se->options,
									'parentEventID' => $newEventId,
							),
							array( '%s', '%s', '%s', '%s', '%s', '%d' )
					);
					$subEventId = $wpdb->insert_id;
					if ( $subEventId > 0 ){
						// Copy over the custom questions...
						$sql       = 'SELECT id, `grouping`, permissionLevel, question, questionTypeID,
														 required, sortOrder
											FROM ' . PRO_QUESTIONS_TABLE . ' WHERE rsvpEventID = %d';
						$questions = $wpdb->get_results( $wpdb->prepare( $sql, $se->id ) );
						if ( $questions ){
							foreach ( $questions as $q ){
								$wpdb->insert(
										PRO_QUESTIONS_TABLE,
										array(
												'grouping'        => $q->grouping,
												'permissionLevel' => $q->permissionLevel,
												'question'        => stripslashes( $q->question ),
												'questionTypeID'  => $q->questionTypeID,
												'required'        => $q->required,
												'sortOrder'       => $q->sortOrder,
												'rsvpEventID'     => $subEventId,
										),
										array( '%s', '%s', '%s', '%s', '%s', '%s', '%d' )
								);
								$newQuestionId                  = $wpdb->insert_id;
								$oldQuestionIdToNewId[ $q->id ] = $newQuestionId;

								$sql     = 'SELECT answer, defaultAnswer FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d';
								$answers = $wpdb->get_results( $wpdb->prepare( $sql, $q->id ) );
								if ( $answers ){
									foreach ( $answers as $a ){
										$wpdb->insert(
												PRO_QUESTION_ANSWERS_TABLE,
												array(
														'questionID'    => $newQuestionId,
														'answer'        => stripslashes( $a->answer ),
														'defaultAnswer' => $a->defaultAnswer,
												),
												array( '%d', '%s', '%s' )
										);
									}
								} // if($answers)...
							} // foreach($questions as...
						} // if($questions
					}
				}
			}

			if ( $copyOverAttendees ){
				$oldAttendeeIdToNewId = array();
				$sql                  = 'SELECT id, firstName, lastName, note, additionalAttendee, ' .
										'personalGreeting, rsvpEventID, passcode, email, numGuests, suffix, ' .
										'salutation, nicknames, primaryAttendee ' .
										'FROM ' . PRO_ATTENDEES_TABLE . ' WHERE rsvpEventID = %d';
				$attendees            = $wpdb->get_results( $wpdb->prepare( $sql, $eventID ) );

				// Copy over attendee
				foreach ( $attendees as $a ){
					$wpdb->insert(
							PRO_ATTENDEES_TABLE,
							array(
									'rsvpEventID'        => $newEventId,
									'firstName'          => stripslashes( $a->firstName ),
									'lastName'           => stripslashes( $a->lastName ),
									'note'               => stripslashes( $a->note ),
									'additionalAttendee' => stripslashes( $a->additionalAttendee ),
									'personalGreeting'   => stripslashes( $a->personalGreeting ),
									'passcode'           => stripslashes( $a->passcode ),
									'email'              => stripslashes( $a->email ),
									'numGuests'          => ( ( $a->numGuests >= 0 ) ? $a->numGuests : null ),
									'suffix'             => stripslashes( $a->suffix ),
									'salutation'         => stripslashes( $a->salutation ),
									'nicknames'          => stripslashes( $a->nicknames ),
									'primaryAttendee'    => stripslashes( $a->primaryAttendee ),
							),
							array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s' )
					);

					$newAttendeeId                  = $wpdb->insert_id;
					$oldAttendeeIdToNewId[ $a->id ] = $newAttendeeId;
				}
				// Copy over associations...
				$sql                 = 'SELECT attendeeID, associatedAttendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE .
									   ' WHERE attendeeID IN (' . implode( ',', array_keys( $oldAttendeeIdToNewId ) ) . ')';
				$associatedAttendees = $wpdb->get_results( $sql );
				foreach ( $associatedAttendees as $aa ){
					if ( isset( $oldAttendeeIdToNewId[ $aa->associatedAttendeeID ] ) ){
						$wpdb->insert(
								PRO_ASSOCIATED_ATTENDEES_TABLE,
								array(
										'attendeeID'           => $oldAttendeeIdToNewId[ $aa->attendeeID ],
										'associatedAttendeeID' => $oldAttendeeIdToNewId[ $aa->associatedAttendeeID ],
								),
								array( '%d', '%d' )
						);
					}
				}

				// Copy over question attendee associations
				if ( count( $oldQuestionIdToNewId ) > 0 ){
					$sql               = 'SELECT questionID, attendeeID FROM ' . PRO_QUESTION_ATTENDEES_TABLE . ' WHERE questionID IN (' . implode( ',', array_keys( $oldQuestionIdToNewId ) ) . ')';
					$questionAttendees = $wpdb->get_results( $sql );
					foreach ( $questionAttendees as $qa ){
						if ( isset( $oldAttendeeIdToNewId[ $qaa->attendeeID ] ) ){
							$wpdb->insert(
									PRO_QUESTION_ATTENDEES_TABLE,
									array(
											'questionID' => $oldQuestionIdToNewId[ $qa->questionID ],
											'attendeeID' => $oldAttendeeIdToNewId[ $qa->attendeeID ],
									),
									array( '%d', '%d' )
							);
						}
					}
				}

				// Copy over custom question answers
				if ( count( $oldQuestionIdToNewId ) > 0 ){
					$sql = 'SELECT questionID, attendeeID, answer FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE questionID IN (' . implode( ',', array_keys( $oldQuestionIdToNewId ) ) . ')';

					$questionAnswerAttendees = $wpdb->get_results( $sql );
					foreach ( $questionAnswerAttendees as $qaa ){
						if ( isset( $oldAttendeeIdToNewId[ $qaa->attendeeID ] ) ){
							$wpdb->insert(
									PRO_ATTENDEE_ANSWERS,
									array(
											'questionID' => $oldQuestionIdToNewId[ $qaa->questionID ],
											'attendeeID' => $oldAttendeeIdToNewId[ $qaa->attendeeID ],
											'answer'     => $qaa->answer,
									),
									array( '%d', '%d', '%s' )
							);
						}
					}
				}

				// Copy over event access association
				$sql       = 'SELECT rsvpEventID, rsvpAttendeeID FROM ' . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = %d';
				$attendees = $wpdb->get_results( $wpdb->prepare( $sql, $eventID ) );
				foreach ( $attendees as $aa ){
					$wpdb->insert(
							PRO_EVENT_ATTENDEE_TABLE,
							array(
									'rsvpEventID'    => $newEventId,
									'rsvpAttendeeID' => $oldAttendeeIdToNewId[ $aa->rsvpAttendeeID ],
							),
							array( '%d', '%d' )
					);
				}
			}
		} // if($newEventId
	}
}

/**
 * Function to handle copying of an event, will display a confirmation prompt first and then copy if the user
 * chooses to proceed.
 */
function rsvp_pro_admin_copy_event( $eventID ){
	global $wpdb;
	if ( isset( $_POST['copyEventSubmit'] ) ){
		check_admin_referer( 'rsvp-copy' );

		$sql         = 'SELECT close_date, eventName, event_access, open_date, options, parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
		$eventToCopy = $wpdb->get_row( $wpdb->prepare( $sql, $eventID ) );

		if ( $eventToCopy ){
			$newEventName      = stripslashes( $eventToCopy->eventName ) . ' - ' . rsvp_pro_get_admin_string( 'copy_text' );
			$copyOverAttendees = false;
			if ( isset( $_POST['copyOverAttendees'] ) && ( $_POST['copyOverAttendees'] == 'Y' ) ){
				$copyOverAttendees = true;
			}
			rsvp_pro_admin_handle_copy_event( $eventID, $newEventName, $copyOverAttendees );
		}
		?>
		<div id="message" class="updated">
			<p class="updated">
				<?php
				echo rsvp_pro_get_admin_string( 'event_copy_to_message' ) . ' ' . $newEventName;
				?>
			</p>
		</div>
		<?php
		rsvp_pro_admin_eventList();
	} else {
		?>
		<h3><?php rsvp_pro_get_admin_string( 'copy_text' ); ?><?php echo rsvp_pro_get_event_name( $eventID ); ?></h3>
		<form name="rsvp_email" method="post"
			  action="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=copy&eventID=' . $eventID ); ?>">
			<?php wp_nonce_field( 'rsvp-copy' ); ?>
			<p><?php echo rsvp_pro_get_admin_string( 'copy_settings_and_questions_label' ); ?>
				<?php echo rsvp_pro_get_event_name( $eventID ); ?> <?php echo rsvp_pro_get_admin_string( 'to_new_event_label' ); ?></p>
			<p><label><?php echo rsvp_pro_get_admin_string( 'copy_attendees_question_label' ); ?>
					<input type="checkbox" name="copyOverAttendees" value="Y"/></label></p>
			<p class="submit"><input type="submit"
									 value="<?php echo rsvp_pro_get_admin_string( 'copy_event_label' ); ?>"
									 name="copyEventSubmit" class="button-primary"/></p>
		</form>
		<?php
	}
}

/**
 * Replaces the current associated attendees tag with information for associated attendees.
 *
 * @param string $attendee_content The content template we want to replace with populated data.
 * @param int    $main_attendee_id The id for the main attendee ID we want to find associations for.
 * @param int    $event_id         The id for the current event.
 * @param string $event_url        The event URL.
 * @param array  $attachments      The attachments array.
 *
 * @return string                   The content replaced with data.
 */
function rsvp_pro_admin_handle_associated_attendee_email_variable( $attendee_content, $main_attendee_id, $event_id, $event_url, &$attachments ){
	global $wpdb;
	$replaced_content = '';

	if ( rsvp_pro_is_sub_event( $event_id ) ){
		$parent_event_id = $wpdb->get_var( $wpdb->prepare( 'SELECT parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d', $event_id ) );

		$sql                  = "SELECT a.id, firstName, lastName, IFNULL(se.rsvpStatus, 'NoResponse') AS rsvpStatus, note, " .
								'suffix, salutation, passcode, email, se.rsvpDate, se.checked_in, se.token ' .
								'FROM ' . PRO_ATTENDEES_TABLE . ' a
			INNER JOIN ' . PRO_ASSOCIATED_ATTENDEES_TABLE . ' aa ON aa.attendeeID = a.id
			INNER JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = %d
			LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . " se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d
			WHERE a.rsvpEventID = %d AND aa.associatedAttendeeID = %d AND ((IFNULL(e.event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "') != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "') OR (a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = e.id)))';
		$associated_attendees = $wpdb->get_results( $wpdb->prepare( $sql, $event_id, $event_id, $parent_event_id, $main_attendee_id ) );
	} else {
		$sql                  = 'SELECT a.id, firstName, lastName, rsvpStatus, note, passcode, email, salutation, suffix, a.rsvpDate, a.token 
            FROM ' . PRO_ATTENDEES_TABLE . ' a
            INNER JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = a.rsvpEventID
            INNER JOIN ' . PRO_ASSOCIATED_ATTENDEES_TABLE . ' aa ON aa.attendeeID = a.id
            WHERE rsvpEventID = %d AND aa.associatedAttendeeID = %d ';
		$associated_attendees = $wpdb->get_results( $wpdb->prepare( $sql, $event_id, $main_attendee_id ) );
	}
	foreach ( $associated_attendees as $aa ){
		$replaced_content .= rsvp_pro_admin_replaceVariablesForEmail( $aa, $event_url, $attendee_content, $event_id, $attachments );
	}

	return $replaced_content;
}

/**
 * Replaces the content in an email template for sub-events.
 *
 * @param string $sub_event_content The template we need to replace with content data.
 * @param object $attendee          A wpdb object of attendee data.
 * @param int    $event_id          The main event ID we want to get sub-events for.
 * @param string $event_url         The event URL we want to use in the variables.
 * @param array  $attachments       The attachments array.
 *
 * @return string                    The template but filled with content.
 */
function rsvp_pro_admin_handle_sub_event_email_variable( $sub_event_content, $attendee, $event_id, $event_url, &$attachments ){
	global $wpdb;
	$replaced_content = '';

	$sql        = 'SELECT id FROM ' . PRO_EVENT_TABLE . ' WHERE parentEventID = %d';
	$sub_events = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
	foreach ( $sub_events as $se ){
		$sql                = "SELECT a.id, firstName, lastName, IFNULL(se.rsvpStatus, 'NoResponse') AS rsvpStatus, note, " .
							  'suffix, salutation, passcode, email, se.rsvpDate, se.checked_in, se.token ' .
							  'FROM ' . PRO_ATTENDEES_TABLE . ' a
			INNER JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = %d
			LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . " se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d
			WHERE se.rsvpEventID = %d AND ((IFNULL(e.event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "') != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "') OR (a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = e.id))) 
			AND se.rsvpAttendeeID = %d';
		$sub_event_attendee = $wpdb->get_row( $wpdb->prepare( $sql, $event_id, $se->id, $se->id, $attendee->id ) );
		if ( null !== $sub_event_attendee ){
			$replaced_content .= rsvp_pro_admin_replaceVariablesForEmail( $sub_event_attendee, $event_url, $sub_event_content, $se->id, $attachments );
		}
	}

	return $replaced_content;
}

function rsvp_pro_admin_replaceVariablesForEmail( $attendee, $eventUrl, $stringToReplace, $eventID, &$attachments ){
	global $wpdb;
	global $rsvp_id;
	global $rsvp_pro_inline_attachments;

	$rsvp_id           = $eventID;
	$prefillUrl        = $eventUrl;
	$prefill_url_token = add_query_arg(
			array(
					'token' => urlencode( $attendee->token ),
			),
			$eventUrl
	);

	if ( rsvp_pro_require_only_passcode_to_register( $eventID ) ){
		$prefillUrl = add_query_arg(
				array(
						'passcode' => urlencode( stripslashes( $attendee->passcode ) ),
				),
				$prefillUrl
		);
	} else {
		$url_values = array(
				'firstName' => urlencode( stripslashes( $attendee->firstName ) ),
				'lastName'  => urlencode( stripslashes( $attendee->lastName ) ),
		);

		if ( rsvp_pro_require_passcode( $eventID ) ){
			$url_values['passcode'] = urlencode( stripslashes( $attendee->passcode ) );
		}

		$prefillUrl = add_query_arg( $url_values, $prefillUrl );
	}

	$replacedString = $stringToReplace;

	/*
	 *  For the SubEvents and Assocaited Attendees chunks we remove the text in
	 *  between the starting and closing of the tags and then replace them with
	 *  the populated data. We will handle nested tags as best as possible.
	 */
	$start_sub_event_pos = stripos( $replacedString, '[[SubEvents]]' );
	do{
		if ( false !== $start_sub_event_pos ){
			$end_sub_event_pos = stripos( $replacedString, '[[/SubEvents]]', $start_sub_event_pos );

			if ( false !== $end_sub_event_pos ){
				$content_start_pos = $start_sub_event_pos + strlen( '[[SubEvents]]' );
				$sub_event_content = substr( $replacedString, $content_start_pos, ( $end_sub_event_pos - $content_start_pos ) );

				$new_content = rsvp_pro_admin_handle_sub_event_email_variable( $sub_event_content, $attendee, $eventID, $eventUrl, $attachments );

				$replacedString = str_ireplace(
						'[[SubEvents]]' . $sub_event_content . '[[/SubEvents]]',
						$new_content,
						$replacedString
				);
			}
		}
		$start_sub_event_pos = stripos( $replacedString, '[[SubEvents]]', $start_sub_event_pos + 1 );
	} while ( false !== $start_sub_event_pos );

	$start_aa_pos = stripos( $replacedString, '[[AssociatedAttendees]]' );
	do{
		if ( false !== $start_aa_pos ){
			$end_aa_pos = stripos( $replacedString, '[[/AssociatedAttendees]]', $start_aa_pos );

			if ( $end_aa_pos !== false ){
				$contentStartPos           = $start_aa_pos + strlen( '[[AssociatedAttendees]]' );
				$associatedAttendeeContent = substr( $replacedString, $contentStartPos, ( $end_aa_pos - $contentStartPos ) );

				$newContent = rsvp_pro_admin_handle_associated_attendee_email_variable( $associatedAttendeeContent, $attendee->id, $eventID, $eventUrl, $attachments );

				$replacedString = str_ireplace( '[[AssociatedAttendees]]' . $associatedAttendeeContent . '[[/AssociatedAttendees]]', $newContent, $replacedString );
			}
		}
		if ( $start_aa_pos >= strlen( $replacedString ) ){
			$start_aa_pos = strlen( $replacedString ) - 1;
		}
		$start_aa_pos = stripos( $replacedString, '[[AssociatedAttendees]]', $start_aa_pos + 1 );
	} while ( false !== $start_aa_pos );

	$main_qr    = rsvp_pro_generate_qr_for_email( $attendee->token );
	$encoded_qr = '';
	if ( false !== stripos( $replacedString, '[QR]' ) ){
		$uid                           = $eventID . '_qr_code';
		$name                          = rsvp_pro_get_event_name( $eventID ) . ' QR Code';
		$rsvp_pro_inline_attachments[] = array(
				'uid'  => $uid,
				'name' => $name,
				'file' => $main_qr,
		);
		$encoded_qr                    = '<img src="cid:' . $uid . '" />';
	}

	$prefill_qr         = rsvp_pro_generate_prefill_qr( $prefill_url_token, $attendee->token );
	$prefill_encoded_qr = '';
	if ( false !== stripos( $replacedString, '[QR_PrefillUrl]' ) ){
		$uid                           = $attendee->token . '_qr_code';
		$name                          = rsvp_pro_get_event_name( $eventID ) . ' QR Registration Code';
		$rsvp_pro_inline_attachments[] = array(
				'uid'  => $uid,
				'name' => $name,
				'file' => $prefill_qr,
		);
		$prefill_encoded_qr            = '<img src="cid:' . $uid . '" />';
	}

	$replacedString = str_ireplace( '[[QR]]', $encoded_qr, $replacedString );
	$replacedString = str_ireplace( '[[QR_PrefillUrl]]', $prefill_encoded_qr, $replacedString );
	$replacedString = str_ireplace( '[[Salutation]]', stripslashes( $attendee->salutation ), $replacedString );
	$replacedString = str_ireplace( '[[Suffix]]', stripslashes( $attendee->suffix ), $replacedString );
	$replacedString = str_ireplace( '[[Note]]', stripslashes( $attendee->note ), $replacedString );
	$replacedString = str_ireplace( '[[FirstName]]', stripslashes( $attendee->firstName ), $replacedString );
	$replacedString = str_ireplace( '[[LastName]]', stripslashes( $attendee->lastName ), $replacedString );
	$replacedString = str_ireplace( '[[RsvpStatus]]', rsvp_pro_humanize_rsvp_status( stripslashes( $attendee->rsvpStatus ), $eventID ), $replacedString );
	$replacedString = str_ireplace( '[[Email]]', stripslashes( $attendee->email ), $replacedString );
	$replacedString = str_ireplace( '[[Passcode]]', stripslashes( $attendee->passcode ), $replacedString );
	$replacedString = str_ireplace( '[[PrefillUrl]]', $prefillUrl, $replacedString );
	$replacedString = str_ireplace( '[[EventUrl]]', $eventUrl, $replacedString );
	$replacedString = str_ireplace( '[[EventName]]', rsvp_pro_get_event_name( $eventID ), $replacedString );
	$replacedString = str_ireplace( '[[EventStartDate]]', rsvp_pro_get_event_start_date( $eventID ), $replacedString );
	$replacedString = str_ireplace( '[[EventEndDate]]', rsvp_pro_get_event_end_date( $eventID ), $replacedString );
	$replacedString = str_ireplace( '[[EventLocation]]', rsvp_pro_get_event_location( $eventID ), $replacedString );
	$replacedString = str_ireplace( '[[EventDescription]]', rsvp_pro_get_event_description( $eventID ), $replacedString );
	$replacedString = str_ireplace( '[[Attendee_Rsvp_Full_Info]]', rsvp_pro_retrieveEmailBodyContent( $attendee->id, $attendee ), $replacedString );

	$sql       = 'SELECT q.id, question, a.answer, questionType FROM ' . PRO_QUESTIONS_TABLE . ' q
			JOIN ' . PRO_QUESTION_TYPE_TABLE . ' qt ON qt.id = q.questionTypeID
			LEFT JOIN ' . PRO_ATTENDEE_ANSWERS . ' a ON a.questionID = q.id AND a.attendeeID = %d
			WHERE q.rsvpEventID = %d OR q.rsvpEventID IN ( SELECT id FROM ' . PRO_EVENT_TABLE . ' WHERE parentEventID = %d )';
	$questions = $wpdb->get_results( $wpdb->prepare( $sql, $attendee->id, $eventID, $eventID ) );
	foreach ( $questions as $q ){
		if ( $q->answer != '' ){
			$answer = stripslashes( $q->answer );
			if ( QT_PRO_FILE === $q->questionType ){
				$answer = wp_get_attachment_url( $q->answer );
			}

			$tmpString      = stripslashes( $q->question ) . ': ' . $answer;
			$replacedString = str_ireplace( '[[CustomQ_' . $q->id . ']]', $tmpString, $replacedString );
			$replacedString = str_ireplace( '[[CustomQAnswer_' . $q->id . ']]', $answer, $replacedString );
			$replacedString = str_ireplace( '[[CustomQuestion_' . $q->id . ']]', stripslashes( $q->question ), $replacedString );
		} else {
			$replacedString = str_ireplace( '[[CustomQ_' . $q->id . ']]', '', $replacedString );
			$replacedString = str_ireplace( '[[CustomQAnswer_' . $q->id . ']]', '', $replacedString );
			$replacedString = str_ireplace( '[[CustomQuestion_' . $q->id . ']]', '', $replacedString );
		}
	}

	return $replacedString;
}

function rsvp_pro_admin_confirm_reset_all_attendees( $event_id ){
	if ( is_numeric( $event_id ) && ( $event_id > 0 ) ){
		?>
		<div class="wrap">
			<form name="rsvpProResetAttendees" method="post"
				  action="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=reset_all_attendees&eventID=' . $event_id ); ?>">
				<?php wp_nonce_field( 'rsvp_reset_attendees_for_event' ); ?>
				<p><?php echo rsvp_pro_get_admin_string( 'reset_attendees_caution_label' ); ?>
					<b><?php echo rsvp_pro_get_event_name( $event_id ); ?></b>?
					<?php echo rsvp_pro_get_admin_string( 'reset_rsvp_status_label' ); ?></p>
				<p class="submit">
					<input type="submit" class="button-primary"
						   value="<?php echo rsvp_pro_get_admin_string( 'reset_label' ); ?>"/>
				</p>
			</form>
		</div>
		<?php
	}
}

/**
 * This will reset all attendee's RSVP information and related
 * fields for a give event.
 *
 * @param int $event_id The event we want to reset the attendees for
 */
function rsvp_pro_admin_reset_all_guests( $event_id ){
	global $wpdb;

	check_admin_referer( 'rsvp_reset_attendees_for_event' );
	if ( is_numeric( $event_id ) && ( $event_id > 0 ) ){
		$sql = 'SELECT id FROM ' . PRO_ATTENDEES_TABLE . ' WHERE rsvpEventID = %d';

		if ( rsvp_pro_is_shared_attendee_list_enabled() ){
			$sql .= ' OR rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID;
		}

		$attendees = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
		foreach ( $attendees as $a ){
			rsvp_pro_admin_reset_single_attendee( $a->id );
		}
	}

	rsvp_pro_admin_eventList();
}

/**
 * Resets an attendee's RSVP information and related fields. It will also
 * clear out the custom questions answered. It will then redirect to the user's
 * modification page.
 *
 * @param int $eventID
 */
function rsvp_pro_admin_reset_guest( $eventID ){
	global $wpdb;

	$user_id = $_GET['id'];
	if ( isset( $user_id ) && ( $user_id > 0 ) ){
		check_admin_referer( 'reset_attendee_' . $user_id );

		rsvp_pro_admin_reset_single_attendee( $user_id );

		rsvp_pro_admin_guest( $eventID );

		return;
	}

	rsvp_pro_admin_guestlist( $eventID );
}

/**
 * Function to reset an individual attendee's information including custom questions.
 *
 * @param int $attendee_id The attendee id we need to reset
 */
function rsvp_pro_admin_reset_single_attendee( $attendee_id ){
	global $wpdb;

	if ( isset( $attendee_id ) && ( $attendee_id > 0 ) ){
		$wpdb->delete( PRO_ATTENDEE_ANSWERS, array( 'attendeeID' => $attendee_id ), array( '%d' ) );

		// Update attendee record for RSVP information
		$wpdb->update(
				PRO_ATTENDEES_TABLE,
				array(
						'rsvpDate'   => null,
						'rsvpStatus' => 'NoResponse',
						'note'       => '',
				),
				array( 'id' => $attendee_id ),
				array( '%s', '%s', '%s' ),
				array( '%d' )
		);

		$wpdb->delete( PRO_ATTENDEE_SUB_EVENTS_TABLE, array( 'rsvpAttendeeID' => $attendee_id ), array( '%d' ) );
	}
}

function rsvp_pro_admin_reminder_delete( $eventID ){
	if ( empty( $_REQUEST['_wpnonce'] ) ){
		rsvp_pro_admin_reminders( $eventID );

		return;
	}

	if ( !wp_verify_nonce( $_REQUEST['_wpnonce'], 'bulk-reminders' ) ){
		rsvp_pro_admin_reminders( $eventID );

		return;
	}

	$ids = isset( $_GET['rsvp_reminder'] ) ? $_GET['rsvp_reminder'] : false;

	if ( !is_array( $ids ) ){
		$ids = array( $ids );
	}

	foreach ( $ids as $id ){
		$r = new Rsvp_Pro_Event_Reminder_Dao( $id );
		$r->delete();
	}

	rsvp_pro_admin_reminders( $eventID );
}

/**
 * Handles the saving of a reminder.
 *
 * @param int $eventID The current event ID
 *
 * @since 2.2.4
 */
function rsvp_pro_admin_reminder_save( $eventID ){
	$reminderID = 0;
	if ( isset( $_POST['reminderID'] ) ){
		$reminderID = $_POST['reminderID'];
	}

	if ( !wp_verify_nonce( $_POST['rsvp-reminder-nonce'], 'rsvp-reminder-form' ) ){
		rsvp_pro_admin_reminders( $eventID );
	} else {
		$reminder = new Rsvp_Pro_Event_Reminder_Dao( $reminderID );
		$reminder->set_RsvpEventID( $eventID );
		$reminder->set_Name( $_POST['name'] );
		$reminder->set_TimeType( $_POST['timeType'] );
		$reminder->set_Period( $_POST['period'] );
		$reminder->set_SendOn( $_POST['sendon'] );
		if ( isset( $_POST['rsvpStatuses'] ) ){
			$reminder->set_RsvpStatuses( implode( ',', $_POST['rsvpStatuses'] ) );
		}
		$reminder->set_MessageSubject( $_POST['messageSubject'] );
		$reminder->set_MessageBody( $_POST['messageBody'] );
		$reminder->save();

		rsvp_pro_admin_reminders( $eventID );
	}
}

/**
 * Displays the form for a specific reminder that will be used for adding or editing the reminder
 *
 * @param int $eventID the current event
 *
 * @since 2.2.4
 */
function rsvp_pro_admin_reminder_form( $eventID ){
	$reminderID = 0;
	if ( isset( $_GET['reminderID'] ) ){
		$reminderID = $_GET['reminderID'];
	}
	$reminders = new Rsvp_Pro_Event_Reminders( $eventID );
	$reminders->show_form( $reminderID );
}

/**
 * Displays the list of reminders for a given event
 *
 * @param int $event_id the event ID that we want to get reminder list for
 *
 * @return outputs the HTML for the reminder list
 */
function rsvp_pro_admin_reminders( $event_id ){
	$reminders = new Rsvp_Pro_Event_Reminders( $event_id );
	$reminders->list_reminders();
}

/**
 * Displays all of the message log entries for a given event
 *
 * @param int $event_id The event we want to get the message log entries for
 *
 * @return outputs the HTML for the message log list
 */
function rsvp_pro_admin_message_logs( $event_id ){
	$message_logs = new Rsvp_Pro_Message_Logs( $event_id );
	$message_logs->list_message_logs();
}

function rsvp_pro_admin_view_message_log( $event_id ){
	if ( isset( $_GET['log_id'] ) && ( $_GET['log_id'] > 0 ) ){
		$message_logs = new Rsvp_Pro_Message_Logs( $event_id );
		$message_logs->view_message_log( $_GET['log_id'] );
	} else {
		rsvp_pro_admin_message_logs( $event_id );
	}
}

/**
 * Deletes the specified message logs
 */
function rsvp_pro_admin_delete_message_logs(){
	global $wpdb;
	if ( !empty( $_REQUEST['_wpnonce'] ) && ( wp_verify_nonce( $_REQUEST['_wpnonce'], 'bulk-messagelogs' ) !== false ) ){
		$ids = isset( $_GET['message_log'] ) ? $_GET['message_log'] : false;

		if ( !is_array( $ids ) ){
			$ids = array( $ids );
		}

		foreach ( $ids as $id ){
			$wpdb->delete(
					PRO_MESSAGE_LOG_ATTENDEES,
					array( 'message_id' => $id ),
					array( '%d' )
			);

			$wpdb->delete(
					PRO_MESSAGE_LOG,
					array( 'id' => $id ),
					array( '%d' )
			);
		}
	}
}

function rsvp_pro_admin_questions( $eventID ){
	global $wpdb;

	$rsvp_pro_helper = RSVP_PRO_Admin_Helper::get_instance();
	if ( $eventID < 0 ){
		rsvp_pro_admin_events();
		die;
	}

	if ( !rsvp_pro_admin_user_has_access_to_settings( $eventID ) ){
		rsvp_pro_admin_eventList();

		return;
	}

	if ( ( count( $_POST ) > 0 ) && ( $_POST['rsvp-bulk-action'] == 'delete' ) && ( is_array( $_POST['q'] ) && ( count( $_POST['q'] ) > 0 ) ) ){
		foreach ( $_POST['q'] as $q ){
			if ( is_numeric( $q ) && ( $q > 0 ) ){
				$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_QUESTIONS_TABLE . ' WHERE id = %d AND rsvpEventID = %d', $q, $eventID ) );
				$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d', $q ) );
				$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE questionID = %d', $q ) );
			}
		}
	} elseif ( ( count( $_POST ) > 0 ) && ( $_POST['rsvp-bulk-action'] == 'saveSortOrder' ) ) {
		rsvp_pro_save_custom_question_sort_order( $eventID );
	}

	$customQs = $rsvp_pro_helper->get_custom_questions($eventID);
	?>
	<div class="wrap">
		<div id="icon-edit" class="icon32"><br/></div>
		<h1 class="wp-heading-inline"><?php echo rsvp_pro_get_event_name( $eventID ); ?> <?php echo rsvp_pro_get_admin_string( 'custom_questions_label' ); ?></h1>
		<a class="page-title-action" href="<?php echo admin_url( "admin.php?page=rsvp-pro-top-level&action=modify_custom_question&eventID=$eventID" ); ?>"><?php echo esc_html__( 'Add new', 'rsvp-pro-plugin' ); ?></a>
		<hr class="wp-header-end">
		<form method="post" id="rsvp-form">
			<input type="hidden" id="rsvp-bulk-action" name="rsvp-bulk-action"/>
			<input type="hidden" id="event_id" name="event_id" value="<?php echo esc_attr( $eventID ); ?>"/>
			<div class="tablenav">
				<div class="alignleft actions">
					<select id="rsvp-action-top" name="rsvpbulkaction">
						<option value=""
								selected="selected"><?php echo rsvp_pro_get_admin_string( 'bulk_actions_label' ); ?></option>
						<option value="delete"><?php echo rsvp_pro_get_admin_string( 'delete_label' ); ?></option>
					</select>
					<input type="submit" value="<?php echo rsvp_pro_get_admin_string( 'apply_label' ); ?>"
						   name="doaction" id="doaction" class="button-secondary action"
						   onclick="document.getElementById('rsvp-bulk-action').value = document.getElementById('rsvp-action-top').value;"/>
					<!--<input type="submit" value="<?php echo rsvp_pro_get_admin_string( 'save_sort_order_label' ); ?>"
						   name="saveSortButton" id="saveSortButton" class="button-secondary action"
						   onclick="document.getElementById('rsvp-bulk-action').value = 'saveSortOrder';"/>-->
					<span id="sortOrderSaveStatus"></span>
				</div>
				<div class="clear"></div>
			</div>
			<?php
			$questions_table = new RSVP_PRO_Questions_List_Table();
			$tableQuestions  = $questions_table->prepare_questions( $customQs );
			$questions_table->prepare_items( $tableQuestions );
			$questions_table->display();
			?>
		</form>
	</div>
	<?php
}

function rsvp_pro_get_question_with_answer_type_ids(){
	global $wpdb;

	$ids     = array();
	$sql     = 'SELECT id FROM ' . PRO_QUESTION_TYPE_TABLE . "
				WHERE questionType IN ('" . QT_PRO_MULTI . "', '" . QT_PRO_DROP . "', '" . QT_PRO_RADIO . "')";
	$results = $wpdb->get_results( $sql );
	foreach ( $results as $r ){
		$ids[] = (int)$r->id;
	}

	return $ids;
}

/**
 * Handles the displaying of a custom question and also the saving of the custom question.
 *
 * @param int $event_id The event ID the custom question is associated with.
 */
function rsvp_pro_admin_custom_question( $event_id ){
	global $wpdb;

	if ( !rsvp_pro_admin_user_has_access_to_settings( $event_id ) ){
		rsvp_pro_admin_eventList();

		return;
	}

	$answerQuestionTypes = rsvp_pro_get_question_with_answer_type_ids();
	$isSubEvent          = false;
	$parentEventID       = $wpdb->get_var( $wpdb->prepare( 'SELECT parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d', $event_id ) );
	if ( $parentEventID > 0 ){
		$isSubEvent = true;
	}

	$radioQuestionType = $wpdb->get_var( 'SELECT id FROM ' . PRO_QUESTION_TYPE_TABLE . " WHERE questionType = 'radio'" );
	if ( $radioQuestionType == 0 ){
		$wpdb->insert(
				PRO_QUESTION_TYPE_TABLE,
				array(
						'questionType' => 'radio',
						'friendlyName' => 'Radio',
				),
				array( '%s', '%s' )
		);
	}
	$hiddeQuestionType = $wpdb->get_var( 'SELECT id FROM ' . PRO_QUESTION_TYPE_TABLE . " WHERE questionType = 'hidden'" );
	if ( $hiddeQuestionType == 0 ){
		$wpdb->insert(
				PRO_QUESTION_TYPE_TABLE,
				array(
						'questionType' => 'hidden',
						'friendlyName' => 'Admin Only',
				),
				array( '%s', '%s' )
		);
	}
	$readonlyQuestionType = $wpdb->get_var( 'SELECT id FROM ' . PRO_QUESTION_TYPE_TABLE . " WHERE questionType = 'readonly'" );
	if ( $readonlyQuestionType == 0 ){
		$wpdb->insert(
				PRO_QUESTION_TYPE_TABLE,
				array(
						'questionType' => 'readonly',
						'friendlyName' => 'Read Only',
				),
				array( '%s', '%s' )
		);
	}
	$isRequired          = ( isset( $_POST['questionRequired'] ) && ( $_POST['questionRequired'] === 'Y' ) ) ? 'Y' : 'N';
	$only_show_on_status = ( isset( $_POST['only_show_on_status'] ) && !empty( $_POST['only_show_on_status'] ) ) ? $_POST['only_show_on_status'] : '';
	$ask_only_associated = ( isset( $_POST['ask_only_associated'] ) && ( $_POST['ask_only_associated'] === 'Y' ) ) ? 'Y' : 'N';
	$other_question      = ( isset( $_POST['other_question'] ) && ( 'Y' === $_POST['other_question'] ) ) ? 'Y' : 'N';

	if ( ( count( $_POST ) > 0 ) && !empty( $_POST['question'] ) && is_numeric( $_POST['questionTypeID'] ) ){
		check_admin_referer( 'rsvp_add_custom_question' );
		if ( isset( $_POST['questionID'] ) && is_numeric( $_POST['questionID'] ) ){
			$wpdb->update(
					PRO_QUESTIONS_TABLE,
					array(
							'question'            => trim( $_POST['question'] ),
							'questionTypeID'      => trim( $_POST['questionTypeID'] ),
							'permissionLevel'     => ( ( trim( $_POST['permissionLevel'] ) == 'private' ) ? 'private' : 'public' ),
							'grouping'            => ( ( $_POST['questionGrouping'] == RSVP_PRO_QG_MULTI ) ? RSVP_PRO_QG_MULTI : RSVP_PRO_QG_SINGLE ),
							'required'            => $isRequired,
							'required_text'       => $_POST['questionRequiredText'],
							'only_show_on_status' => $only_show_on_status,
							'ask_only_associated' => $ask_only_associated,
							'other_question'      => $other_question,
							'other_question_text' => $_POST['other_question_text']
					),
					array( 'id' => $_POST['questionID'] ),
					array( '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ),
					array( '%d' )
			);
			$questionId = $_POST['questionID'];

			$answers = $wpdb->get_results( $wpdb->prepare( 'SELECT id FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d', $questionId ) );
			if ( count( $answers ) > 0 ){
				foreach ( $answers as $a ){
					if ( isset( $_POST[ 'deleteAnswer' . $a->id ] ) && ( strToUpper( $_POST[ 'deleteAnswer' . $a->id ] ) == 'Y' ) ){
						$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE id = %d', $a->id ) );
					} elseif ( isset( $_POST[ 'answer' . $a->id ] ) && ( $_POST[ 'answer' . $a->id ] != '' ) ) {
						$wpdb->update(
								PRO_QUESTION_ANSWERS_TABLE,
								array(
										'answer'        => trim( $_POST[ 'answer' . $a->id ] ),
										'defaultAnswer' => ( ( isset( $_POST[ 'defaultAnswer' . $a->id ] ) && ( $_POST[ 'defaultAnswer' . $a->id ] === 'Y' ) ) ? 'Y' : 'N' ),
								),
								array( 'id' => $a->id ),
								array( '%s', '%s' ),
								array( '%d' )
						);
					}
				}
			}
		} else {
			$wpdb->insert(
					PRO_QUESTIONS_TABLE,
					array(
							'question'            => trim( $_POST['question'] ),
							'questionTypeID'      => trim( $_POST['questionTypeID'] ),
							'permissionLevel'     => ( ( trim( $_POST['permissionLevel'] ) == 'private' ) ? 'private' : 'public' ),
							'grouping'            => ( ( $_POST['questionGrouping'] == RSVP_PRO_QG_MULTI ) ? RSVP_PRO_QG_MULTI : RSVP_PRO_QG_SINGLE ),
							'required'            => $isRequired,
							'required_text'       => $_POST['questionRequiredText'],
							'rsvpEventID'         => $event_id,
							'only_show_on_status' => $only_show_on_status,
							'ask_only_associated' => $ask_only_associated,
							'other_question'      => $other_question,
							'other_question_text' => $_POST['other_question_text']
					),
					array( '%s', '%d', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s' )
			);
			$questionId = $wpdb->insert_id;
		}

		if ( isset( $_POST['numNewAnswers'] ) && is_numeric( $_POST['numNewAnswers'] ) &&
			 in_array( $_POST['questionTypeID'], $answerQuestionTypes ) ){
			for ( $i = 0; $i < $_POST['numNewAnswers']; $i++ ){
				if ( isset( $_POST[ 'newAnswer' . $i ] ) && ( $_POST[ 'newAnswer' . $i ] != '' ) ){
					$wpdb->insert(
							PRO_QUESTION_ANSWERS_TABLE,
							array(
									'questionID'    => $questionId,
									'answer'        => $_POST[ 'newAnswer' . $i ],
									'defaultAnswer' => ( isset( $_POST[ 'newDefaultAnswer' . $i ] ) && ( $_POST[ 'newDefaultAnswer' . $i ] == 'Y' ) ? 'Y' : 'N' ),
							),
							array(
									'%d',
									'%s',
									'%s',
							)
					);
				}
			}
		}

		if ( isset( $_POST['answer_import'] ) && !empty( $_POST['answer_import'] ) ){
			$answers = explode( "\r\n", $_POST['answer_import'] );
			foreach ( $answers as $a ){
				$wpdb->insert(
						PRO_QUESTION_ANSWERS_TABLE,
						array(
								'questionID' => $questionId,
								'answer'     => trim( $a ),
						),
						array(
								'%d',
								'%s',
						)
				);
			}
		}

		if ( strToLower( trim( $_POST['permissionLevel'] ) ) == 'private' ){
			$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . PRO_QUESTION_ATTENDEES_TABLE . ' WHERE questionID = %d', $questionId ) );
			if ( isset( $_POST['attendees'] ) && is_array( $_POST['attendees'] ) ){
				foreach ( $_POST['attendees'] as $aid ){
					if ( is_numeric( $aid ) && ( $aid > 0 ) ){
						$wpdb->insert(
								PRO_QUESTION_ATTENDEES_TABLE,
								array(
										'attendeeID' => $aid,
										'questionID' => $questionId,
								),
								array(
										'%d',
										'%d',
								)
						);
					}
				}
			}
		}
		?>
		<p><?php echo rsvp_pro_get_admin_string( 'custom_question_saved_label' ); ?></p>
		<p>
			<a class="button button-secondary" href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=custom_questions&eventID=' . $event_id ); ?>"><?php echo rsvp_pro_get_admin_string( 'continue_question_list_label' ); ?></a>
			<a class="button button-primary" href="<?php echo admin_url( "admin.php?page=rsvp-pro-top-level&action=modify_custom_question&eventID=$event_id" ); ?>"><?php echo rsvp_pro_get_admin_string( 'another_question_label' ); ?></a>
		</p>
		<?php
	} else {
		$questionTypeId      = 0;
		$question            = '';
		$isNew               = true;
		$questionId          = 0;
		$permissionLevel     = 'public';
		$savedAttendees      = array();
		$grouping            = RSVP_PRO_QG_SINGLE;
		$required            = 'N';
		$required_text       = '';
		$show_only_on_status = '';
		$ask_only_associated = 'N';
		$other_question      = 'N';
		$other_question_text = '';

		if ( isset( $_GET['id'] ) && is_numeric( $_GET['id'] ) ){
			$qRs = $wpdb->get_row(
					$wpdb->prepare(
							'SELECT id, question, questionTypeID, ask_only_associated, permissionLevel, `grouping`,
					required, only_show_on_status, required_text, other_question, other_question_text
					FROM ' . PRO_QUESTIONS_TABLE . ' WHERE id = %d',
							$_GET['id']
					)
			);
			if ( $qRs !== null ){
				$isNew               = false;
				$questionId          = $qRs->id;
				$question            = stripslashes( $qRs->question );
				$permissionLevel     = stripslashes( $qRs->permissionLevel );
				$questionTypeId      = $qRs->questionTypeID;
				$grouping            = stripslashes( $qRs->grouping );
				$required            = ( $qRs->required === 'Y' ) ? 'Y' : 'N';
				$required_text       = stripslashes( $qRs->required_text );
				$ask_only_associated = ( $qRs->ask_only_associated === 'Y' ) ? 'Y' : 'N';
				$only_show_on_status = stripslashes( $qRs->only_show_on_status );
				$other_question      = ( $qRs->other_question === 'Y' ) ? 'Y' : 'N';
				$other_question_text = stripslashes_deep( $qRs->other_question_text );

				if ( $permissionLevel == 'private' ){
					$aRs = $wpdb->get_results( $wpdb->prepare( 'SELECT attendeeID FROM ' . PRO_QUESTION_ATTENDEES_TABLE . ' WHERE questionID = %d', $questionId ) );
					if ( count( $aRs ) > 0 ){
						foreach ( $aRs as $a ){
							$savedAttendees[] = $a->attendeeID;
						}
					}
				}
			}
		}

		$sql           = 'SELECT id, questionType, friendlyName FROM ' . PRO_QUESTION_TYPE_TABLE;
		$questionTypes = $wpdb->get_results( $sql );
		?>
		<script type="text/javascript">
			var questionTypeId = [
				<?php
				foreach ( $answerQuestionTypes as $aqt ){
					echo '"' . $aqt . '",';
				}
				?>
			];

			function addAnswer( counterElement ) {
				var currAnswer = jQuery( "#numNewAnswers" ).val();
				if ( isNaN( currAnswer ) ) {
					currAnswer = 0;
				}

				var s = "<tr>\r\n" +
						"<td align=\"right\" width=\"75\"><label for=\"newAnswer" + currAnswer + "\"><?php echo rsvp_pro_get_admin_string( 'answer_label' ); ?>:</label></td>\r\n" +
						"<td><input type=\"text\" name=\"newAnswer" + currAnswer + "\" id=\"newAnswer" + currAnswer + "\" size=\"40\" /><br />\r\n" +
						"<label><input type=\"checkbox\" name=\"newDefaultAnswer" + currAnswer + "\" value=\"Y\" /><?php echo rsvp_pro_get_admin_string( 'default_answer_label' ); ?></label>" +
						"</td>\r\n" +
						"</tr>\r\n";
				jQuery( "#answerContainer" ).append( s );
				currAnswer++;
				jQuery( "#numNewAnswers" ).val( currAnswer );
				return false;
			}

			jQuery( document ).ready( function () {
				<?php
				if ( $isNew || !in_array( $questionTypeId, $answerQuestionTypes ) ){
					echo 'jQuery("#answerContainer").hide();';
				}

				if ( $isNew || ( $permissionLevel == 'public' ) ) {
				?>
				jQuery( "#attendeesArea" ).hide();
				<?php
				}
				?>
				jQuery( "#questionType" ).change( function () {
					var selectedValue = jQuery( "#questionType" ).val();
					if ( questionTypeId.indexOf( selectedValue ) != -1 ) {
						jQuery( "#answerContainer" ).show();
					} else {
						jQuery( "#answerContainer" ).hide();
					}
				} );

				jQuery( "#permissionLevel" ).change( function () {
					if ( jQuery( "#permissionLevel" ).val() != "public" ) {
						jQuery( "#attendeesArea" ).show();
					} else {
						jQuery( "#attendeesArea" ).hide();
					}
				} );
			} );
		</script>
		<h3><?php echo rsvp_pro_get_event_name( $event_id ); ?> Question</h3>
		<form name="contact" method="post">
			<input type="hidden" name="numNewAnswers" id="numNewAnswers" value="0"/>
			<?php
			if ( $questionId > 0 ){
				?>
				<input type="hidden" name="questionID" value="<?php echo $questionId; ?>"/>
				<?php
			}
			wp_nonce_field( 'rsvp_add_custom_question' );
			?>
			<p class="submit">
				<input type="submit" class="button-primary"
					   value="<?php echo rsvp_pro_get_admin_string( 'save_label' ); ?>"/>
				<a class="button button-secondary" href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=custom_questions&eventID=' . $event_id ); ?>"><?php echo rsvp_pro_get_admin_string( 'back_custom_question_label' ); ?></a>
			</p>
			<table id="customQuestions" class="form-table">
				<tr valign="top">
					<th scope="row"><label
								for="questionGrouping"><?php echo rsvp_pro_get_admin_string( 'question_grouping_label' ); ?>
							:</label></th>
					<td align="left"><select name="questionGrouping" id="questionGrouping" size="1">
							<option value="<?php echo RSVP_PRO_QG_SINGLE; ?>" <?php echo ( $grouping == RSVP_PRO_QG_SINGLE ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'question_asked_everyone_label' ); ?></option>
							<option value="<?php echo RSVP_PRO_QG_MULTI; ?>" <?php echo ( $grouping == RSVP_PRO_QG_MULTI ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'question_asked_per_associated_label' ); ?></option>
						</select>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><label
								for="questionType"><?php echo rsvp_pro_get_admin_string( 'question_type_label' ); ?>
							:</label></th>
					<td align="left"><select name="questionTypeID" id="questionType" size="1">
							<?php
							foreach ( $questionTypes as $qt ){
								echo '<option value="' . $qt->id . '" ' . ( ( $questionTypeId == $qt->id ) ? ' selected="selected"' : '' ) . '>' . $qt->friendlyName . "</option>\r\n";
							}
							?>
						</select>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><label for="question"><?php echo rsvp_pro_get_admin_string( 'question_label' ); ?>
							:</label></th>
					<td align="left"><textarea name="question" id="question" rows="5"
											   cols="60"><?php echo htmlentities( $question ); ?></textarea></td>
				</tr>
				<tr valign="top">
					<th scope="row"><label
								for="questionRequired"><?php echo rsvp_pro_get_admin_string( 'is_required_label' ); ?>
							:</label></th>
					<td align="left"><input type="checkbox" name="questionRequired" id="questionRequired"
											value="Y" <?php echo( ( $required == 'Y' ) ? 'checked="checked"' : '' ); ?> />
					</td>
				</tr>
				<tr valign="top">
					<th scope="row"><label
								for="questionRequiredText"><?php echo rsvp_pro_get_admin_string( 'required_text_label' ); ?>
							:</label></th>
					<td align="left"><input type="text" name="questionRequiredText" id="questionRequiredText"
											value="<?php echo esc_attr( $required_text ); ?>" class="large-text"/></td>
				</tr>
				<tr valign="top">
					<th scope="row"><label
								for="ask_only_associated"><?php echo rsvp_pro_get_admin_string( 'only_ask_associated_new_label' ); ?>
							:</label></th>
					<td align="left"><input type="checkbox" name="ask_only_associated" id="ask_only_associated"
											value="Y" <?php echo( ( $ask_only_associated === 'Y' ) ? 'checked="checked"' : '' ); ?> />
					</td>
				</tr>
				<tr>
					<th scope="row"><label
								for="permissionLevel"><?php echo rsvp_pro_get_admin_string( 'question_permission_label' ); ?>
							:</label></th>
					<td align="left"><select name="permissionLevel" id="permissionLevel" size="1">
							<option value="public" <?php echo ( $permissionLevel == 'public' ) ? ' selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'everyone_label' ); ?></option>
							<option value="private" <?php echo ( $permissionLevel == 'private' ) ? ' selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'select_people_label' ); ?></option>
						</select></td>
				</tr>
				<tr id="attendeesArea">
					<th scope="row"><label
								for="attendees"><?php echo rsvp_pro_get_admin_string( 'attendees_allowed_to_answer_label' ); ?>
							:</label></th>
					<td>
						<p>
							<span style="margin-left: 30px;"><?php _e( 'Available people', 'rsvp-pro-plugin' ); ?></span>
							<span style="margin-left: 65px;"><?php _e( 'People that have access', 'rsvp-pro-plugin' ); ?></span>
						</p>
						<select name="attendees[]" id="attendeesQuestionSelect" style="height:75px;"
								multiple="multiple">
							<?php
							$sql = 'SELECT id, firstName, lastName FROM ' . PRO_ATTENDEES_TABLE . ' WHERE rsvpEventID = %d ';
							if ( rsvp_pro_is_shared_attendee_list_enabled() ){
								$sql .= ' OR rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID;
							}
							$sql .= ' ORDER BY lastName, firstName';
							$sql = $wpdb->prepare( $sql, $event_id );

							if ( $isSubEvent ){
								$sql = 'SELECT id, firstName, lastName FROM ' . PRO_ATTENDEES_TABLE . ' WHERE rsvpEventID = %d ';
								if ( rsvp_pro_is_shared_attendee_list_enabled() ){
									$sql .= ' OR rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID;
								}
								$sql .= ' ORDER BY lastName, firstName';
								$sql = $wpdb->prepare( $sql, $parentEventID );
							}
							$attendees = $wpdb->get_results( $sql );

							foreach ( $attendees as $a ){
								?>
								<option value="<?php echo $a->id; ?>"
										<?php echo( ( in_array( $a->id, $savedAttendees ) ) ? ' selected="selected"' : '' ); ?>><?php echo htmlentities( stripslashes( $a->firstName ) . ' ' . stripslashes( $a->lastName ) ); ?></option>
							<?php } ?>
						</select>
						<p>
							<span style="margin-left: 30px;"><a href="#" class="select-all-multiselect"
																data-ms-id="attendeesQuestionSelect"><?php echo rsvp_pro_get_admin_string( 'select_all_label' ); ?></a></span>
							<span style="margin-left: 110px;"><a href="#" class="deselect-all-multiselect"
																 data-ms-id="attendeesQuestionSelect"><?php echo rsvp_pro_get_admin_string( 'deselect_all_label' ); ?></a></span>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="only_show_on_status"><?php echo rsvp_pro_get_admin_string( 'show_question_rsvp_status_label' ); ?>
							:</label>
					</th>
					<td>
						<select name="only_show_on_status" id="only_show_on_status" size="1">
							<option value="">--</option>
							<option value="Yes" <?php echo ( $only_show_on_status == 'Yes' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_humanize_rsvp_status( 'Yes', $event_id ); ?></option>
							<option value="No" <?php echo ( $only_show_on_status == 'No' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_humanize_rsvp_status( 'No', $event_id ); ?></option>
							<option value="NoResponse" <?php echo ( $only_show_on_status == 'NoResponse' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_humanize_rsvp_status( 'NoResponse', $event_id ); ?></option>
							<option value="Maybe" <?php echo ( $only_show_on_status == 'Maybe' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_humanize_rsvp_status( 'Maybe', $event_id ); ?></option>
							<option value="Waitlist" <?php echo ( $only_show_on_status == 'Waitlist' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_humanize_rsvp_status( 'Waitlist', $event_id ); ?></option>
							<option value="PlusOne" <?php echo ( $only_show_on_status == 'PlusOne' ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_humanize_rsvp_status( 'PlusOne', $event_id ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<table cellpadding="0" cellspacing="0" border="0" id="answerContainer">
							<tr>
								<th>
									<label for="other_question"><?php echo rsvp_pro_get_admin_string( 'other_question_display_setting_label' ); ?>
										:</label></th>
								<td><input type="checkbox" name="other_question" id="other_question" value="Y" <?php
									if ( 'Y' === $other_question ){
										echo 'checked="checked"';
									}
									?> /></td>
							</tr>
							<tr>
								<th>
									<label for="other_question_text"><?php echo rsvp_pro_get_admin_string( 'other_question_text_setting_label' ); ?>
										:</label></th>
								<td><input type="text" name="other_question_text" id="other_question_text"
										   value="<?php echo esc_attr( $other_question_text ); ?>"
										   class="regular-text"/>
									<br/>
									<span class="description"><?php echo rsvp_pro_get_admin_string( 'other_question_text_setting_description' ); ?></span>
								</td>
							</tr>
							<tr>
								<th><?php echo rsvp_pro_get_admin_string( 'answers_label' ); ?></th>
								<th align="right"><a href="#"
													 onclick="return addAnswer();"><?php echo rsvp_pro_get_admin_string( 'add_answer_label' ); ?></a>
								</th>
							</tr>
							<?php
							if ( !$isNew ){
								$aRs = $wpdb->get_results( $wpdb->prepare( 'SELECT id, answer, defaultAnswer FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d', $questionId ) );
								if ( count( $aRs ) > 0 ){
									foreach ( $aRs as $answer ){
										?>
										<tr>
											<td width="75" align="right"><label
														for="answer<?php echo $answer->id; ?>"><?php echo rsvp_pro_get_admin_string( 'answer_label' ); ?>
													:</label></td>
											<td><input type="text" name="answer<?php echo $answer->id; ?>"
													   id="answer<?php echo $answer->id; ?>" size="40"
													   value="<?php echo esc_attr( stripslashes( $answer->answer ) ); ?>"/>
												<br/>
												<input type="checkbox" name="deleteAnswer<?php echo $answer->id; ?>"
													   id="deleteAnswer<?php echo $answer->id; ?>" value="Y"/><label
														for="deleteAnswer<?php echo $answer->id; ?>"><?php echo rsvp_pro_get_admin_string( 'delete_label' ); ?></label>
												<br/>
												<label><input type="checkbox"
															  name="defaultAnswer<?php echo $answer->id; ?>"
															  id="defaultAnswer<?php echo $answer->id; ?>"
															  value="Y" <?php echo( ( $answer->defaultAnswer == 'Y' ) ? 'checked="checked"' : '' ); ?> /><?php echo rsvp_pro_get_admin_string( 'default_answer_label' ); ?>
												</label>
											</td>
										</tr>
										<?php
									}
								}
							}
							?>
						</table>
					</td>
				</tr>
				<tr>
					<th colspan="2"><label
								for="answer_import"><?php echo rsvp_pro_get_admin_string( 'custom_questions_answer_import_label' ); ?></label>
					</th>
				</tr>
				<tr>
					<td colspan="2">
						<textarea name="answer_import" id="answer_import" rows="15" cols="60"></textarea>
					</td>
				</tr>
			</table>
			<p class="submit">
				<input type="submit" class="button-primary"
					   value="<?php echo rsvp_pro_get_admin_string( 'save_label' ); ?>"/>
			</p>
		</form>
		<?php
	}
}

function rsvp_pro_admin_import_from_free( $eventID ){
	global $wpdb;

	$sql    = 'SELECT eventName FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
	$events = $wpdb->get_results( $wpdb->prepare( $sql, $eventID ) );
	if ( count( $events ) <= 0 ){
		rsvp_pro_admin_eventList();

		return;
	}

	if ( !rsvp_pro_admin_user_has_access_to_settings( $eventID ) ){
		rsvp_pro_admin_eventList();

		return;
	}

	if ( count( $_POST ) > 0 ){
		check_admin_referer( 'rsvp_import_from_free' );

		// we will use this array for when we want to move data over from the old questions
		// but don't want to look up the new and old question IDs. Just is an "easy" way
		// to keep a relationship between the old and new records.
		$questionMapping = array();

		// Import rsvpCustomQuestions
		$qTable   = $wpdb->prefix . 'rsvpCustomQuestions';
		$sql      = "SELECT id, permissionLevel, question, questionTypeID, sortOrder FROM $qTable";
		$customQs = $wpdb->get_results( $sql );
		if ( count( $customQs ) > 0 ){
			foreach ( $customQs as $cq ){
				$wpdb->insert(
						PRO_QUESTIONS_TABLE,
						array(
								'question'        => trim( $cq->question ),
								'questionTypeID'  => trim( $cq->questionTypeID ),
								'permissionLevel' => ( ( trim( $cq->permissionLevel ) == 'private' ) ? 'private' : 'public' ),
								'sortOrder'       => $cq->sortOrder,
								'rsvpEventID'     => $eventID,
						),
						array( '%s', '%d', '%s', '%d', '%d' )
				);
				$questionId                 = $wpdb->insert_id;
				$questionMapping[ $cq->id ] = $questionId;

				// Import rsvpCustomQuestionAnswers
				$qaTable   = $wpdb->prefix . 'rsvpCustomQuestionAnswers';
				$sql       = "SELECT answer FROM $qaTable WHERE questionID = %d";
				$customQAs = $wpdb->get_results( $wpdb->prepare( $sql, $cq->id ) );
				if ( count( $customQAs ) ){
					foreach ( $customQAs as $qa ){
						$wpdb->insert(
								PRO_QUESTION_ANSWERS_TABLE,
								array(
										'questionID' => $questionId,
										'answer'     => $qa->answer,
								)
						);
					}
				}
			}
		}

		// Similar to the $questionMapping array used above.
		$attendeeMapping = array();

		// Import attendees
		$attendeeTable = $wpdb->prefix . 'attendees';
		$sql           = "SELECT firstName, lastName, email, personalGreeting, passcode, additionalAttendee, id, note, rsvpDate, rsvpStatus FROM $attendeeTable";
		$attendees     = $wpdb->get_results( $sql );
		if ( count( $attendees ) > 0 ){
			foreach ( $attendees as $a ){
				$wpdb->insert(
						PRO_ATTENDEES_TABLE,
						array(
								'firstName'          => $a->firstName,
								'lastName'           => $a->lastName,
								'email'              => $a->email,
								'personalGreeting'   => $a->personalGreeting,
								'passcode'           => $a->passcode,
								'additionalAttendee' => $a->additionalAttendee,
								'note'               => $a->note,
								'rsvpDate'           => $a->rsvpDate,
								'rsvpStatus'         => $a->rsvpStatus,
								'rsvpEventID'        => $eventID,
						),
						array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' )
				);
				$attendeeId                = $wpdb->insert_id;
				$attendeeMapping[ $a->id ] = $attendeeId;

				// Import rsvpCustomQuestionAttendees
				$cqAttendees      = $wpdb->prefix . 'rsvpCustomQuestionAttendees';
				$sql              = "SELECT attendeeID, questionID FROM $cqAttendees WHERE attendeeID = %d";
				$customQAttendees = $wpdb->get_results( $wpdb->prepare( $sql, $a->id ) );
				if ( count( $customQAttendees ) > 0 ){
					foreach ( $customQAttendees as $cqa ){
						$wpdb->insert(
								PRO_QUESTION_ATTENDEES_TABLE,
								array(
										'attendeeID' => $attendeeId,
										'questionID' => $questionMapping[ $cqa->questionID ],
								),
								array( '%d', '%d' )
						);
					}
				}

				// Import attendeeAnswers
				$aaTable  = $wpdb->prefix . 'attendeeAnswers';
				$sql      = "SELECT answer, questionID FROM $aaTable WHERE attendeeID = %d";
				$aAnswers = $wpdb->get_results( $wpdb->prepare( $sql, $a->id ) );
				if ( count( $aAnswers ) > 0 ){
					foreach ( $aAnswers as $ans ){
						$wpdb->insert(
								PRO_ATTENDEE_ANSWERS,
								array(
										'attendeeID' => $attendeeId,
										'questionID' => $questionMapping[ $ans->questionID ],
										'answer'     => $ans->answer,
								),
								array( '%d', '%d', '%s' )
						);
					}
				}
			}
		}

		// Finally import associatedAttendees
		$aaTable       = $wpdb->prefix . 'associatedAttendees';
		$sql           = "SELECT associatedAttendeeID, attendeeID FROM $aaTable";
		$assocAttendee = $wpdb->get_results( $sql );
		if ( count( $assocAttendee ) > 0 ){
			foreach ( $assocAttendee as $aa ){
				$wpdb->insert(
						PRO_ASSOCIATED_ATTENDEES_TABLE,
						array(
								'associatedAttendeeID' => $attendeeMapping[ $aa->associatedAttendeeID ],
								'attendeeID'           => $attendeeMapping[ $aa->attendeeID ],
						),
						array( '%d', '%d' )
				);
			}
		}
		?>
		<p><?php echo rsvp_pro_get_admin_string( 'import_complete_label' ); ?>.</p>

		<p>
			<a href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=attendees&eventID=' . $eventID ); ?>"><?php echo rsvp_pro_get_admin_string( 'continue_attendee_list_label' ); ?></a>
		</p>
		<?php
	} else {
		?>
		<form name="importFromFree" method="post">
			<?php wp_nonce_field( 'rsvp_import_from_free' ); ?>
			<p><?php echo rsvp_pro_get_admin_string( 'import_from_free_label' ); ?> <?php echo $events[0]->eventName; ?>
				?</p>
			<p class="submit">
				<input type="submit" class="button-primary"
					   value="<?php echo rsvp_pro_get_admin_string( 'import_label' ); ?>"/>
			</p>
		</form>
		<?php
	} // if(count($_POST) > 0)...
}

/**
 * Surfaces the global options for the RSVP Pro plugin.
 */
function rsvp_pro_global_options(){
	?>
	<div class="wrap">
		<h1><?php echo rsvp_pro_get_admin_string( 'rsvp_general_settings_label' ); ?></h1>
		<?php
		settings_errors();
		?>
		<form method="post" action="options.php">
			<?php wp_nonce_field( 'rsvp_pro_global_settings' ); ?>
			<?php settings_fields( 'rsvp-pro-option-group' ); ?>
			<table class="form-table">
				<tbody>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_DELETE_TABLES; ?>"><?php echo rsvp_pro_get_admin_string( 'delete_data_uninstall_label' ); ?></label>
					</th>
					<td>
						<input type="checkbox" name="<?php echo RSVP_PRO_GLOBAL_OPTION_DELETE_TABLES; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_DELETE_TABLES; ?>"
							   value="Y" <?php echo( ( get_option( RSVP_PRO_GLOBAL_OPTION_DELETE_TABLES ) == 'Y' ) ? ' checked="checked"' : '' ); ?> />
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_NUM_ATTENDEES_PER_PAGE; ?>"><?php echo rsvp_pro_get_admin_string( 'admin_attendees_per_page_setting_label' ); ?></label>
					</th>
					<td>
						<?php $tmp_page_size = get_option( RSVP_PRO_GLOBAL_OPTION_NUM_ATTENDEES_PER_PAGE ); ?>
						<select name="<?php echo RSVP_PRO_GLOBAL_OPTION_NUM_ATTENDEES_PER_PAGE; ?>"
								id="<?php echo RSVP_PRO_GLOBAL_OPTION_NUM_ATTENDEES_PER_PAGE; ?>" size="1">
							<option value="">--</option>
							<option value="25" <?php echo ( '25' == $tmp_page_size ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'result_25' ); ?></option>
							<option value="50" <?php echo ( '50' == $tmp_page_size ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'result_50' ); ?></option>
							<option value="100" <?php echo ( '100' == $tmp_page_size ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'result_100' ); ?></option>
							<option value="all" <?php echo ( 'all' == $tmp_page_size ) ? 'selected="selected"' : ''; ?>><?php echo rsvp_pro_get_admin_string( 'result_all' ); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_POST_TYPE; ?>"><?php echo rsvp_pro_get_admin_string( 'post_type_select_settings_label' ); ?></label>
					</th>
					<td>
						<select name="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_POST_TYPE; ?>"
								id="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_POST_TYPE; ?>" size="1">
							<?php
							$selected_post_type = 'page';
							if ( get_option( RSVP_PRO_GLOBAL_OPTION_AUTO_POST_TYPE ) != '' ){
								$selected_post_type = get_option( RSVP_PRO_GLOBAL_OPTION_AUTO_POST_TYPE );
							}

							$args       = array(
									'public' => true,
							);
							$post_types = get_post_types( $args );
							foreach ( $post_types as $pt ){
								?>
								<option value="<?php echo $pt; ?>"
										<?php echo( ( $selected_post_type == $pt ) ? 'selected="selected"' : '' ); ?>><?php echo ucfirst( $pt ); ?></option>
								<?php
							}
							?>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_DISABLE_COMMENTS; ?>"><?php echo rsvp_pro_get_admin_string( 'disable_comments_label' ); ?></label>
					</th>
					<td>
						<input type="checkbox" name="<?php echo RSVP_PRO_GLOBAL_OPTION_DISABLE_COMMENTS; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_DISABLE_COMMENTS; ?>"
							   value="Y" <?php echo( ( get_option( RSVP_PRO_GLOBAL_OPTION_DISABLE_COMMENTS ) == 'Y' ) ? ' checked="checked"' : '' ); ?> />
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'disable_comments_description' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST; ?>"><?php echo rsvp_pro_get_admin_string( 'enable_global_attendee_list_label' ); ?></label>
					</th>
					<td>
						<input type="checkbox" name="<?php echo RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST; ?>" value="Y"
								<?php
								echo( ( get_option( RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST ) == 'Y' ) ? ' checked="checked" ' : '' );
								?>
						/>
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'enable_global_attendee_list_description' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_ENABLE_ATTENDEE_CHANGELOG; ?>"><?php echo rsvp_pro_get_admin_string( 'enable_global_attendee_changelog_label' ); ?></label>
					</th>
					<td>
						<input type="checkbox" name="<?php echo RSVP_PRO_GLOBAL_OPTION_ENABLE_ATTENDEE_CHANGELOG; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_ENABLE_ATTENDEE_CHANGELOG; ?>" value="Y"
								<?php
								echo( ( get_option( RSVP_PRO_GLOBAL_OPTION_ENABLE_ATTENDEE_CHANGELOG ) == 'Y' ) ? ' checked="checked" ' : '' );
								?>
						/>
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'enable_global_attendee_changelog_description' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_PAGE; ?>"><?php echo rsvp_pro_get_admin_string( 'auto_create_post_type_label' ); ?></label>
					</th>
					<td>
						<input type="checkbox" name="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_PAGE; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_PAGE; ?>"
							   value="Y" <?php echo( ( get_option( RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_PAGE ) == 'Y' ) ? ' checked="checked"' : '' ); ?> />
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'page_found_or_not_description_label' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_ADD_ATTENDEE_LIST_TO_PAGE; ?>"><?php echo rsvp_pro_get_admin_string( 'add_attendee_list_to_auto_page_label' ); ?></label>
					</th>
					<td>
						<input type="checkbox" name="<?php echo RSVP_PRO_GLOBAL_OPTION_ADD_ATTENDEE_LIST_TO_PAGE; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_ADD_ATTENDEE_LIST_TO_PAGE; ?>"
							   value="Y" <?php echo( ( get_option( RSVP_PRO_GLOBAL_OPTION_ADD_ATTENDEE_LIST_TO_PAGE ) == 'Y' ) ? ' checked="checked"' : '' ); ?> />
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'attendee_list_auto_page_description' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_ATTENDEE_LIST; ?>"><?php echo rsvp_pro_get_admin_string( 'auto_create_attendee_list_label' ); ?></label>
					</th>
					<td>
						<input type="checkbox" name="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_ATTENDEE_LIST; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_ATTENDEE_LIST; ?>"
							   value="Y" <?php echo( ( get_option( RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_ATTENDEE_LIST ) == 'Y' ) ? 'checked="checked"' : '' ); ?> />
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'auto_create_attendee_list_description' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_STYLES; ?>"><?php echo rsvp_pro_get_admin_string( 'custom_styling_label' ); ?></label>
					</th>
					<td>
						<textarea name="<?php echo RSVP_PRO_GLOBAL_OPTION_STYLES; ?>"
								  id="<?php echo RSVP_PRO_GLOBAL_OPTION_STYLES; ?>" rows="20" cols="70"
								  class="large-text code"><?php echo esc_html( get_option( RSVP_PRO_GLOBAL_OPTION_STYLES ) ); ?></textarea>
					</td>
				</tr>
				<tr>
					<th scope="row" colspan="2">
						<h3><?php echo rsvp_pro_get_admin_string( 'attendee_event_list_settings_title' ); ?></h3>
					</th>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_ATTENDEE_LIST_GREETING_TEXT; ?>"><?php echo rsvp_pro_get_admin_string( 'attendee_list_greeting_label' ); ?></label>
					</th>
					<td>
						<input type="text" name="<?php echo RSVP_PRO_GLOBAL_OPTION_ATTENDEE_LIST_GREETING_TEXT; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_ATTENDEE_LIST_GREETING_TEXT; ?>"
							   value="<?php echo esc_attr( get_option( RSVP_PRO_GLOBAL_OPTION_ATTENDEE_LIST_GREETING_TEXT ) ); ?>"
							   class="regular-text"/>
						<br/>
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'attendee_list_greeting_description' ); ?></span>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo RSVP_PRO_GLOBAL_OPTION_ATTENDEE_RSVP_FOR_TEXT; ?>"><?php echo rsvp_pro_get_admin_string( 'attendee_list_rsvp_for_label' ); ?></label>
					</th>
					<td>
						<input type="text" name="<?php echo RSVP_PRO_GLOBAL_OPTION_ATTENDEE_RSVP_FOR_TEXT; ?>"
							   id="<?php echo RSVP_PRO_GLOBAL_OPTION_ATTENDEE_RSVP_FOR_TEXT; ?>"
							   value="<?php echo esc_attr( get_option( RSVP_PRO_GLOBAL_OPTION_ATTENDEE_RSVP_FOR_TEXT ) ); ?>"
							   class="regular-text"/>
						<br/>
						<span class="description"><?php echo rsvp_pro_get_admin_string( 'attendee_list_rsvp_for_description' ); ?></span>
					</td>
				</tr>
				</tbody>
			</table>
			<input type="hidden" name="action" value="update"/>
			<p class="submit">
				<input type="submit" class="button-primary"
					   value="<?php echo rsvp_pro_get_admin_string( 'save_label' ); ?>"/>
			</p>
		</form>
	</div>
	<?php
}

/**
 * Shows the form for importing in events
 *
 * @since 2.5.7
 */
function rsvp_pro_import_events(){
	global $wpdb;

	if ( isset( $_FILES['import_file'] ) && isset( $_POST['_wpnonce'] ) &&
		 wp_verify_nonce( $_POST['_wpnonce'], 'import_events' ) &&
		 is_uploaded_file( $_FILES['import_file']['tmp_name'] ) ){
		// Get custom question types...
		$sql            = 'SELECT questionType, id FROM ' . PRO_QUESTION_TYPE_TABLE;
		$question_types = array();
		$qts            = $wpdb->get_results( $sql );
		foreach ( $qts as $qt ){
			$question_types[ stripslashes( $qt->questionType ) ] = $qt->id;
		}

		$events = json_decode( file_get_contents( $_FILES['import_file']['tmp_name'] ) );
		foreach ( $events as $e ){
			// insert in event
			$wpdb->insert(
					PRO_EVENT_TABLE,
					array(
							'eventName'             => $e->eventName,
							'open_date'             => $e->open_date,
							'close_date'            => $e->close_date,
							'options'               => $e->options,
							'event_access'          => $e->event_access,
							'eventStartDate'        => $e->eventStartDate,
							'eventEndDate'          => $e->eventEndDate,
							'eventLocation'         => $e->eventLocation,
							'eventDescription'      => $e->eventDescription,
							'repeatStartDate'       => $e->repeatStartDate,
							'repeatEndDate'         => $e->repeatEndDate,
							'repeatFrequencyType'   => $e->repeatFrequencyType,
							'repeatFrequency'       => $e->repeatFrequency,
							'eventLength'           => $e->eventLength,
							'eventLengthType'       => $e->eventLengthType,
							'currentRepeatEndDate'  => $e->currentRepeatEndDate,
							'open_date_timezone'    => $e->open_date_timezone,
							'open_date_time'        => $e->open_date_time,
							'close_date_timezone'   => $e->close_date_timezone,
							'close_date_time'       => $e->close_date_time,
							'attendee_list_sent_on' => $e->attendee_list_sent_on,
							'send_attendee_list'    => $e->send_attendee_list,
							'attendee_columns'      => $e->attendee_columns,
					),
					array(
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
					)
			);
			$new_event_id = $wpdb->insert_id;

			// insert in custom questions
			rsvp_pro_import_event_custom_question( $e->custom_questions, $new_event_id, $question_types );

			// insert in reminders
			foreach ( $e->reminders as $r ){
				$wpdb->insert(
						PRO_EVENT_REMINDERS_TABLE,
						array(
								'rsvpEventID'    => $new_event_id,
								'name'           => $r->name,
								'timeType'       => $r->timeType,
								'sendOn'         => $r->sendOn,
								'period'         => $r->period,
								'rsvpStatuses'   => $r->rsvpStatuses,
								'messageBody'    => $r->messageBody,
								'messageSubject' => $r->messageSubject,
						),
						array( '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s' )
				);
			}

			// insert in sub-events
			foreach ( $e->sub_events as $se ){
				if ( isset( $se->eventName ) && ( $se->eventName != '' ) ){
					// insert in event
					$wpdb->insert(
							PRO_EVENT_TABLE,
							array(
									'eventName'             => $se->eventName,
									'open_date'             => $se->open_date,
									'close_date'            => $se->close_date,
									'options'               => $se->options,
									'event_access'          => $se->event_access,
									'eventStartDate'        => $se->eventStartDate,
									'eventEndDate'          => $se->eventEndDate,
									'eventLocation'         => $se->eventLocation,
									'eventDescription'      => $se->eventDescription,
									'repeatStartDate'       => $se->repeatStartDate,
									'repeatEndDate'         => $se->repeatEndDate,
									'repeatFrequencyType'   => $se->repeatFrequencyType,
									'repeatFrequency'       => $se->repeatFrequency,
									'eventLength'           => $se->eventLength,
									'eventLengthType'       => $se->eventLengthType,
									'currentRepeatEndDate'  => $se->currentRepeatEndDate,
									'open_date_timezone'    => $se->open_date_timezone,
									'open_date_time'        => $se->open_date_time,
									'close_date_timezone'   => $se->close_date_timezone,
									'close_date_time'       => $se->close_date_time,
									'attendee_list_sent_on' => $se->attendee_list_sent_on,
									'send_attendee_list'    => $se->send_attendee_list,
									'parentEventID'         => $new_event_id,
							),
							array(
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%s',
									'%d',
							)
					);

					$subevent_id = $wpdb->insert_id;

					rsvp_pro_import_event_custom_question( $se->custom_questions, $subevent_id, $question_types );
				}
			}
		} // foreach($events as $e) {
		?>
		<div class="wrap">
			<p>
				<?php echo rsvp_pro_get_admin_string( 'events_imported_label' ); ?>
			</p>
		</div>
		<?php
	} else {
		?>
		<div class="wrap">
			<h1><?php echo rsvp_pro_get_admin_string( 'rsvp_pro_import_events_label' ); ?></h1>
			<form method="post" enctype="multipart/form-data">
				<?php wp_nonce_field( 'import_events' ); ?>
				<p>
					<label><?php echo rsvp_pro_get_admin_string( 'select_file_import_label' ); ?></label><br/>
					<input type="file" name="import_file"/>
				</p>
				<p class="submit">
					<input type="submit" class="button-primary"
						   value="<?php echo rsvp_pro_get_admin_string( 'import_events_label' ); ?>"/>
				</p>
			</form>
		</div>
		<?php
	}
}

function rsvp_pro_import_event_custom_question( $custom_questions, $event_id, $question_types ){
	global $wpdb;

	foreach ( $custom_questions as $cq ){
		$wpdb->insert(
				PRO_QUESTIONS_TABLE,
				array(
						'question'        => $cq->question,
						'sortOrder'       => $cq->sortOrder,
						'questionTypeID'  => $question_types[ $cq->questionType ],
						'permissionLevel' => $cq->permissionLevel,
						'grouping'        => $cq->grouping,
						'required'        => $cq->required,
						'required_text'   => $cq->required_text,
						'rsvpEventID'     => $event_id,
				),
				array( '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%d' )
		);

		$cq_id = $wpdb->insert_id;

		if ( is_array( $cq->answers ) && ( count( $cq->answers ) > 0 ) ){
			foreach ( $cq->answers as $a ){
				$wpdb->insert(
						PRO_QUESTION_ANSWERS_TABLE,
						array(
								'answer'        => $a->answer,
								'defaultAnswer' => $a->defaultAnswer,
								'questionID'    => $cq_id,
						),
						array( '%s', '%s', '%d' )
				);
			}
		} // if( is_array( $cq->answers ) && ( count( $cq->answers ) > 0 ) ) {
	}
}

/**
 * Displays a form to select which events you want to export and then allow you to export them.
 *
 * @since 2.5.7
 */
function rsvp_pro_export_events(){
	global $wpdb;
	?>
	<div class="wrap">
		<h1><?php echo rsvp_pro_get_admin_string( 'export_events_header' ); ?></h1>
		<form method="post">
			<p>
				<label for="events_to_export"><?php echo rsvp_pro_get_admin_string( 'select_events_exported_label' ); ?></label><br/>
				<select name="events[]" id="events_to_export" multiple="multiple">
					<?php
					$sql    = 'SELECT e.id, e.eventName, pe.eventName AS parentEvent
						FROM ' . PRO_EVENT_TABLE . ' e
						LEFT JOIN ' . PRO_EVENT_TABLE . ' pe ON pe.id = e.parentEventID 
						WHERE e.id <> ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID;
					$events = $wpdb->get_results( $sql );
					foreach ( $events as $e ){
						?>
						<option value="<?php echo $e->id; ?>"><?php echo esc_html( stripslashes( $e->eventName ) ); ?>
							<?php
							if ( $e->parentEvent != '' ){
								echo rsvp_pro_get_admin_string( 'export_parent_is_label' );
								echo esc_html( stripslashes( $e->parentEvent ) );
							}
							?>
						</option>
						<?php
					}
					?>
				</select>
				<br/>
			<p>
				<input type="checkbox" name="incldue_attendee_info" id="include_attendee_info" value="Y"/>
				<label for="include_attendee_info"><?php echo rsvp_pro_get_admin_string( 'export_event_attendee_label' ); ?></label>
			</p>
			</p>

			<p class="submit">
				<input type="hidden" name="page" value="rsvp-pro-export-events"/>
				<input type="hidden" name="action" value="do_event_export"/>
				<input type="submit" class="button-primary"
					   value="<?php echo rsvp_pro_get_admin_string( 'export_events_label' ); ?>"/>
			</p>
		</form>
	</div>
	<?php
}

/**
 * RSVP Pro exports the events selected to a JSON file for people to use.
 *
 * @since 2.5.6
 */
function rsvp_pro_admin_event_export(){
	global $wpdb;

	$events = array();

	if ( isset( $_POST['events'] ) ){
		$tmpEvents = '';
		if ( !is_array( $_POST['events'] ) ){
			$tmpEvents = explode( ',', $_POST['events'] );
		} else {
			$tmpEvents = $_POST['events'];
		}

		$include_attendee_info = ( isset( $_POST['incldue_attendee_info'] ) && ( 'Y' === $_POST['incldue_attendee_info'] ) ) ? true : false;

		foreach ( $tmpEvents as $id ){
			if ( is_numeric( $id ) && ( $id > 0 ) && ( rsvp_pro_is_sub_event( $id ) === false ) ){
				// Get general information.
				$event = rsvp_pro_export_get_event_information( $id );

				// reminders.
				$reminders = array();
				$sql       = 'SELECT name, timeType, sendOn, period,
						rsvpStatuses, messageBody, messageSubject
					FROM ' . PRO_EVENT_REMINDERS_TABLE . '
					WHERE rsvpEventID = %d ';
				$r_data    = $wpdb->get_results( $wpdb->prepare( $sql, $id ) );
				foreach ( $r_data as $r ){
					$tmp_r                   = array();
					$tmp_r['name']           = stripslashes( $r->name );
					$tmp_r['timeType']       = stripslashes( $r->timeType );
					$tmp_r['sendOn']         = stripslashes( $r->sendOn );
					$tmp_r['period']         = stripslashes( $r->period );
					$tmp_r['rsvpStatuses']   = stripslashes( $r->rsvpStatuses );
					$tmp_r['messageBody']    = stripslashes( $r->messageBody );
					$tmp_r['messageSubject'] = stripslashes( $r->messageSubject );
					$reminders[ uniqid() ]   = $tmp_r;
				}
				$event['reminders'] = $reminders;

				$event['custom_questions'] = rsvp_pro_export_get_custom_question_information( $id );

				if ( $include_attendee_info ){
					$event['attendees'] = rsvp_pro_export_get_attendee_information( $id );
				}

				// sub_events
				$subevents = array();
				$sql       = 'SELECT id FROM ' . PRO_EVENT_TABLE . ' WHERE parentEventID = %d ';
				$subevents = $wpdb->get_results( $wpdb->prepare( $sql, $id ) );
				foreach ( $subevents as $se ){
					if ( in_array( $se->id, $tmpEvents ) === true ){
						$sub = rsvp_pro_export_get_event_information( $se->id );

						$sub['custom_questions'] = rsvp_pro_export_get_custom_question_information( $se->id );

						if ( $include_attendee_info ){
							$subevents['attendees'] = rsvp_pro_export_get_attendee_information( $se->id );
						}

						$subevents[ uniqid() ] = $sub;
					}
				}
				$event['sub_events'] = $subevents;
				$events[ uniqid() ]  = $event;
			}
		}
	}

	if ( isset( $_SERVER['HTTP_USER_AGENT'] ) && preg_match( '/MSIE/', $_SERVER['HTTP_USER_AGENT'] ) ){
		// IE Bug in download name workaround
		ini_set( 'zlib.output_compression', 'Off' );
	}
	header( 'Content-Description: RSVP Event export' );
	header( 'Content-Type: application/json', true );
	header( 'Content-Disposition: attachment; filename="rsvp_event_export.json"' );
	echo json_encode( $events );
	exit();
}

/**
 * Gets the event information for a given ID
 *
 * @param int $rsvpEventId The RSVP event we want to get the information for
 *
 * @return array             The event information returned as an array
 */
function rsvp_pro_export_get_event_information( $rsvpEventId ){
	global $wpdb;

	$event = array();

	$sql                            = 'SELECT eventName, open_date, close_date, options,
			event_access, eventStartDate, eventEndDate, eventLocation,
			eventDescription, repeatStartDate, repeatEndDate, repeatFrequencyType,
			repeatFrequency, eventLength, eventLengthType, currentRepeatEndDate,
			open_date_timezone, open_date_time, close_date_timezone, close_date_time,
			attendee_list_sent_on, send_attendee_list, attendee_columns
			FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
	$event_info                     = $wpdb->get_row( $wpdb->prepare( $sql, $rsvpEventId ) );
	$event['eventName']             = stripslashes( $event_info->eventName );
	$event['open_date']             = stripslashes( $event_info->open_date );
	$event['close_date']            = stripslashes( $event_info->close_date );
	$event['options']               = $event_info->options;
	$event['event_access']          = stripslashes( $event_info->event_access );
	$event['eventStartDate']        = stripslashes( $event_info->eventStartDate );
	$event['eventEndDate']          = stripslashes( $event_info->eventEndDate );
	$event['eventLocation']         = stripslashes( $event_info->eventLocation );
	$event['eventDescription']      = stripslashes( $event_info->eventDescription );
	$event['repeatStartDate']       = stripslashes( $event_info->repeatStartDate );
	$event['repeatEndDate']         = stripslashes( $event_info->repeatEndDate );
	$event['repeatFrequencyType']   = stripslashes( $event_info->repeatFrequencyType );
	$event['repeatFrequency']       = stripslashes( $event_info->repeatFrequency );
	$event['eventLength']           = stripslashes( $event_info->eventLength );
	$event['eventLengthType']       = stripslashes( $event_info->eventLengthType );
	$event['currentRepeatEndDate']  = stripslashes( $event_info->currentRepeatEndDate );
	$event['open_date_timezone']    = stripslashes( $event_info->open_date_timezone );
	$event['open_date_time']        = stripslashes( $event_info->open_date_time );
	$event['close_date_timezone']   = stripslashes( $event_info->close_date_timezone );
	$event['close_date_time']       = stripslashes( $event_info->close_date_time );
	$event['attendee_list_sent_on'] = stripslashes( $event_info->attendee_list_sent_on );
	$event['send_attendee_list']    = stripslashes( $event_info->send_attendee_list );
	$event['attendee_columns']      = stripslashes( $event_info->attendee_columns );

	return $event;
}

/**
 * Gets the custom questions for exporting for a given event
 *
 * @param int $rsvpEventId The we need to get the custom question information for
 *
 * @return array              The custom question information including answers
 */
function rsvp_pro_export_get_custom_question_information( $rsvpEventId ){
	global $wpdb;

	$custom_questions = array();
	$sql              = 'SELECT q.id, question, questionType, sortOrder,
			permissionLevel, `grouping`, required, required_text
			FROM ' . PRO_QUESTIONS_TABLE . ' q
			INNER JOIN ' . PRO_QUESTION_TYPE_TABLE . ' qt ON qt.id = q.questionTypeID
			WHERE q.rsvpEventID = %d';
	$cqs              = $wpdb->get_results( $wpdb->prepare( $sql, $rsvpEventId ) );
	foreach ( $cqs as $cq ){
		$tmp_cq                    = array();
		$tmp_cq['question']        = stripslashes( $cq->question );
		$tmp_cq['questionType']    = stripslashes( $cq->questionType );
		$tmp_cq['sortOrder']       = stripslashes( $cq->sortOrder );
		$tmp_cq['permissionLevel'] = stripslashes( $cq->permissionLevel );
		$tmp_cq['grouping']        = stripslashes( $cq->grouping );
		$tmp_cq['required']        = stripslashes( $cq->required );
		$tmp_cq['required_text']   = stripslashes( $cq->required_text );

		$tmp_answers = array();
		$sql         = 'SELECT answer, defaultAnswer FROM ' . PRO_QUESTION_ANSWERS_TABLE . '
			  WHERE questionID = %d';
		$answers     = $wpdb->get_results( $wpdb->prepare( $sql, $cq->id ) );
		foreach ( $answers as $a ){
			$tmp_a                  = array();
			$tmp_a['answer']        = stripslashes( $a->answer );
			$tmp_a['defaultAnswer'] = $a->defaultAnswer;

			$tmp_answers[ uniqid() ] = $tmp_a;
		}
		$tmp_cq['answers']            = $tmp_answers;
		$custom_questions[ uniqid() ] = $tmp_cq;
	}

	return $custom_questions;
}

/**
 * Retrieves all of the attendees for an event and prepares it for the event export functionality.
 *
 * @param int $event_id The event ID we want to get the attendee information for.
 *
 * @return array         An array of attendee information.
 */
function rsvp_pro_export_get_attendee_information( $event_id ){
	global $wpdb;
	$attendees           = array();
	$global_list_enabled = rsvp_pro_is_shared_attendee_list_enabled();

	if ( rsvp_pro_is_sub_event( $event_id ) ){
		$sql = "SELECT a.id, firstName, lastName, IFNULL(se.rsvpStatus, 'NoResponse') AS rsvpStatus,
			note, additionalAttendee, passcode, alternate_passcode, email, salutation, suffix,
			a.rsvpDate, a.primaryAttendee, a.numGuests, a.personalGreeting, se.checked_in
			FROM " . PRO_ATTENDEES_TABLE . ' a
			INNER JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = %d
			LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d
			WHERE ( (a.rsvpEventID = %d) ';

		if ( $global_list_enabled ){
			$sql .= ' OR ( a.rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . ') ';
		}

		$sql .= " ) AND ((IFNULL(e.event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "') != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "') OR (a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = e.id)))';

		$attendees_information = $wpdb->get_results( $wpdb->prepare( $sql, $event_id, $event_id, rsvp_pro_get_parent_event_id( $event_id ) ) );
	} else {
		$sql = 'SELECT a.id, firstName, lastName, IFNULL(se.rsvpStatus, a.rsvpStatus) as rsvpStatus, 
				note, additionalAttendee,
				passcode, alternate_passcode, email, salutation, suffix, IFNULL(se.rsvpDate, a.rsvpDate) as rsvpDate, 
				a.primaryAttendee,
				a.numGuests, a.personalGreeting, IFNULL(se.checked_in, a.checked_in) AS checked_in
				FROM ' . PRO_ATTENDEES_TABLE . ' a
				INNER JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = a.rsvpEventID
				LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d
				WHERE ( (a.rsvpEventID = %d) ';

		if ( $global_list_enabled ){
			$sql .= ' OR ( a.rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . ') ';
		}

		$sql .= ' ) ';

		$sql                   .= "AND ((IFNULL(e.event_access, '" . RSVP_PRO_OPEN_EVENT_ACCESS . "') != '" . RSVP_PRO_PRIVATE_EVENT_ACCESS . "') OR
			(a.id IN (SELECT rsvpAttendeeID FROM " . PRO_EVENT_ATTENDEE_TABLE . ' WHERE rsvpEventID = e.id)))';
		$attendees_information = $wpdb->get_results( $wpdb->prepare( $sql, $event_id, $event_id ) );
	}

	foreach ( $attendees_information as $ai ){
		$tmp_a                        = array();
		$tmp_a['first_name']          = stripslashes_deep( $ai->firstName );
		$tmp_a['last_name']           = stripslashes_deep( $ai->lastName );
		$tmp_a['rsvp_status']         = stripslashes_deep( $ai->rsvpStatus );
		$tmp_a['note']                = stripslashes_deep( $ai->note );
		$tmp_a['additional_attendee'] = stripslashes_deep( $ai->additionalAttendee );
		$tmp_a['passcode']            = stripslashes_deep( $ai->passcode );
		$tmp_a['alternate_passcode']  = stripslashes_deep( $ai->alternate_passcode );
		$tmp_a['email']               = stripslashes_deep( $ai->email );
		$tmp_a['salutation']          = stripslashes_deep( $ai->salutation );
		$tmp_a['suffix']              = stripslashes_deep( $ai->suffix );
		$tmp_a['rsvp_date']           = stripslashes_deep( $ai->rsvpDate );
		$tmp_a['primary_attendee']    = stripslashes_deep( $ai->primaryAttendee );
		$tmp_a['num_guests']          = stripslashes_deep( $ai->numGuests );
		$tmp_a['personal_greeting']   = stripslashes_deep( $ai->personalGreeting );
		$tmp_a['checked_in']          = stripslashes_deep( $ai->checked_in );

		$sql              = 'SELECT question, answer FROM ' . PRO_ATTENDEE_ANSWERS . ' a 
		INNER JOIN ' . PRO_QUESTIONS_TABLE . ' q ON q.id = a.questionID 
		WHERE a.attendeeID = %d';
		$custom_questions = array();
		$tmp_questions    = $wpdb->get_results( $wpdb->prepare( $sql, $ai->id ) );
		foreach ( $tmp_questions as $cq ){
			$tmp_q['question'] = stripslashes_deep( $cq->question );
			$tmp_q['answer']   = stripslashes_deep( $cq->answer );

			$custom_questions[ uniqid() ] = $tmp_q;
		}

		$tmp_a['custom_questions'] = $custom_questions;
		$attendees[ uniqid() ]     = $tmp_a;
	}

	return $attendees;
}

/**
 * Wires up the menus in the admin area for the RSVP Pro plugin.
 */
function rsvp_pro_modify_menu(){
	add_menu_page(
			'RSVP Pro',
			'RSVP Pro',
			'publish_posts',
			'rsvp-pro-top-level',
			'rsvp_pro_admin_events',
			plugins_url( 'images/rsvp_pro_icon_16_x_16.png', RSVP_PRO_PLUGIN_FILE )
	);

	add_submenu_page(
			'rsvp-pro-top-level',
			__( 'Events', 'rsvp-pro-plugin' ),
			__( 'Events', 'rsvp-pro-plugin' ),
			'publish_posts',
			'rsvp-pro-top-level',
			'rsvp_pro_admin_events'
	);

	add_submenu_page(
			'rsvp-pro-top-level',
			rsvp_pro_get_admin_string( 'event_management_label' ),
			rsvp_pro_get_admin_string( 'add_events' ),
			'publish_posts',
			'rsvp-pro-admin-manage-event',
			'rsvp_pro_admin_manage_event'
	);

	add_submenu_page(
			'rsvp-pro-top-level',
			rsvp_pro_get_admin_string( 'rsvp_general_settings_label' ),
			rsvp_pro_get_admin_string( 'general_settings_label' ),
			'publish_posts',
			'rsvp-pro-global-options',
			'rsvp_pro_global_options'
	);

	add_submenu_page(
			'rsvp-pro-top-level',
			rsvp_pro_get_admin_string( 'export_events_label' ),
			rsvp_pro_get_admin_string( 'export_events_label' ),
			'publish_posts',
			'rsvp-pro-export-events',
			'rsvp_pro_export_events'
	);

	add_submenu_page(
			'rsvp-pro-top-level',
			rsvp_pro_get_admin_string( 'import_events_label' ),
			rsvp_pro_get_admin_string( 'import_events_label' ),
			'publish_posts',
			'rsvp-pro-import-events',
			'rsvp_pro_import_events'
	);

	if ( !rsvp_pro_is_network_activated() ){
		add_submenu_page(
				'rsvp-pro-top-level',
				rsvp_pro_get_admin_string( 'rsvp_pro_plugin_license_label' ),
				rsvp_pro_get_admin_string( 'rsvp_pro_plugin_license_label' ),
				'manage_options',
				'rsvppro-license',
				'rsvp_pro_license_page'
		);
	}
}

/**
 * Displays the license menu option when it is a multisite install. We only want this displayed
 * in the network admin area and not every multisite.
 */
function rsvp_pro_modify_multiesite_menu(){
	add_submenu_page(
			'rsvp-pro-top-level',
			rsvp_pro_get_admin_string( 'rsvp_pro_plugin_license_label' ),
			rsvp_pro_get_admin_string( 'rsvp_pro_plugin_license_label' ),
			'manage_options',
			'rsvppro-license',
			'rsvp_pro_license_page'
	);
}

/**
 * Displayes and handles the licensing UI for people to enter in their licenses for
 * the RSVP Pro plugin and additional extensions.
 */
function rsvp_pro_license_page(){
	if ( isset( $_POST ) &&
		 isset( $_POST['rsvp_pro_license_key'] ) &&
		 check_admin_referer( 'rsvp_pro_license_nonce', 'rsvp_pro_license_nonce' ) ){
		rsvp_pro_update_option_license( 'rsvp_pro_license_key', $_POST['rsvp_pro_license_key'] );
		if ( !isset( $_POST['rsvp_pro_license_deactivate'] ) ){
			$_POST['rsvp_pro_license_activate'] = 'Activate License';
			rsvp_pro_activate_license();
		}

		do_action( 'rsvp_pro_licensing_form_handler' );
	}

	$license = rsvp_pro_get_option_license( 'rsvp_pro_license_key' );
	$status  = rsvp_pro_get_option_license( 'rsvp_pro_license_status' );
	?>
	<div class="wrap">
		<h1><?php _e( 'RSVP Pro Plugin License Options', 'rsvp-pro-plugin' ); ?></h1>
		<form method="post">
			<?php wp_nonce_field( 'rsvp_pro_license_nonce', 'rsvp_pro_license_nonce' ); ?>
			<?php settings_fields( 'rsvppro-license' ); ?>

			<table class="form-table">
				<tbody>
				<tr valign="top">
					<th scope="row" valign="top"><?php _e( 'License Key', 'rsvp-pro-plugin' ); ?></th>
					<td>
						<input id="rsvp_pro_license_key" name="rsvp_pro_license_key" type="text" class="regular-text"
							   value="<?php echo esc_attr( $license ); ?>"/>
						<label class="description"
							   for="rsvp_pro_license_key"><?php echo rsvp_pro_get_admin_string( 'enter_license_key_label' ); ?></label>
					</td>
				</tr>
				<?php if ( false !== $license ){ ?>
					<tr valign="top">
						<th scope="row" valign="top">
							<?php _e( 'Activate License', 'rsvp-pro-plugin' ); ?>
						</th>
						<td>
							<?php if ( $status !== false && $status == 'valid' ){ ?>
								<span style="color:green;"><?php echo rsvp_pro_get_admin_string( 'active_label' ); ?></span>
								<input type="submit" class="button-secondary" name="rsvp_pro_license_deactivate"
									   value="<?php echo rsvp_pro_get_admin_string( 'deactivate_license_label' ); ?>"/>
							<?php } else { ?>
								<input type="submit" class="button-secondary" name="rsvp_pro_license_activate"
									   value="<?php echo rsvp_pro_get_admin_string( 'activate_license_label' ); ?>"/>
							<?php } ?>
						</td>
					</tr>
				<?php } ?>
				<?php do_action( 'rsvp_pro_licensing_form_display' ); ?>
				</tbody>
			</table>
			<?php submit_button(); ?>
		</form>
	</div>
	<?php
}

function rsvp_pro_generate_calendar_invite( $rsvp_event_id ){
	global $wpdb;

	$invite = rsvp_pro_retrieve_calendar_invite_content( $rsvp_event_id );

	if ( !empty( $invite ) ){
		header( 'Content-type:text/calendar' );
		header( 'Content-Disposition: attachment; filename="' . rsvp_pro_get_event_information( $rsvp_event_id, RSVP_PRO_INFO_EVENT_NAME ) . '.ics"' );
		Header( 'Content-Length: ' . strlen( $invite ) );
		Header( 'Connection: close' );
		echo $invite;
		exit();
	}
}

function rsvp_pro_retrieve_calendar_invite_content( $event_id ){
	global $wpdb;

	$sql        = 'SELECT id, eventName, eventStartDate, eventEndDate, eventLocation, eventDescription
			FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d';
	$event_info = $wpdb->get_row( $wpdb->prepare( $sql, $event_id ) );
	if ( $event_info ){
		$invite = "BEGIN:VCALENDAR\r\n" .
				  "VERSION:2.0\r\n" .
				  "METHOD:PUBLISH\r\n";

		$invite .= "BEGIN:VEVENT\r\n" .
				   'DTSTART:' . rsvp_pro_get_timezone_set_date_for_calendar( $event_info->eventStartDate ) . "\r\n" .
				   'DTEND:' . rsvp_pro_get_timezone_set_date_for_calendar( $event_info->eventEndDate ) . "\r\n" .
				   'LOCATION:' . stripslashes( $event_info->eventLocation ) . "\r\n" .
				   "TRANSP: OPAQUE\r\n" .
				   "SEQUENCE:0\r\n" .
				   'DTSTAMP:' . date( 'Ymd\THis\Z' ) . "\r\n" .
				   'SUMMARY:' . stripslashes( $event_info->eventName ) . "\r\n" .
				   'DESCRIPTION:' . str_replace( "\r\n", "\\n", stripslashes( $event_info->eventDescription ) ) . "\r\n" .
				   "PRIORITY:1\r\n" .
				   "CLASS:PUBLIC\r\n" .
				   "END:VEVENT\r\n";

		$invite .= "END:VCALENDAR\r\n";

		return $invite;
	}

	return '';
}

/**
 * Sends the attendee list out to an email address.
 *
 * @param int  $rsvp_id            The event we want to send the information out for.
 * @param bool $update_sent_date   Specifies if the sent date should be updated,
 *                                 we do not want to update it in case of manual sending.
 *
 * @since 2.3.5
 */
function rsvp_pro_send_attendee_list_notifications( $rsvp_id, $update_sent_date = true ){
	global $wpdb;

	if ( $rsvp_id > 0 ){
		$row_format = rsvp_pro_get_event_option( $rsvp_id, RSVP_PRO_OPTION_SEND_ATTENDEE_LIST_FORMAT );
		$email_to   = rsvp_pro_get_event_option( $rsvp_id, RSVP_PRO_OPTION_SEND_ATTENDEE_LIST_EMAIL );
		if ( empty( $email_to ) ){
			$email_to = rsvp_pro_get_event_option( $rsvp_id, RSVP_PRO_OPTION_NOTIFY_EMAIL );
		}
		$subject = rsvp_pro_get_admin_string( 'attendee_list_for_label' );
		$subject .= rsvp_pro_get_event_information( $rsvp_id, RSVP_PRO_INFO_EVENT_NAME );
		$body    = rsvp_pro_get_event_option( $rsvp_id, RSVP_PRO_OPTION_SEND_ATTENDEE_LIST_NOTE );

		if ( !empty( $body ) ){
			$body .= "\r\n\r\n";
		}

		$sql = 'SELECT a.id, firstName, lastName, IFNULL(se.rsvpStatus, a.rsvpStatus) as rsvpStatus,
            note, passcode, email, salutation, suffix, IFNULL(se.rsvpDate, a.rsvpDate) as rsvpDate, a.token
			FROM ' . PRO_ATTENDEES_TABLE . ' a
            LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpAttendeeID = a.id AND se.rsvpEventID = %d
            WHERE ( (a.rsvpEventID = %d) ';

		if ( rsvp_pro_is_shared_attendee_list_enabled() ){
			$sql .= ' OR ( a.rsvpEventID = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . ' ) ';
		}

		$sql       .= " ) AND ( (a.rsvpStatus = 'Yes') OR ( se.rsvpStatus = 'Yes') OR (a.rsvpStatus = 'PlusOne') OR (se.rsvpStatus = 'PlusOne') )";
		$attendees = $wpdb->get_results( $wpdb->prepare( $sql, $rsvp_id, $rsvp_id ) );
		$tmp_array = array();
		foreach ( $attendees as $a ){
			$body .= rsvp_pro_admin_replaceVariablesForEmail( $a, '', $row_format, $rsvp_id, $tmp_array ) . "\r\n";
		}

		rsvp_pro_send_mail( $email_to, $subject, $body );

		if ( $update_sent_date ){
			$wpdb->update(
					PRO_EVENT_TABLE,
					array( 'attendee_list_sent_on' => date( 'Y-m-d H:i:s' ) ),
					array( 'id' => $rsvp_id ),
					array( '%s' ),
					array( '%d' )
			);
		}
	}
}

/**
 * This checks to see if the global attendee event ID exists and if not it is added.
 *
 * @since 3.3.8
 */
function rsvp_pro_insert_global_event(){
	global $wpdb;

	$sql = 'SELECT id FROM ' . PRO_EVENT_TABLE . ' WHERE id = ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID;
	$id  = $wpdb->get_var( $sql );
	if ( $id == null ){
		$wpdb->insert(
				PRO_EVENT_TABLE,
				array(
						'eventName' => 'Global Attendee Event List',
						'id'        => RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID,
				),
				array( '%s', '%d' )
		);
	}
}

/**
 * Registers actions and settings that should only be used for the admin area.
 */
function rsvp_pro_register_settings(){
	add_action( 'wp_ajax_rsvp_pro_get_event_list', 'rsvp_pro_get_event_list' );
	add_action( 'wp_ajax_rsvp_pro_has_passcode_been_used', 'rsvp_pro_has_passcode_been_used' );
	add_action( 'wp_ajax_nopriv_rsvp_pro_has_passcode_been_used', 'rsvp_pro_has_passcode_been_used' );
	add_action( 'wp_ajax_rsvp_pro_unique_email_validation', 'rsvp_pro_unique_email_validation' );
	add_action( 'wp_ajax_nopriv_rsvp_pro_unique_email_validation', 'rsvp_pro_unique_email_validation' );

	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_DELETE_TABLES );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_STYLES );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_PAGE );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_AUTO_CREATE_ATTENDEE_LIST );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_DISABLE_COMMENTS );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_ADD_ATTENDEE_LIST_TO_PAGE );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_AUTO_POST_TYPE );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_ENABLE_GLOBAL_ATTENDEE_LIST );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_ENABLE_ATTENDEE_CHANGELOG );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_NUM_ATTENDEES_PER_PAGE );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_ATTENDEE_LIST_GREETING_TEXT );
	register_setting( 'rsvp-pro-option-group', RSVP_PRO_GLOBAL_OPTION_ATTENDEE_RSVP_FOR_TEXT );
}

function rsvp_pro_admin_scripts(){

	$screen = get_current_screen();
	if ( strpos( $screen->base, 'rsvp-pro' ) !== false ){
		wp_enqueue_style( 'rsvp_pro_admin_css' );
		wp_enqueue_script( 'jquery-ui-core' );
		wp_enqueue_script( 'jquery-ui-tabs' );
		wp_enqueue_script( 'jquery-ui-sortable' );
		wp_enqueue_script( 'jquery-ui-datepicker' );
		wp_register_script( 'jquery_multi_select', plugins_url( 'multi-select/js/jquery.multi-select.js', RSVP_PRO_PLUGIN_FILE ) );
		wp_register_script( 'jquery_timepicker', plugins_url( 'jquery.timepicker.min.js', RSVP_PRO_PLUGIN_FILE ) );

		wp_enqueue_script( 'jquery_multi_select' );
		wp_enqueue_script( 'jquery_timepicker' );

		wp_register_style( 'jquery_multi_select_css', plugins_url( 'multi-select/css/multi-select.css', RSVP_PRO_PLUGIN_FILE ) );
		wp_register_style( 'jquery_timepicker_css', plugins_url( 'jquery.timepicker.min.css', RSVP_PRO_PLUGIN_FILE ) );

		wp_enqueue_style( 'jquery_multi_select_css' );
		wp_enqueue_style( 'jquery_timepicker_css' );
		wp_enqueue_style( 'jquery_ui_stylesheet' );
		wp_enqueue_style( 'jquery-ui-datepicker' );

		wp_register_script( 'rsvp_pro_admin', plugins_url( 'rsvp_pro_plugin_admin.js', RSVP_PRO_PLUGIN_FILE ), array('jquery-ui-sortable'),'',false );
		wp_localize_script(
				'rsvp_pro_admin',
				'rsvp_pro_admin_data',
				array(
						'ajaxurl' => admin_url( 'admin-ajax.php' ),
				)
		);

		wp_enqueue_script( 'rsvp_pro_admin' );
	}
}

add_action( 'admin_enqueue_scripts', 'rsvp_pro_admin_scripts' );

/**
 * Initializes the plugin and resources needed.
 */
function rsvp_pro_init(){
	global $admin_strings;
	global $us_admin_strings;
	global $rsvp_pro_frontend_strings;
	global $us_rsvp_pro_frontend_strings;
	global $rsvp_id;

	wp_register_script( 'jquery_validate', plugins_url( 'jquery.validate.min.js', RSVP_PRO_PLUGIN_FILE ), array( 'jquery' ) );
	wp_register_script( 'rsvp_pro_plugin', plugins_url( 'rsvp_pro_plugin.js', RSVP_PRO_PLUGIN_FILE ) );
	wp_register_style( 'rsvp_pro_css', plugins_url( 'rsvp_pro_plugin.css', RSVP_PRO_PLUGIN_FILE ) );
	wp_register_style( 'rsvp_pro_admin_css', plugins_url( 'rsvp_admin.css', RSVP_PRO_PLUGIN_FILE ) );
	if ( !is_admin() || ( isset( $_GET['page'] ) && ( stripos( $_GET['page'], 'rsvp-pro' ) !== false ) ) ){
		wp_register_style( 'rsvp_pro_jquery_ui_stylesheet', plugins_url( 'jquery-ui.css', RSVP_PRO_PLUGIN_FILE ) );
	}
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'jquery-ui-core' );
	wp_enqueue_script( 'jquery-ui-tabs' );
	wp_enqueue_script( 'jquery-ui-datepicker' );
	wp_enqueue_script( 'jquery_validate' );
	wp_enqueue_script( 'rsvp_pro_plugin', '', array( 'jquery', 'jquery_validate' ), false, true );

	wp_enqueue_style( 'rsvp_pro_css' );
	wp_enqueue_style( 'rsvp_pro_jquery_ui_stylesheet' );
	wp_enqueue_style( 'jquery-ui-datepicker' );

	wp_localize_script(
			'rsvp_pro_plugin',
			'rsvp_pro_translate',
			array( 'errors'  => array( 
					'required' => esc_html__( "This field is required.", 'rsvp-pro-plugin' ),
					'email'    => esc_html__( "Please enter a valid email address.", 'rsvp-pro-plugin' ),
				)
			)
	);

	if ( !is_admin() ){
		wp_enqueue_script(
				'recaptcha_api_js',
				'https://www.google.com/recaptcha/api.js',
				array()
		);
		wp_enqueue_script(
			'rsvp-pro-turnstile-captcha',
			add_query_arg( array( 'onload' => 'onloadRSVPTurnstileCallback' ), 'https://challenges.cloudflare.com/turnstile/v0/api.js' ),
			array()
		);
	}

	$admin_strings             = rsvp_pro_get_admin_strings();
	$rsvp_pro_frontend_strings = rsvp_pro_get_frontend_strings();

	$tmp_locale = get_locale();

	unload_textdomain( 'rsvp-pro-plugin' );
	load_textdomain( 'rsvp-pro-plugin', WP_LANG_DIR . '/rsvp-pro-plugin/rsvp-pro-plugin-en_US.mo' );
	$us_admin_strings             = rsvp_pro_get_admin_strings();
	$us_rsvp_pro_frontend_strings = rsvp_pro_get_frontend_strings();
	unload_textdomain( 'rsvp-pro-plugin' );
	load_textdomain( 'rsvp-pro-plugin', WP_LANG_DIR . '/rsvp-pro-plugin/rsvp-pro-plugin-' . $tmp_locale . '.mo' );

	rsvp_pro_register_strings();
	rsvp_pro_insert_global_event();

	// $payment_gateways[] = new Rsvp_Pro_Stripe_Payment_Gateway();
	$payment_gateways[] = new Rsvp_Pro_PayPal_Payment_Gateway();
}

add_action( 'wp_ajax_get_validation_messages', 'rsvp_pro_ajax_get_validation_messages' );
add_action( 'wp_ajax_nopriv_get_validation_messages', 'rsvp_pro_ajax_get_validation_messages' );
add_action( 'wp_ajax_handle_rsvp_form', 'rsvp_pro_ajax_handle_rsvp_form' );
add_action( 'wp_ajax_nopriv_handle_rsvp_form', 'rsvp_pro_ajax_handle_rsvp_form' );
add_action( 'wp_ajax_rsvp_delete_custom_question_file', 'rsvp_pro_ajax_delete_custom_question_file' );
add_action( 'wp_ajax_noprive_rsvp_delete_custom_question_file', 'rsvp_pro_ajax_delete_custom_question_file' );

/**
 * AJAX endpoint for handling custom question file deletion.
 *
 * @return void The results of the deletion of the custom question.
 */
function rsvp_pro_ajax_delete_custom_question_file(){
	global $wpdb;

	if ( isset( $_POST['attendee_token'] ) && isset( $_POST['qid'] ) ){
		$sql  = 'SELECT aa.id, aa.answer FROM ' . PRO_ATTENDEE_ANSWERS . ' aa ' .
				'LEFT JOIN ' . PRO_ATTENDEES_TABLE . ' a ON a.id = aa.attendeeID ' .
				'LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' ase ON ase.rsvpAttendeeID = aa.attendeeID 
			WHERE aa.questionID = %d AND ( a.token = %s OR ase.token = %s )';
		$file = $wpdb->get_row( $wpdb->prepare( $sql, $_POST['qid'], $_POST['attendee_token'], $_POST['attendee_nonce'] ) );
		if ( false !== $file ){
			wp_delete_attachment( $file->answer );
			$wpdb->delete(
					PRO_ATTENDEE_ANSWERS,
					array( 'id' => $file->id ),
					array( '%d' )
			);
		}
	}
	echo wp_json_encode( array( 'success' => 'success' ) );
	die();
}

/**
 * Handles the shortcode for the RSVP Pro plugin.
 *
 * @param array $atts All of the attributes inside of the shortcode.
 *
 * @return string       The output for this shortcode.
 */
function rsvp_pro_shortcode_handler( $atts ){
	if ( isset( $atts['id'] ) && is_numeric( $atts['id'] ) ){
		try{
			$hide_edit_form = false;
			$hide_new_form  = false;

			if ( isset( $atts['hide_edit_form'] ) && ( $atts['hide_edit_form'] == true ) ){
				$hide_edit_form = true;
			}

			if ( isset( $atts['hide_new_form'] ) && ( $atts['hide_new_form'] == true ) ){
				$hide_new_form = true;
			}

			return rsvp_pro_frontend_handler( "[rsvp-pro-pluginhere-{$atts['id']}]", $hide_edit_form, $hide_new_form );
		}
		catch ( Exception $ex ){
			echo $ex;
		}
	}

	return '';
}

/**
 * The attendee list shortcode handler for the RSVP Pro plugin.
 *
 * @param array $atts An array of all the attributes for this shortcode.
 *
 * @return string       The output for this shortcode.
 */
function rsvp_pro_attendeelist_shortcode_handler( $atts ){
	if ( isset( $atts['id'] ) && is_numeric( $atts['id'] ) ){
		return rsvp_pro_attendeelist_frontend_handler( $atts['id'], $atts );
	}

	return '';
}

/**
 * Shortcode handler for the attendee events list handler.
 *
 * @param array $atts The attributes that got passed in for the short code.
 *
 * @return string       The out from the shortcode handler.
 */
function rsvp_pro_attendee_events_handler( $atts ){
	return rsvp_pro_frontend_attendee_event_list();
}

/**
 * Handles a successful payment from a third-party.
 *
 * @param array $atts Attributes from the shortcode.
 *
 * @return string      The output from the shortcode handler.
 */
function rsvp_pro_payment_success_handler( $atts ){
	return rsvp_pro_payment_success_page();
}

/**
 * THe shortcode handler for payment failures from a third-party.
 *
 * @param array $atts Attributes from the shortcode.
 *
 * @return string      The output from the shortcode handler.
 */
function rsvp_pro_payment_failure_handler( $atts ){
	return rsvp_pro_payment_failure_page();
}

function rsvp_pro_numeric_total( $atts ){
	global $wpdb;

	if ( isset( $atts['id'] ) && is_numeric( $atts['id'] ) ){
		$sql     = 'SELECT answer FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE questionID = %d';
		$answers = $wpdb->get_results( $wpdb->prepare( $sql, $atts['id'] ) );
		$total   = 0;
		foreach ( $answers as $a ){
			if ( is_numeric( $a->answer ) ){
				$total += $a->answer;
			}
		}

		return $total;
	}

	return '';
}

/**
 * The event list shortcode handler for the RSVP Pro plugin.
 *
 * @param array $atts The array of attributes for this shortcode.
 *
 * @return string       The event list for this RSVP Pro plugin instance.
 */
function rsvp_pro_eventlist_shortcode_handler( $atts ){
	return rsvp_pro_eventlist_frontend_handler();
}

/**
 * Schedules events for items that will happen in the background.
 */
function rsvp_pro_scheduler(){
	if ( !wp_next_scheduled( 'rsvp_pro_reoccurring_events' ) ){
		wp_schedule_event( time(), 'hourly', 'rsvp_pro_reoccurring_events' );
	}

	if ( !wp_next_scheduled( 'rsvp_pro_reminder_notifications' ) ){
		wp_schedule_event( time(), 'daily', 'rsvp_pro_reminder_notifications' );
	}

	if ( !wp_next_scheduled( 'rsvp_pro_attendee_list_notifications' ) ){
		wp_schedule_event( time(), 'hourly', 'rsvp_pro_attendee_list_notifications' );
	}
}

function rsvp_pro_add_row_meta_links( $links, $file ){
	if ( $file == 'rsvp-pro-plugin/rsvp-pro.php' ){
		$links[] = '<a href="https://www.rsvpproplugin.com/knowledge-base/">' . rsvp_pro_get_admin_string( 'documentation_label' ) . '</a>';
	}

	return $links;
}

function rsvp_pro_deactivation(){
	wp_clear_scheduled_hook( 'rsvp_pro_reoccurring_events' );
	wp_clear_scheduled_hook( 'rsvp_pro_reminder_notifications' );
	wp_clear_scheduled_hook( 'rsvp_pro_attendee_list_notifications' );
}

function rsvp_pro_add_css(){
	$css = get_option( RSVP_PRO_GLOBAL_OPTION_STYLES );

	if ( !empty( $css ) ){
		$output = '<!-- RSVP Pro Styling -->';
		$output .= '<style type="text/css">' . $css . '</style>';

		echo $output;
	}
}

function rsvp_pro_activation(){
	rsvp_pro_database_setup();
	rsvp_pro_scheduler();
}

function rsvp_pro_calendar_invite_handler(){
	if ( isset( $_GET['rsvp_calendar_download'] ) &&
		 is_numeric( $_GET['rsvp_calendar_download'] ) &&
		 ( $_GET['rsvp_calendar_download'] > 0 )
	){
		rsvp_pro_generate_calendar_invite( $_GET['rsvp_calendar_download'] );
	}
}


/**
 * The data eraser registration that lets the core of WP know
 * we can handle erasing of the RSVP Pro Plugin information
 * if it is ever requested.
 *
 * @param array $erasers The array of erasers already registered with this WP instance.
 *
 * @return array           The erasers array now with the RSVP Pro eraser added.
 */
function rsvp_pro_register_data_eraser( $erasers ){
	$erasers['rsvp-pro-plugin'] = array(
			'eraser_friendly_name' => rsvp_pro_get_admin_string( 'rsvp_pro_friendly_name' ),
			'callback'             => array( 'RSVP_PRO_Admin_Helper', 'data_eraser_handler' ),
	);

	return $erasers;
}

/**
 * Retrieves the custom question and answers for export
 *
 * @param integer $attendee_id  The attendee we want to get the answers for.
 * @param string  $event_name   The event name we atr trying to get the custom questions for.
 * @param integer $event_id     The event ID we are trying to get the custom questions for.
 * @param array   $export_items The current exported items that we need to add to.
 *
 * @return array                 The export items with the custom questions added for the event passed in.
 */
function rsvp_pro_data_exporter_custom_questions( $attendee_id, $event_name, $event_id, $export_items ){
	global $wpdb;

	$sql = 'SELECT answer, question FROM ' . PRO_ATTENDEE_ANSWERS . ' aa 
	JOIN ' . PRO_QUESTIONS_TABLE . ' q ON q.id = aa.questionID 
	WHERE aa.attendeeID = %d AND q.rsvpEventID = %d';

	$custom_questions = $wpdb->get_results( $wpdb->prepare( $sql, $attendee_id, $event_id ) );
	foreach ( $custom_questions as $cq ){
		$export_items[ $event_name . ' - ' . stripslashes( $cq->question ) ] = stripslashes( $cq->answer );
	}

	return $export_items;
}

/**
 * Registers the RSVP Pro data exporter to WP core
 *
 * @param array $exporters The current array of exporters registered with this WP instance.
 *
 * @return array             The exporters array now with the RSVP Pro exporter added.
 */
function rsvp_pro_register_data_exporter( $exporters ){
	$exporters['rsvp-pro-plugin'] = array(
			'exporter_friendly_name' => rsvp_pro_get_admin_string( 'rsvp_pro_friendly_name' ),
			'callback'               => array( 'RSVP_PRO_Admin_Helper', 'data_exporter_handler' ),
	);

	return $exporters;
}


/**
 * Retrieves all of the open events and returns them as an array with each event in a format of:
 *
 * [
 *  'id' => ID_OF_EVENT,
 *  'shortcode' => SHORTCODE_OF_EVENT,
 *  'event_name' => NAME_OF_EVENT
 * ]
 *
 * @return array Each element of the event is in the format described above.
 */
function rsvp_pro_retrieve_open_events(){
	global $wpdb;
	$results = array();

	$sql    = 'SELECT id, eventName FROM ' . PRO_EVENT_TABLE .
			  ' WHERE parentEventID <= 0 AND 
	  ( ( eventEndDate >= ' . date( 'Y-m-d' ) . ' ) OR ( eventEndDate = \'0000-00-00 00:00:00\' ) ) AND
	  id != ' . RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID . '
	ORDER BY eventEndDate';
	$events = $wpdb->get_results( $sql );
	foreach ( $events as $e ){
		$results[] = array(
				'id'         => $e->id,
				'shortcode'  => '[rsvppro id="' . $e->id . '"]',
				'event_name' => stripslashes_deep( $e->eventName ),
		);
	}

	return $results;
}

/**
 * Gets the RSVP Pro Event List and returns it as a JSON array.
 *
 * @return string A JSON array of all events that registration has not past and are main events.
 */
function rsvp_pro_get_event_list(){
	$events = rsvp_pro_retrieve_open_events();

	echo wp_json_encode( $events );
	die();
}

/**
 * Checks to see if a passcode has been used already and if so returns true.
 * This function is used for validation when the feature for making sure a unique
 * passcode is set is turned on.
 *
 * @return boolean True if the passcode has been used, false otherwise.
 */
function rsvp_pro_has_passcode_been_used(){
	global $wpdb;

	$has_been_used = false;

	if ( isset( $_POST['rsvp_id'] ) && is_numeric( $_POST['rsvp_id'] ) && ( 0 <= $_POST['rsvp_id'] ) ){
		$rsvp_id = $_POST['rsvp_id'];
		if ( rsvp_pro_is_sub_event( $rsvp_id ) ){
			$rsvp_id = rsvp_pro_get_parent_event_id( $rsvp_id );
		}

		if ( 'Y' === rsvp_pro_get_event_option( $rsvp_id, RSVP_PRO_OPTION_PASSCODE_UNIQUE ) ){
			$attendee_id = ( isset( $_POST['attendee_id'] ) ) ? $_POST['attendee_id'] : 0;
			$passcode    = ( isset( $_POST['passcode'] ) ) ? $_POST['passcode'] : '';
			$sql         = 'SELECT id FROM ' . PRO_ATTENDEES_TABLE . ' WHERE rsvpEventID = %d AND passcode = %s AND id != %d';
			$tmp_id      = $wpdb->get_var( $wpdb->prepare( $sql, $rsvp_id, $passcode, $attendee_id ) );

			if ( false != $tmp_id ){
				$has_been_used = true;
			}
		}
	}

	echo wp_json_encode( array( 'has_been_used' => $has_been_used ) );
	die();
}

/**
 * Checks to see if the email address has already been used for this event.
 *
 * @return boolean True if the email has been used, false otherwise.
 */
function rsvp_pro_unique_email_validation(){
	global $wpdb;

	$has_been_used = false;

	if ( isset( $_POST['rsvp_id'] ) && is_numeric( $_POST['rsvp_id'] ) && ( 0 <= $_POST['rsvp_id'] ) ){
		$rsvp_id = $_POST['rsvp_id'];
		if ( rsvp_pro_is_sub_event( $rsvp_id ) ){
			$rsvp_id = rsvp_pro_get_parent_event_id( $rsvp_id );
		}

		if ( 'Y' === rsvp_pro_get_event_option( $rsvp_id, RSVP_PRO_OPTION_EMAIL_UNIQUE_VALIDATION ) ){
			$attendee_id = ( isset( $_POST['attendee_id'] ) ) ? $_POST['attendee_id'] : 0;
			$email       = ( isset( $_POST['email'] ) ) ? $_POST['email'] : '';
			$sql         = 'SELECT id FROM ' . PRO_ATTENDEES_TABLE . ' WHERE rsvpEventID = %d AND email = %s AND id != %d';
			$tmp_id      = $wpdb->get_var( $wpdb->prepare( $sql, $rsvp_id, $email, $attendee_id ) );

			if ( false != $tmp_id ){
				$has_been_used = true;
			}
		}
	}

	echo wp_json_encode( array( 'has_been_used' => $has_been_used ) );
	die();
}

/**
 * Adds the privacy policy content to the WordPress privacy policy for this site.
 */
function rsvp_pro_add_privacy_policy_content(){
	if ( !function_exists( 'wp_add_privacy_policy_content' ) ){
		return;
	}

	$content = __(
			'All information entered either from an attendee or a WordPress admin for RSVP 
			Pro events are never sent to external sites. The data stays in database tables 
			on the WordPress instance.',
			'rsvp-pro-plugin'
	);

	wp_add_privacy_policy_content(
			'RSVP Pro Plugin',
			wp_kses_post( wpautop( $content, false ) )
	);
}

/**
 * Handles the bootstrapping of when the plugin is loaded. That includes
 * making sure the database is up to date and any JavaScript variables for
 * the Gutenberg editor are loaded.
 */
function rsvp_pro_plugins_loaded(){
	rsvp_pro_update_db_check();
	add_action( 'enqueue_block_editor_assets', 'rsvp_pro_on_enqueue_block_editor_assets' );

	if ( true === class_exists( 'Haet_Sender_Plugin' ) ){
		require_once RSVP_PRO_PLUGIN_PATH . '/includes/class-rsvp-pro-wp-html-mail.php';
	}
}

/**
 * Enqueue's up the needed items for Gutenberg editor and the RSVP blocks.
 */
function rsvp_pro_on_enqueue_block_editor_assets(){
	wp_enqueue_script(
			'rsvp_pro_gutenberg_widgets',
			plugins_url( 'rsvp_pro_gutenberg_widgets.js', RSVP_PRO_PLUGIN_FILE ),
			array( 'wp-blocks', 'wp-i18n', 'wp-element' ),
			filemtime( plugin_dir_path( RSVP_PRO_PLUGIN_FILE ) . 'rsvp_pro_gutenberg_widgets.js' ),
			$in_footer = true
	);

	$events = array(
			0 => array(
					'value' => 0,
					'label' => __( 'Choose your Event', 'rsvp-pro-plugin' ),
			),
	);

	foreach ( rsvp_pro_retrieve_open_events() as $e ){
		$events[] = array(
				'value' => $e['id'],
				'label' => $e['event_name'],
		);
	}

	wp_localize_script(
			'rsvp_pro_gutenberg_widgets',
			'rsvppro_event_block_params',
			array(
					'events' => $events,
			)
	);
}

/**
 * Displays the license activation message if the license is invalid.
 */
function rsvp_pro_license_notification(){
	if ( 'valid' !== rsvp_pro_check_license() ){
		?>
		<div class="notice">
			<p>
				<?php
				echo sprintf(
						rsvp_pro_get_admin_string( 'invalid_license' ),
						admin_url( 'admin.php?page=rsvppro-license' )
				);
				?>
			</p>
		</div>
		<?php
	}
}

/**
 * This is a bit of a hack. However, depending on the options we will want
 * to redirect when a RSVP submission is entered. So if we detect an RSVP
 * submission we start to buffer the output.
 */
function rsvp_pro_frontend_redirect_buffer(){
	if ( !is_admin() && isset( $_POST['rsvp_nonce_value'] ) ){
		ob_start();
	}
}

/**
 * Adds the RSVP Pro plugin to the HTML Mail plugin.
 *
 * @param array $plugins existing array of plugins.
 *
 * @return array          The array of plugins with the RSVP Pro plugin added to it.
 */
function rsvp_pro_add_to_html_mail_plugins( $plugins ){
	$plugins['rsvppro'] = array(
			'name'         => 'rsvp-pro-plugin',
			'file'         => 'rsvp-pro-plugin/rsvp-pro.php',
			'class'        => 'RSVP_Pro_WP_HTML_Sender_Plugin_RSVP_Pro',
			'display_name' => 'RSVP Pro Plugin',
			'image_url'    => plugins_url( 'images/rsvp_pro_icon.png', RSVP_PRO_PLUGIN_FILE ),
	);
	return $plugins;
}

add_action( 'wp_head', 'rsvp_pro_attendee_checkin_listener', 1115 );
add_action( 'wp_loaded', 'rsvp_pro_frontend_redirect_buffer' );

add_action( 'admin_notices', 'rsvp_pro_license_notification' );

add_action( 'admin_init', 'rsvp_pro_add_privacy_policy_content' );
add_filter( 'wp_privacy_personal_data_erasers', 'rsvp_pro_register_data_eraser', 10 );
add_filter( 'wp_privacy_personal_data_exporters', 'rsvp_pro_register_data_exporter', 10 );
add_action( 'init', 'rsvp_pro_calendar_invite_handler', 20 );

add_shortcode( 'rsvppro', 'rsvp_pro_shortcode_handler' );
add_shortcode( 'rsvppro-attendeelist', 'rsvp_pro_attendeelist_shortcode_handler' );
add_shortcode( 'rsvppro-eventlist', 'rsvp_pro_eventlist_shortcode_handler' );
add_shortcode( 'rsvp-pro-numeric-total', 'rsvp_pro_numeric_total' );
add_shortcode( 'rsvp-pro-attendee-events', 'rsvp_pro_attendee_events_handler' );
add_shortcode( 'rsvp-pro-payment-success', 'rsvp_pro_payment_success_handler' );
add_shortcode( 'rsvp-pro-payment-failure', 'rsvp_pro_payment_failure_handler' );

add_action( 'admin_menu', 'rsvp_pro_modify_menu' );
add_action( 'network_admin_menu', 'rsvp_pro_modify_menu' );
if ( rsvp_pro_is_network_activated() ){
	add_action( 'network_admin_menu', 'rsvp_pro_modify_multiesite_menu' );
}

add_filter( 'plugin_row_meta', 'rsvp_pro_add_row_meta_links', 10, 2 );
add_filter( 'haet_mail_available_plugins', 'rsvp_pro_add_to_html_mail_plugins' );
add_action( 'admin_init', 'rsvp_pro_register_settings' );
add_action( 'init', 'rsvp_pro_init', 20 );
add_action( 'plugins_loaded', 'rsvp_pro_plugins_loaded' );
add_action( 'wp_head', 'rsvp_pro_add_css' );
add_action( 'rsvp_pro_reoccurring_events', 'rsvp_pro_handle_reoccurring_events' );
add_action( 'rsvp_pro_reminder_notifications', 'rsvp_pro_handle_reminder_notifications' );
add_action( 'rsvp_pro_attendee_list_notifications', 'rsvp_pro_cron_attendee_list_notifications' );
add_action( 'media_buttons', array( 'Rsvp_Pro_Editor_Button', 'add_form_buttons' ), 20 );

if ( Rsvp_Pro_Editor_Button::page_supports_add_form_button() ){
	add_action( 'admin_footer', array( 'Rsvp_Pro_Editor_Button', 'add_form_popup' ) );
}
register_activation_hook( __FILE__, 'rsvp_pro_activation' );
register_deactivation_hook( __FILE__, 'rsvp_pro_deactivation' );
