<?php

/**
 * Form and handler of adding and editing attendees in the admin area.
 *
 * @param  int $event_id The event ID that this guest is associated with.
 */
function rsvp_pro_admin_guest( $event_id ) {
	global $wpdb;
	global $rsvp_id;

	$rsvp_id                      = $event_id;
	$is_sub_event                 = false;
	$parent_event_id              = $wpdb->get_var( $wpdb->prepare( 'SELECT parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d', $event_id ) );
	$global_attendee_list_enabled = rsvp_pro_is_shared_attendee_list_enabled();

	if ( $parent_event_id > 0 || ( isset( $_POST['attendeeID'] ) && rsvp_pro_is_attendee_a_global_attendee( $_POST['attendeeID'] ) && ( $event_id !== RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) ) ) {
		$is_sub_event = true;
	} else {
		$parent_event_id = $event_id;
	}

	if ( ( count( $_POST ) > 0 ) &&
		 ( ! empty( $_POST['firstName'] ) || $is_sub_event ) ) {
		rsvp_pro_handle_admin_guest_form( $event_id, $parent_event_id, $is_sub_event, $global_attendee_list_enabled );
	} else {
		$attendee         = new Rsvp_Pro_Attendee();
		$sub_event_record = new Rsvp_Pro_Attendee_Subevent();

		if ( isset( $_GET['id'] ) && is_numeric( $_GET['id'] ) ) {
			$attendee = new Rsvp_Pro_Attendee( $_GET['id'] );

			if ( $is_sub_event ) {
				foreach ( $attendee->get_sub_event_responses() as $se ) {
					if ( $se->get_event_id() == $event_id ) {
						$sub_event_record = $se;
						break;
					}
				}
			}
		}
		?>
		<h3><?php echo rsvp_pro_get_event_name( $event_id ); ?></h3>
		<form name="contact" id="rsvp_pro_attendee_contact"
			  action="<?php echo admin_url( "admin.php?page=rsvp-pro-top-level&action=modify_attendee&eventID=$event_id" ); ?>"
			  method="post" enctype="multipart/form-data">
			<?php rsvp_pro_admin_attendee_form( $event_id, $attendee, $is_sub_event, $parent_event_id ); ?>
			<p class="submit">
				<input type="submit" class="button-primary" value="<?php esc_html_e( 'Save','rsvp-pro-plugin' ); ?>"/>
				<a class="button button-secondary" href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=attendees&eventID=' . $event_id ); ?>"><?php echo rsvp_pro_get_admin_string( 'back_attendee_list_label' ); ?></a>
			</p>
			<p>
				<a href="<?php echo admin_url( "admin.php?page=rsvp-pro-top-level&action=mass_email&eventID=$event_id&attendee[]=" . $attendee->get_id() ); ?>"
				   class="button-primary"><?php echo rsvp_pro_get_admin_string( 'email_attendee_label' ); ?></a>
			</p>
			<p>
				<br/>
				<a href="<?php echo wp_nonce_url( admin_url( "admin.php?page=rsvp-pro-top-level&action=reset_attendee&eventID=$event_id&id=" . $attendee->get_id() ), 'reset_attendee_' . $attendee->get_id() ); ?>"><?php echo rsvp_pro_get_admin_string( 'reset_attendee_label' ); ?></a>
				<br/>
				<span class="description"><?php echo rsvp_pro_get_admin_string( 'reset_rsvp_status_label' ); ?></span>
			</p>
		</form>
		<?php
		if ( 'Y' === rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_ENABLE_PAYMENTS ) ) {
			// Add ability to execute a refund.
			$sql      = 'SELECT amount, payment_status, transaction_id, e.eventName, a.rsvpEventID FROM ' . PRO_ATTENDEES_TABLE . ' a 
			JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = a.rsvpEventID 
			WHERE a.id = %d AND transaction_id != \'\' 
			UNION 
			SELECT amount, payment_status, transaction_id, e.eventName, se.rsvpEventID FROM ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se 
			JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = se.rsvpEventID 
			WHERE se.rsvpAttendeeID = %d AND transaction_id != \'\'';
			$payments = $wpdb->get_results( $wpdb->prepare( $sql, $attendee->get_id(), $attendee->get_id() ) );
			if ( count( $payments ) > 0 ) {
		?>
			<h3><?php echo rsvp_pro_get_admin_string( 'attendee_payment_transactions_header' ); ?></h3>
			<div class="rsvp_pro_attendee_payment_listing">
			<?php
			foreach ( $payments as $p ) {
			?>
				<p><?php echo stripslashes_deep( $p->eventName ) . ': ' . rsvp_pro_get_event_currency_symbol( $p->rsvpEventID) . rsvp_pro_format_money( $p->amount, $p->rsvpEventID ); ?> - PayPal - <?php echo stripslashes_deep( $p->transaction_id ); ?> - <?php echo stripslashes_deep( $p->payment_status ); ?></p>
			<?php
				// $amt = new \PayPal\Api\Amount();
				// $amt->setTotal( $p->amount );

				// $refund = new \PayPal\Api\RefundRequest();
				// $refund->setAmount( $amt );

				// $sale = new \PayPal\Api\Sale();
				// $sale->setId( $p->transaction_id );
				// $api = new \PayPal\Rest\ApiContext(
				// 	new \PayPal\Auth\OAuthTokenCredential(
				// 		"Ac7utdgoBdWh8wFsb7hrkcF9iWtKykcwjnBwQ6k2QvWFOXsNeSJJKr5HRagy6wbyuFDTY9FfqyfHTb5L",
				// 		"EBSJ2bxyd2KsXnvLe4SdDaJNzNszS5YMaDnXhXejH3K-c4ijes_zBq-DolBMTi0dkpPl4HbJoCmjEaTW"
				// 	)
				// );

				// $refunded_sale =  \PayPal\Api\Capture::get( $p->transaction_id, $api ); //$sale->refundSale($refund, $api);
				// var_dump( $refunded_sale );
				// die();
			}
			?>
			</div>
		<?php
			}
		}
		?>
		<?php
		if ( get_option( RSVP_PRO_GLOBAL_OPTION_ENABLE_ATTENDEE_CHANGELOG ) == 'Y' ) {
			$sql        = 'SELECT changes, change_date FROM ' . PRO_ATTENDEE_CHANGELOG . ' WHERE attendeeID = %d';
			$changelogs = $wpdb->get_results( $wpdb->prepare( $sql, $attendee->get_id() ) );
			if ( count( $changelogs ) > 0 ) {
				?>
				<div class="rsvp_pro_attendee_changelog_listing">
					<table cellpadding="2" cellspacing="0">
						<tr>
							<th><?php echo rsvp_pro_get_admin_string( 'change_heading' ); ?></th>
							<th><?php echo rsvp_pro_get_admin_string( 'change_heading_date' ); ?></th>
						</tr>
						<?php
						foreach ( $changelogs as $c ) {

							?>
							<tr>
								<td>
								<?php
								$changes = json_decode( stripslashes( $c->changes ) );
								foreach ( $changes as $change ) {
									if ( is_object( $change ) ) {
										echo '<p>' . $change->field . ': ' . $change->old_value .
											 ' ' . rsvp_pro_get_admin_string( 'changed_to_label' ) . ' ' . $change->new_value . '</p>';
									}
								}
								?>
									</td>
								<td valign="top"><?php echo date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $c->change_date ) ); ?></td>
							</tr>
							<?php
						}
						?>
					</table>
				</div>
				<?php
			}
		}
	}
}

/**
 * Displays all of the fields for editing or adding an attenndee. This is a shared function between the admin area and
 * the extension that allows for people to manage attendees from the front-end.
 *
 * @param int    $event_id The event ID related to this attendee.
 * @param object $attendee The current attendee for this form, if a new attendee the attendee object should have all of the defaults.
 * @param bool   $is_sub_event If the current event is a sub-event or not.
 * @param int    $parent_event_id The parent event ID for this event.
 */
function rsvp_pro_admin_attendee_form( $event_id, $attendee, $is_sub_event, $parent_event_id = 0 ) {
	global $wpdb;

	$is_global_attendee = rsvp_pro_is_attendee_a_global_attendee( $attendee->get_id() );

	if ( $is_global_attendee && ( $event_id !== RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) ) {
		// This handles the case where a global attendee is trying to be modified and in this case 
		// event event should be handled like a "sub-event". 
		$is_sub_event = true;
		$parent_event_id = $event_id;
	}

	$sub_event_record = new Rsvp_Pro_Attendee_Subevent();
	if ( $is_sub_event ) {
		foreach ( $attendee->get_sub_event_responses() as $se ) {
			if ( $se->get_event_id() == $event_id ) {
				$sub_event_record = $se;
				break;
			}
		}
	}
	?>
	<input type="hidden" name="eventID" id="eventID" value="<?php echo $event_id; ?>"/>
	<?php
	if ( $attendee->get_id() > 0 ) {
		?>
		<input type="hidden" name="attendeeID" id="attendeeID" value="<?php echo $attendee->get_id(); ?>"/>
		<?php
	}
	?>
	<?php
	if ( ! rsvp_pro_require_passcode( $event_id ) ) {
		?>
		<input type="hidden" name="passcode" value="<?php echo htmlentities( $attendee->get_passcode() ); ?>"/>
		<input type="hidden" name="alternate_passcode" value="<?php echo htmlentities( $attendee->get_alternate_passcode() ); ?>"/>
		<?php
	}
	?>
	<?php wp_nonce_field( 'rsvp_add_guest' ); ?>
	<?php
	if ( $is_sub_event ) :
		?>
		<div class="updated">
			<p>
				<?php
				echo sprintf( esc_html__( 'You are editing the attendee record for this sub-event not all fields will be editable. To edit all fields not-related to this event go to the <a href="%s">main record</a>', 'rsvp-pro-plugin' ), admin_url( "admin.php?page=rsvp-pro-top-level&action=modify_attendee&eventID=$parent_event_id&id=" . $attendee->get_id() ) ); ?>
			</p>
		</div>
		<?php
	endif;

	if ( ! empty( $attendee->get_rsvp_date() ) && ( strtotime( $attendee->get_rsvp_date() ) !== false ) ) {
		?>
		<p>
			<?php echo esc_html( $attendee->get_first_name() . ' ' . $attendee->get_last_name() ) . ' ' . rsvp_pro_get_admin_string( 'rsvpd_label' ); ?>
			<?php echo $attendee->get_rsvp_date(); ?>
		</p>
		<?php
	}
	?>
	<table class="form-table">
		<tbody>
		<tr>
			<th scope="row"><label
						for="firstName"><?php echo rsvp_pro_get_frontend_string( 'first_name_label' ); ?>
					:</label></th>
			<td>
				<?php
				if ( $is_sub_event ) {
					echo esc_html( $attendee->get_first_name() );
				} else {
					?>
					<input type="text" name="firstName" id="firstName" size="30"
						   value="<?php echo esc_attr( $attendee->get_first_name() ); ?>"/>
				<?php } ?>
			</td>
		</tr>
		<?php
		if ( ! $is_sub_event ) :
			?>
			<tr>
				<th scope="row"><label
							for="nicknames"><?php echo rsvp_pro_get_admin_string( 'alt_first_name_label' ); ?>
						:</label></th>
				<td>
					<input type="text" name="nicknames" id="nicknames" size="30"
						   value="<?php echo esc_attr( $attendee->get_nicknames() ); ?>"/>
					<br/>
					<span class="description"><?php echo esc_html__('Separate each alternative name with a comma (i.e. bob,jane)','rsvp-pro-plugin'); ?></span>
				</td>
			</tr>
			<?php
		endif;
		?>
		<tr>
			<th scope="row"><label
						for="lastName"><?php echo rsvp_pro_get_frontend_string( 'last_name_label' ); ?>:</label>
			</th>
			<td>
				<?php
				if ( $is_sub_event ) {
					echo esc_html( $attendee->get_last_name() );
				} else {
					?>
					<input type="text" name="lastName" id="lastName" size="30"
						   value="<?php echo esc_attr( $attendee->get_last_name() ); ?>"/>
					<?php
				}
				?>
			</td>
		</tr>
		<?php if ( ! $is_sub_event ) : ?>
			<?php if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_SHOW_SALUTATION ) == 'Y' ) : ?>
				<tr>
					<th scope="row"><label
								for="salutation"><?php echo rsvp_pro_get_frontend_string( 'salutation_text' ); ?>
							:</label></th>
					<td>
						<select name="salutation" id="salutation">
							<option value="">--</option>
							<?php
							$salutations = rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_SALUTATIONS );
							if ( empty( $salutations ) ) {
								$salutations = RSVP_PRO_DEFAULT_SALUTATION;
							}
							$salutations = explode( '||', $salutations );
							foreach ( $salutations as $s ) {
								$s = trim( $s );
								?>
								<option value="<?php echo esc_html( $s ); ?>" <?php echo( ( $s == $attendee->get_salutation() ) ? ' selected="selected"' : '' ); ?>><?php echo esc_html( $s ); ?></option>
							<?php } ?>
						</select>
					</td>
				</tr>
			<?php endif; ?>
			<?php if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_SHOW_SUFFIX ) == 'Y' ) : ?>
				<tr>
					<th scope="row"><label
								for="suffix"><?php echo rsvp_pro_get_frontend_string( 'suffix_label' ); ?>
							:</label></th>
					<td>
						<input type="text" name="suffix" id="suffix" size="15"
							   value="<?php echo esc_html( $attendee->get_suffix() ); ?>"/>
					</td>
				</tr>
			<?php endif; ?>
			<tr>
				<th scope="row"><label for="email"><?php echo rsvp_pro_get_frontend_string( 'email_label' ); ?>
						:</label></th>
				<td>
					<input type="text" name="email" id="email" size="30"
						   value="<?php echo esc_attr( $attendee->get_email() ); ?>"/>
				</td>
			</tr>
			<tr>
				<th scope="row"><label
							for="primaryAttendee"><?php echo rsvp_pro_get_admin_string( 'primary_attendee_label' ); ?>
						:</label></th>
				<td>
					<input type="checkbox" name="primaryAttendee" id="primaryAttendee" value="Y"
						<?php echo ( $attendee->get_primary_attendee() == 'Y' ) ? 'checked="checked"' : ''; ?> />
					<br/>
					<span class="description"><?php echo rsvp_pro_get_admin_string( 'primary_attendee_description_message' ); ?></span>
				</td>
			</tr>
		<?php endif; ?>
		<?php
		if ( rsvp_pro_require_passcode( $event_id ) ) {
			$maxLength = 6;
			if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_PASSWORD_LENGTH ) > 0 ) {
				$maxLength = rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_PASSWORD_LENGTH );
			}
			?>
			<tr>
				<th scope="row"><label
							for="passcode"><?php echo rsvp_pro_get_frontend_string( 'passcode_label' ); ?>
						:</label></th>
				<td>
					<input type="text" name="passcode" id="passcode" size="30"
						   value="<?php echo htmlentities( $attendee->get_passcode() ); ?>"
						   maxlength="<?php echo $maxLength; ?>"/>
				</td>
			</tr>
			<tr>
				<th scope="row"><label
							for="alternate_passcode"><?php echo rsvp_pro_get_admin_string( 'alternate_passcode_label' ); ?>
						:</label></th>
				<td>
					<input type="text" name="alternate_passcode" id="alternate_passcode" size="30"
						   value="<?php echo htmlentities( $attendee->get_alternate_passcode() ); ?>"
						   maxlength="<?php echo $maxLength; ?>"/>
				</td>
			</tr>
			<?php
		}

		if ( $event_id != RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) {
			?>
			<tr>
				<th scope="row">
					<label for="rsvpStatus"><?php echo rsvp_pro_get_frontend_string( 'rsvp_status_label' ); ?></label>
				</th>
				<td>
					<select name="rsvpStatus" id="rsvpStatus" size="1">
						<?php
						if ( $is_sub_event ) {
							$rsvp_response = $sub_event_record->get_rsvp_status();
						} else {
							$rsvp_response = $attendee->get_rsvp_status();
						}
						?>
						<option value="NoResponse" 
						<?php
						echo( ( $rsvp_response == 'NoResponse' ) ? ' selected="selected"' : '' );
						?>
						><?php echo rsvp_pro_get_frontend_string( 'noresponse_text' ); ?></option>
						<option value="Yes" 
						<?php
						echo( ( $rsvp_response == 'Yes' ) ? ' selected="selected"' : '' );
						?>
						><?php echo rsvp_pro_get_frontend_string( 'yes_text' ); ?></option>
						<option value="No" 
						<?php
						echo( ( $rsvp_response == 'No' ) ? ' selected="selected"' : '' );
						?>
						><?php echo rsvp_pro_get_frontend_string( 'no_text' ); ?></option>
						<?php
						if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_ENABLE_MAYBE ) == 'Y' ) :
							?>
							<option value="Maybe" <?php echo( ( $rsvp_response == 'Maybe' ) ? ' selected="selected"' : '' ); ?>><?php echo rsvp_pro_get_frontend_string( 'maybe_text' ); ?></option>
							<?php
						endif;

						if ( rsvp_pro_waitlist_enabled( $event_id ) ) :
							?>
							<option value="Waitlist"
								<?php echo( ( $rsvp_response == 'Waitlist' ) ? ' selected="selected"' : '' ); ?>><?php echo rsvp_pro_get_frontend_string( 'waitlist_text' ); ?></option>
							<?php
						endif;

						if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_PLUS_ONE_ENABLED ) == 'Y' ) :
							?>
							<option value="PlusOne"
								<?php echo( ( $rsvp_response == 'PlusOne' ) ? ' selected="selected"' : '' ); ?>><?php echo rsvp_pro_get_frontend_string( 'plusone_text' ); ?></option>
						<?php endif; ?>
					</select>
				</td>
			</tr>
			<?php
		} // Global Attendee Event ID Check
		if ( ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_ALLOW_CHECKINS ) === 'Y' ) ||
			 ( $is_sub_event && ( rsvp_pro_get_event_option( $parent_event_id, RSVP_PRO_OPTION_ALLOW_CHECKINS ) === 'Y' ) ) ) :

			$checked_in = $attendee->get_checked_in();
			if ( $is_sub_event ) {
				$checked_in = $sub_event_record->get_checked_in();
			}
			?>
			<tr>
				<th scope="row">
					<label for="checked_in"><?php echo rsvp_pro_get_admin_string( 'checked_in_label' ); ?></label>
				</th>
				<td>
					<input type="checkbox" name="checked_in" id="checked_in"
						   value="Y" <?php echo( ( $checked_in === 'Y' ) ? 'checked="checked"' : '' ); ?> />
				</td>
			</tr>
			<?php
		endif;
		if ( ! $is_sub_event || $is_global_attendee ) :
			$num_guests = $attendee->get_num_guests();

			if ( $is_global_attendee && ( $event_id !== RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) ) {
				$num_guests = $sub_event_record->get_num_guests();
			}
			if( null === $num_guests ){
				$num_guests = '';
			}
			?>
			<tr>
				<th scope="row"><label
							for="numGuests"><?php echo rsvp_pro_get_admin_string( 'number_guests_allowed_label' ); ?>
						:</label></th>
				<td>
					<input type="text" name="numGuests" id="numGuests" size="30"
						value="<?php echo htmlentities( $num_guests ); ?>"/>
				</td>
			</tr>
		<?php endif; ?>
		<?php if ( ! $is_sub_event ) : ?>
			<tr>
				<th scope="row"><label
							for="personalGreeting"><?php echo rsvp_pro_get_admin_string( 'custom_message_label' ); ?>
						:</label></th>
				<td>
							<textarea name="personalGreeting" id="personalGreeting" rows="5"
									  cols="40"><?php echo htmlentities( $attendee->get_personal_greeting() ); ?></textarea>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="note"><?php echo rsvp_pro_get_admin_string( 'note_label' ); ?>
						:</label></th>
				<td>
							<textarea name="note" id="note" rows="5"
									  cols="40"><?php echo htmlentities( $attendee->get_note() ); ?></textarea>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php echo rsvp_pro_get_frontend_string( 'associated_attendees_label' ); ?>:
				</th>
				<td>
					<p>
						<span style="margin-left: -5px;"><?php echo rsvp_pro_get_admin_string( 'non_associated_attendees_label' ); ?></span>
						<span style="margin-left:26px;"><?php echo rsvp_pro_get_frontend_string( 'associated_attendees_label' ); ?></span>
					</p>
					<select name="associatedAttendees[]" id="associatedAttendeesSelect" multiple="multiple"
							size="5">
						<?php
						$attendees = $wpdb->get_results(
							$wpdb->prepare(
								'SELECT id, firstName, lastName 			
								    FROM ' . PRO_ATTENDEES_TABLE . ' 
                                    WHERE rsvpEventID = %d ORDER BY 
                                    lastName, firstName',
								$event_id
							)
						);
						foreach ( $attendees as $a ) {
							if ( $a->id != $attendee->get_id() ) {
								?>
								<option value="<?php echo $a->id; ?>"
									<?php echo( ( in_array( $a->id, $attendee->get_associated_attendees() ) ) ? 'selected="selected"' : '' ); ?>><?php echo htmlentities( stripslashes_deep( $a->firstName ) . ' ' . stripslashes_deep( $a->lastName ) ); ?></option>
								<?php
							}
						}
						?>
					</select>
				</td>
			</tr>
		<?php endif; ?>
		<tr>
			<th scope="row"><?php echo rsvp_pro_get_admin_string( 'rsvp_date_label' ); ?>:</th>
			<?php
			$rsvp_date = $attendee->get_rsvp_date();
			if ( $is_sub_event ) {
				$rsvp_date = $sub_event_record->get_rsvp_date();
			}
			if( null !== $rsvp_date ){
				$rsvp_date = date_i18n( get_option( 'date_format' ), strtotime( $rsvp_date ) );
			}
			?>
			<td><input type="text" name="rsvp_date" id="rsvp_date" value="<?php echo $rsvp_date; ?>" /></td>
		</tr>
		<?php
		$sql = 'SELECT question, answer, ans.id AS answerID, q.ID AS questionID, questionType, 
			`grouping`, other_question, other_question_text FROM ' . PRO_QUESTIONS_TABLE . ' q
			LEFT JOIN ' . PRO_ATTENDEE_ANSWERS . ' ans ON ans.questionID = q.id AND attendeeID = %d
			INNER JOIN ' . PRO_QUESTION_TYPE_TABLE . ' qt ON qt.ID = q.questionTypeID
			WHERE q.rsvpEventID = %d
			ORDER BY q.sortOrder';
		$aRs = $wpdb->get_results( $wpdb->prepare( $sql, $attendee->get_id(), $event_id ) );
		if ( count( $aRs ) > 0 ) {
			?>
			<tr>
				<th><?php echo rsvp_pro_get_admin_string( 'custom_questions_label' ); ?></th>
			</tr>
			<?php
			foreach ( $aRs as $a ) {
				?>
				<tr>
					<th scope="row"><?php echo stripslashes( $a->question ); ?></th>
					<td>
						<?php
						if ( $a->questionType == QT_PRO_MULTI ) {
							$oldAnswers = explode( '||', stripslashes( $a->answer ) );

							$possibleAnswers = $wpdb->get_results( $wpdb->prepare( 'SELECT id, answer FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d', $a->questionID ) );
							if ( count( $possibleAnswers ) > 0 ) {
								?>
								<table>
									<?php
									foreach ( $possibleAnswers as $pa ) {
										?>
										<tr>
											<th>
												<label for="question<?php echo $a->questionID . $pa->id; ?>"><?php echo stripslashes( $pa->answer ); ?></label>
											</th>
											<td><input type="checkbox"
													   name="question<?php echo $a->questionID; ?>[]"
													   id="question<?php echo $a->questionID . $pa->id; ?>"
													   value="<?php echo $pa->id; ?>"
													<?php echo( ( in_array( stripslashes( $pa->answer ), $oldAnswers ) ) ? ' checked="checked"' : '' ); ?> />
											</td>
										</tr>
										<?php
									}

									if ( 'Y' === $a->other_question ) {
										$answer_text  = rsvp_pro_get_frontend_string( 'custom_question_other_label' );
										$answer       = '';
										$answer_found = false;

										foreach( $oldAnswers as $oa ) {
											if ( stripos( $oa, 'other--') !== false ) {
												$answer_found = true;
												$answer       = str_ireplace( 'other--', '', $oa );
											}
										}

										if ( '' !== $a->other_question_text ) {
											$answer_text = stripslashes_deep( $a->other_question_text );
										}
										?>
										<tr>
											<th>
												<label for="question<?php echo $a->questionID; ?>other"><?php echo $answer_text; ?></label>
											</th>
											<td><input type="checkbox"
													   name="question<?php echo $a->questionID; ?>[]"
													   id="question<?php echo $a->questionID; ?>other"
													   value="other"
													<?php echo( ( $answer_found ) ? ' checked="checked"' : '' ); ?> />
												<input type="text" name="question<?php echo $a->questionID; ?>other" value="<?php echo esc_attr( $answer ); ?>" />
											</td>
										</tr>
										<?php
									}
									?>
								</table>
								<?php
							}
						} elseif ( $a->questionType == QT_PRO_DROP ) {
							?>
							<select name="question<?php echo $a->questionID; ?>" size="1">
								<option value="">--</option>
								<?php
								$possibleAnswers = $wpdb->get_results( $wpdb->prepare( 'SELECT id, answer FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d', $a->questionID ) );
								if ( count( $possibleAnswers ) > 0 ) {
									foreach ( $possibleAnswers as $pa ) {
										?>
										<option value="<?php echo $pa->id; ?>" <?php echo( ( stripslashes( $pa->answer ) == stripslashes( $a->answer ) ) ? ' selected="selected"' : '' ); ?>><?php echo stripslashes( $pa->answer ); ?></option>
										<?php
									}
								}
								?>
							</select>
							<?php
						} elseif ( ( $a->questionType == QT_PRO_LONG ) || ( $a->questionType == QT_PRO_HIDDEN ) || ( $a->questionType == QT_PRO_READ_ONLY ) ) {
							?>
							<textarea name="question<?php echo $a->questionID; ?>" rows="5"
									  cols="35"><?php echo htmlspecialchars( $a->answer ); ?></textarea>
							<?php
						} elseif ( $a->questionType == QT_PRO_RADIO ) {
							$possibleAnswers = $wpdb->get_results( $wpdb->prepare( 'SELECT id, answer FROM ' . PRO_QUESTION_ANSWERS_TABLE . ' WHERE questionID = %d', $a->questionID ) );
							if ( count( $possibleAnswers ) > 0 ) {
								?>
								<table>
									<?php
									foreach ( $possibleAnswers as $pa ) {
										?>
										<tr>
											<th scope="row">
												<label for="question<?php echo $a->questionID . $pa->id; ?>"><?php echo stripslashes( $pa->answer ); ?></label>
											</th>
											<td>
												<input type="radio" name="question<?php echo $a->questionID; ?>"
													   id="question<?php echo $a->questionID . $pa->id; ?>"
													   value="<?php echo $pa->id; ?>" <?php echo( ( stripslashes( $pa->answer ) == stripslashes( $a->answer ) ) ? ' checked="checked"' : '' ); ?> />
											</td>
										</tr>
										<?php
									}

									if ( 'Y' === $a->other_question ) {
										$answer_text  = rsvp_pro_get_frontend_string( 'custom_question_other_label' );
										$answer       = '';
										$answer_found = false;

										if ( stripos( $a->answer, 'other--') !== false ) {
											$answer_found = true;
											$answer       = str_ireplace( 'other--', '', stripslashes_deep( $a->answer ) );
										}

										if ( '' !== $a->other_question_text ) {
											$answer_text = stripslashes_deep( $a->other_question_text );
										}

										?>
										<tr>
											<th scope="row">
												<label for="question<?php echo $a->questionID ; ?>other"><?php echo $answer_text; ?></label>
											</th>
											<td>
												<input type="radio" name="question<?php echo $a->questionID; ?>"
													   id="question<?php echo $a->questionID; ?>other"
													   value="other" <?php echo ( ( $answer_found ) ? ' checked="checked"' : '' ); ?> />
												<input type="text" name="question<?php echo $a->questionID; ?>other" value="<?php echo esc_attr( $answer ); ?>" />
											</td>
										</tr>
										<?php
									}
									?>
								</table>
								<?php
							}
						} elseif ( $a->questionType === QT_DATEPICKER ) {
							?>
							<input type="text" name="question<?php echo $a->questionID; ?>"
								   value="<?php echo htmlspecialchars( $a->answer ); ?>"
								   class="rsvp_pro_datepicker_question"/>
							<?php
						} elseif ( $a->questionType === QT_PRO_FILE ) {
							?>
							<input type="file" name="question<?php echo $a->questionID; ?>" />
							<?php
							if ( isset( $a->answer ) && ( 0 < $a->answer ) && ( false !== wp_get_attachment_url( $a->answer ) ) ) {
								$file_url = wp_get_attachment_url( $a->answer );
							?>
								<div class="file_attachment_container">
									<a href="<?php echo esc_attr( $file_url ); ?>"><?php echo rsvp_pro_get_admin_string( 'admin_attendee_view_file' ); ?></a> | 
									<a href="#" class="delete_attendee_attachment" data-attendee-token="<?php echo $attendee->get_token(); ?>" data-question-id="<?php echo $a->questionID; ?>"><?php echo rsvp_pro_get_admin_string( 'admin_attendee_delete_file' ); ?></a>
								</div>
							<?php
							}
						} else {
							?>
							<input type="text" name="question<?php echo $a->questionID; ?>"
								   value="<?php echo htmlspecialchars( $a->answer ); ?>"/>
							<?php
						}
						?>
						<?php
						if ( $a->grouping == RSVP_PRO_QG_MULTI ) {
							?>
							<span class="description"><?php esc_html_e( 'Question asked once per associated attendees', 'rsvp-pro-plugin') ;?></span>
							<?php
						}
						?>
					</td>
				</tr>
				<?php
			}
			?>
			<?php
		}
		?>
		</tbody>
	</table>
	<?php
}

/**
 * Saves the attendee form information.
 *
 * @param  int  $event_id                     The current event ID.
 * @param  int  $parent_event_id              The parent event ID.
 * @param  bool $is_sub_event                 If the event is a sub event or not.
 * @param  bool $global_attendee_list_enabled If the global attendee list is enabled.
 * @return object                               The current attenndee as an object.
 */
function rsvp_pro_save_admin_guest_form( $event_id, $parent_event_id, $is_sub_event, $global_attendee_list_enabled ) {
	global $wpdb;
	global $rsvp_id;

	if ( isset( $_POST['attendeeID'] ) && rsvp_pro_is_attendee_a_global_attendee( $_POST['attendeeID'] ) && ( $event_id != RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) ) {
		// This handles the case where a global attendee is trying to be modified and in this case 
		// event event should be handled like a "sub-event".
		$is_sub_event = true;
	}

	if ( $is_sub_event ) {
		if ( isset( $_POST['attendeeID'] ) && is_numeric( $_POST['attendeeID'] ) && ( $_POST['attendeeID'] > 0 ) ) {
			$attendee         = new Rsvp_Pro_Attendee( $_POST['attendeeID'] );
			$sub_event_record = new Rsvp_Pro_Attendee_Subevent();
			$attendee_id      = $attendee->get_id();

			foreach ( $attendee->get_sub_event_responses() as $se ) {
				if ( $se->get_event_id() == $event_id ) {
					$sub_event_record = $se;
				}
			}

			$sub_event_record->set_rsvp_status( $_POST['rsvpStatus'] );

			if ( $sub_event_record->get_id() <= 0 ) {
				$sub_event_record->set_event_id( $event_id );
				$sub_event_record->set_attendee_id( $attendee->get_id() );
			}

			if ( rsvp_pro_get_event_option( $parent_event_id, RSVP_PRO_OPTION_ALLOW_CHECKINS ) === 'Y' ) {
				$check_in_value = 'N';
				if ( isset( $_POST['checked_in'] ) && ( strtoupper( $_POST['checked_in'] ) === 'Y' ) ) {
					$check_in_value = 'Y';
				}

				$sub_event_record->set_checked_in( $check_in_value );
			}
			$num_guests = null;
			if ( isset( $_POST['numGuests'] ) && ( $_POST['numGuests'] >= 0 ) && ( is_numeric( $_POST['numGuests'] ) ) ) {
				$num_guests = $_POST['numGuests'];
			}

			$sub_event_record->set_num_guests( $num_guests );
			$sub_event_record->set_rsvp_date( $_POST['rsvp_date'] );
			$sub_event_record->save();
		}
	} else {
		$passcode   = ( isset( $_POST['passcode'] ) ) ? $_POST['passcode'] : '';
		$alternate_passcode = ( isset( $_POST['alternate_passcode'] ) ) ? $_POST['alternate_passcode'] : '';
		$num_guests = null;
		if ( isset( $_POST['numGuests'] ) && ( $_POST['numGuests'] >= 0 ) && ( is_numeric( $_POST['numGuests'] ) ) ) {
			$num_guests = $_POST['numGuests'];
		}

		$primary_attendee = ( isset( $_POST['primaryAttendee'] ) && ( $_POST['primaryAttendee'] == 'Y' ) ) ? 'Y' : 'N';

		$rsvp_status        = isset( $_POST['rsvpStatus'] ) ? trim( $_POST['rsvpStatus'] ) : 'NoResponse';
		$global_rsvp_status = $rsvp_status;

		if ( $global_attendee_list_enabled && ( $event_id != RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) &&
			isset( $_POST['attendeeID'] ) && rsvp_pro_is_attendee_a_global_attendee( $_POST['attendeeID'] ) ) {
			$rsvp_status = 'NoResponse';
		}

		$attendee    = new Rsvp_Pro_Attendee();
		$attendee_id = 0;
		if ( isset( $_POST['attendeeID'] ) && is_numeric( $_POST['attendeeID'] ) ) {
			$attendee    = new Rsvp_Pro_Attendee( $_POST['attendeeID'] );
			$attendee_id = $_POST['attendeeID'];
		}

		$attendee->set_first_name( rsvp_pro_smart_quote_replace( trim( $_POST['firstName'] ) ) );
		$attendee->set_last_name( rsvp_pro_smart_quote_replace( trim( $_POST['lastName'] ) ) );
		$attendee->set_nicknames( rsvp_pro_smart_quote_replace( trim( $_POST['nicknames'] ) ) );
		$attendee->set_personal_greeting( trim( $_POST['personalGreeting'] ) );
		$attendee->set_rsvp_status( $rsvp_status );
		$attendee->set_email( trim( $_POST['email'] ) );
		$attendee->set_note( trim( $_POST['note'] ) );
		$attendee->set_primary_attendee( $primary_attendee );
		$attendee->set_num_guests( $num_guests );
		$attendee->set_rsvp_event_id( $event_id );
		$attendee->set_rsvp_date( $_POST['rsvp_date'] );

		if ( $global_attendee_list_enabled && ( $event_id != RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) && rsvp_pro_is_attendee_a_global_attendee( $attendee_id ) ) {

			$sub_events = $attendee->get_sub_event_responses();
			$sub_event  = new Rsvp_Pro_Attendee_Subevent();
			foreach ( $sub_events as $se ) {
				if ( $se->get_event_id() === $event_id ) {
					$sub_event = $se;
					break;
				}
			}

			$sub_event->set_rsvp_status( trim( $global_rsvp_status ) );
			$sub_event->set_event_id( $event_id );
			$attendee->add_sub_event_responses( $sub_event );
		}

		if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_SHOW_SALUTATION ) == 'Y' ) {
			$attendee->set_salutation( trim( $_POST['salutation'] ) );
		}

		if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_SHOW_SUFFIX ) == 'Y' ) {
			$attendee->set_suffix( trim( $_POST['suffix'] ) );
		}

		if ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_ALLOW_CHECKINS ) === 'Y' ) {
			$check_in_value = 'N';
			if ( isset( $_POST['checked_in'] ) && ( strtoupper( $_POST['checked_in'] ) === 'Y' ) ) {
				$check_in_value = 'Y';
			}
			$attendee->set_checked_in( $check_in_value );
		}

		if ( rsvp_pro_require_passcode( $event_id ) ) {
			if ( empty( $passcode ) ) {
				$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 );
				}

				$passcode = rsvp_pro_generate_passcode( $length );
			}
			$attendee->set_passcode( $passcode );
			$attendee->set_alternate_passcode( $alternate_passcode );
		}

		$attendee->save();
		$attendee_id = $attendee->get_id();

		if ( isset( $_POST['associatedAttendees'] ) && is_array( $_POST['associatedAttendees'] ) ) {
			$associated_attendees = array();
			foreach ( $_POST['associatedAttendees'] as $aid ) {
				if ( is_numeric( $aid ) && ( $aid > 0 ) ) {
					$associated_attendees[] = $aid;
				}
			}

			$attendee->set_associated_attendees( $associated_attendees );
			$attendee->save();

			// See if there are some custom questions that should be associated to this new user....
			$sql     = 'SELECT id FROM ' . PRO_QUESTIONS_TABLE . ' WHERE id IN (SELECT questionID FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE attendeeID IN (SELECT associatedAttendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . " WHERE attendeeID = %d)) AND `grouping` = 'multi' AND id NOT IN (SELECT questionID FROM " . PRO_ATTENDEE_ANSWERS . ' WHERE attendeeID = %d)';
			$multiQs = $wpdb->get_results( $wpdb->prepare( $sql, $attendee_id, $attendee_id ) );
			if ( count( $multiQs ) > 0 ) {
				foreach ( $multiQs as $mq ) {
					$sql    = 'SELECT DISTINCT answer FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE questionID = %d AND attendeeID IN (SELECT associatedAttendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . ' WHERE attendeeID = %d)';
					$answer = $wpdb->get_results( $wpdb->prepare( $sql, $mq->id, $attendee_id ) );
					if ( count( $answer ) > 0 ) {
						$wpdb->insert(
							PRO_ATTENDEE_ANSWERS,
							array(
								'attendeeID' => $attendee_id,
								'answer'     => stripslashes( $answer[0]->answer ),
								'questionID' => $mq->id,
							),
							array(
								'%d',
								'%s',
								'%d',
							)
						);
					} //if(count($answer) > 0).
				} //foreach($multiQs as $mq).
			}
		} else {
			$attendee->set_associated_attendees( array() );
			$attendee->save();
		}
	} // if($is_sub_event).

	rsvp_pro_handleAdditionalQuestions( $attendee_id, 'question', true );
	rsvp_pro_handleGroupQuestions( $attendee_id, 'question' );

	return $attendee;
}

/**
 * Handles the processing for adding or editing an attendee from the admin side.
 *
 * @param  int  $event_id The event ID we want the user associated with.
 * @param  int  $parent_event_id The parent event ID if there is any. This is only done in the case where we are editing a sub-event.
 * @param  bool $is_sub_event If this event is a sub-event or not.
 * @param  bool $global_attendee_list_enabled If the global attendee list is enabled.
 */
function rsvp_pro_handle_admin_guest_form( $event_id, $parent_event_id, $is_sub_event, $global_attendee_list_enabled ) {
	global $wpdb;
	global $rsvp_id;
	check_admin_referer( 'rsvp_add_guest' );
	$attendee = rsvp_pro_save_admin_guest_form( $event_id, $parent_event_id, $is_sub_event, $global_attendee_list_enabled );
	?>
	<p><?php echo rsvp_pro_get_admin_string( 'attendee_label' ); ?> <?php echo esc_html( $attendee->get_first_name() . ' ' . $attendee->get_last_name() ); ?> <?php echo rsvp_pro_get_admin_string( 'attendee_successfully_saved_message' ); ?></p>
	<p>
		<a class="button button-secondary"
		   href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action&action=attendees&eventID=' . $event_id ); ?>"><?php echo rsvp_pro_get_admin_string( 'continue_attendee_list_label' ); ?></a>
		<a class="button button-primary"
		   href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=modify_attendee&eventID=' . $event_id ); ?>"><?php echo rsvp_pro_get_admin_string( 'add_attendees_button' ); ?></a>
		<a class="button button-secondary"
		   href="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=modify_attendee&eventID=' . $event_id . '&id=' . $attendee->get_id() ); ?>">
			<?php
			echo rsvp_pro_get_admin_string( 'edit_label' ) . ' ';
			echo htmlentities( $attendee->get_first_name() . ' ' . $attendee->get_last_name() );
			echo ' ';
			echo rsvp_pro_get_admin_string( 'again_label' );
			?>
		</a>
	</p>
	<?php
}
