<?php
/**
 * Main attendee export piece of functionality. This will output a
 * file of attendees for a given event.
 *
 * @param  int $eventID The event we want to export the attendee information for.
 */
function rsvp_pro_admin_export( $eventID ) {
	global $wpdb;
	if ( isset( $_GET['eventID'] ) && ( $_GET['eventID'] > 0 ) ) {
		$eventID = $_GET['eventID'];
	}

	$isSubEvent          = false;
	$includeSubInfo      = false;
	$customLinkBase      = '';
	$subEventID          = 0;
	$global_list_enabled = rsvp_pro_is_shared_attendee_list_enabled();

	if ( isset( $_GET['includeSubs'] ) && ( $_GET['includeSubs'] === true ) ) {
		$includeSubInfo = true;
	}

	rsvp_pro_save_export_columns( $eventID );

	$parentEventId = $wpdb->get_var( $wpdb->prepare( 'SELECT parentEventID FROM ' . PRO_EVENT_TABLE . ' WHERE id = %d', $eventID ) );
	if ( $parentEventId > 0 ) {
		$isSubEvent = true;
		$subEventID = $eventID;
		$eventID    = $parentEventId;
	}
	$queryString = 's=[rsvppro id="' . $eventID . '"]';
	$query       = new WP_Query( $queryString );
	if ( $query->have_posts() ) {
		$query->the_post();
		$customLinkBase = get_permalink();
		if ( strpos( $customLinkBase, '?' ) !== false ) {
			$customLinkBase .= '&';
		} else {
			$customLinkBase .= '?';
		}

		if ( rsvp_pro_require_only_passcode_to_register( $eventID ) ) {
			$customLinkBase .= 'passcode=%s';
		} else {
			$customLinkBase .= 'firstName=%s&lastName=%s';

			if ( rsvp_pro_require_passcode( $eventID ) ) {
				$customLinkBase .= '&passcode=%s';
			}
		}
	}
	wp_reset_postdata();
	$csv = '';

	if ( rsvp_pro_admin_export_include_column( 'export_salutation', true ) ) {
		$csv .= '"Salutation",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_first_name', true ) ) {
		$csv .= '"First Name",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_last_name', true ) ) {
		$csv .= '"Last Name",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_suffix', true ) ) {
		$csv .= '"Suffix",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_rsvp_status', true ) ) {
		$csv .= '"RSVP Status",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_associated_attendees', true ) ) {
		$csv .= '"Associated Attendees",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_passcode', rsvp_pro_require_passcode( $eventID ) ) ) {
		$csv .= '"Passcode",';
	}
	if ( rsvp_pro_admin_export_include_column( 'export_alternate_passcode', rsvp_pro_require_passcode( $eventID ) ) ) {
		$csv .= '"Alternate Passcode",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_custom_message', true ) ) {
		$csv .= '"Custom Message",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_email', true ) ) {
		$csv .= '"Email",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_num_guests_allowed', true ) ) {
		$csv .= '"Number of guests allowed for attendee",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_note', true ) ) {
		$csv .= '"Note",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_primary_attendee', true ) ) {
		$csv .= '"Primary Attendee",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_additional_attendee', true ) ) {
		$csv .= '"Additional Attendee",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_rsvp_date', true ) ) {
		$csv .= '"RSVP Date",';
	}

	$sql = 'SELECT id, question, permissionLevel 
            FROM ' . PRO_QUESTIONS_TABLE . ' 
            WHERE rsvpEventID = %d ORDER BY sortOrder, id';
	$qRs = $wpdb->get_results( $wpdb->prepare( $sql, ( $isSubEvent ) ? $subEventID : $eventID ) );
	if ( count( $qRs ) > 0 ) {
		foreach ( $qRs as $q ) {
			if ( rsvp_pro_admin_export_include_column( 'export_custom_question_' . $q->id, true ) ) {
				$csv .= '"' . strip_tags( stripslashes( $q->question ) ) . '",';

				if ( $q->permissionLevel == 'private' ) {
					$csv .= '"pq_' . $q->id . '",';
				}
			}
		}
	}

	if ( rsvp_pro_admin_export_include_column( 'export_prefill_url', ( $customLinkBase != '' ) ) ) {
		$csv .= '"pre-fill URL",';
	}

	if ( $includeSubInfo ) {
		$sql  = 'SELECT id, eventName FROM ' . PRO_EVENT_TABLE . '
					WHERE parentEventID = %d
					ORDER BY id';
		$subs = $wpdb->get_results( $wpdb->prepare( $sql, $eventID ) );
		foreach ( $subs as $s ) {
			$csv .= '"' . stripslashes( $s->eventName ) . ' RSVP Status",';

			$sql = 'SELECT id, question, permissionLevel FROM ' . PRO_QUESTIONS_TABLE . ' WHERE rsvpEventID = %d ORDER BY sortOrder, id';
			$qRs = $wpdb->get_results( $wpdb->prepare( $sql, $s->id ) );
			if ( count( $qRs ) > 0 ) {
				foreach ( $qRs as $q ) {
					$csv .= '"' . stripslashes( $q->question ) . '",';

					if ( $q->permissionLevel == 'private' ) {
						$csv .= '"pq_' . $q->id . '",';
					}
				}
			}
		}
	}

	if ( rsvp_pro_admin_export_include_column( 'export_checked_in', ( rsvp_pro_get_event_option( $eventID, RSVP_PRO_OPTION_ALLOW_CHECKINS ) === 'Y' ) ) ) {
		$csv .= '"Checked In",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_change_log', false ) ) {
		$csv .= '"Change Log",';
	}

	$csv .= "\r\n";

	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 Export' );
	header( 'Content-Type: application/vnd.ms-excel', true );
	header( 'Content-Disposition: attachment; filename="rsvpEntries.csv"' );
	echo $csv;

	if ( $isSubEvent ) {
		$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)  OR (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)))';
	} 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 .= ' ) ';

		if ( ! $includeSubInfo ) {
			$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)))';
		}
	}
	$orderBy = ' lastName, firstName';
	if ( isset( $_POST['sortValue'] ) ) {
		if ( strToLower( $_POST['sortValue'] ) == 'rsvpstatus' ) {
			$orderBy = ' rsvpStatus ' . ( ( strtolower( $_POST['exportSortDirection'] ) == 'desc' ) ? 'DESC' : 'ASC' ) . ', ' . $orderBy;
		} elseif ( strToLower( $_POST['sortValue'] ) == 'attendee' ) {
			$direction = ( ( strtolower( $_POST['exportSortDirection'] ) == 'desc' ) ? 'DESC' : 'ASC' );
			$orderBy   = " lastName $direction, firstName $direction";
		} elseif ( strToLower( $_POST['sortValue'] ) == 'additional' ) {
			$orderBy = ' additionalAttendee ' . ( ( strtolower( $_POST['exportSortDirection'] ) == 'desc' ) ? 'DESC' : 'ASC' ) . ', ' . $orderBy;
		}
	}
	$sql .= ' ORDER BY ' . $orderBy;
	if ( $isSubEvent ) {
		$preparedSql = $wpdb->prepare( $sql, $subEventID, $subEventID, $subEventID, $eventID );
	} else {
		$preparedSql = $wpdb->prepare( $sql, $eventID, $eventID );
	}

	$attendees         = $wpdb->get_results( $preparedSql );
	$attendeesExported = array();

	foreach ( $attendees as $a ) {
		if ( ! in_array( $a->id, $attendeesExported ) ) {
			$attendeesExported [] = $a->id;

			echo rsvp_pro_prepare_attendee_row( $a, $eventID, $isSubEvent, $subEventID, $customLinkBase, $includeSubInfo );

			// Get associated people and get the information for them as well..
			if ( $isSubEvent ) {
				$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.id IN (SELECT attendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . ' WHERE associatedAttendeeID = %d)
							OR a.id in (SELECT associatedAttendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . " WHERE attendeeID = %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)))';
			} 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.id IN (SELECT attendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . ' WHERE associatedAttendeeID = %d)
							OR a.id in (SELECT associatedAttendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . " WHERE attendeeID = %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))) ';

				if ( ! $includeSubInfo ) {
					$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)))';
				}
			}
			if ( $isSubEvent ) {
				$associations = $wpdb->get_results( $wpdb->prepare( $sql, $subEventID, $subEventID, $a->id, $a->id ) );
			} else {
				$associations = $wpdb->get_results( $wpdb->prepare( $sql, $eventID, $a->id, $a->id ) );	
			}

			if ( count( $associations ) > 0 ) {
				foreach ( $associations as $assoc ) {
					if ( ! in_array( $assoc->id, $attendeesExported ) ) {
						$attendeesExported [] = $assoc->id;
						echo rsvp_pro_prepare_attendee_row( $assoc, $eventID, $isSubEvent, $subEventID, $customLinkBase, $includeSubInfo );
					}
				}
			}
		} // if ( ! in_array( $a->id, $attendeesExported ) ) {
	}
	exit();
}

/**
 * Gets the data and prepares the CSV row for an attendee.
 *
 * @return string Of all the data for an attendee
 */
function rsvp_pro_prepare_attendee_row( $attendee, $event_id, $is_sub_event, $sub_event_id, $custom_link_base, $include_sub_info ) {
	global $wpdb;

	$fName = stripslashes( $attendee->firstName );
	$fName = rsvp_pro_handle_text_encoding( $fName );
	$lName = stripslashes( $attendee->lastName );
	$lName = rsvp_pro_handle_text_encoding( $lName );

	$csv = '';
	if ( rsvp_pro_admin_export_include_column( 'export_salutation', true ) ) {
		$csv .= '"' . stripslashes( $attendee->salutation ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_first_name', true ) ) {
		$csv .= '"' . $fName . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_last_name', true ) ) {
		$csv .= '"' . $lName . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_suffix', true ) ) {
		$csv .= '"' . stripslashes( $attendee->suffix ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_rsvp_status', true ) ) {
		$csv .= '"' . ( $attendee->rsvpStatus ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_associated_attendees', true ) ) {
		$csv .= '"';

		$sql = "SELECT CONCAT_WS(' ', firstName, lastName) AS name FROM " . PRO_ATTENDEES_TABLE . ' a
    			JOIN ' . PRO_EVENT_TABLE . ' e ON e.id = a.rsvpEventID
    			WHERE a.id IN (SELECT attendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . ' WHERE associatedAttendeeID = %d)
    			OR a.id in (SELECT associatedAttendeeID FROM ' . PRO_ASSOCIATED_ATTENDEES_TABLE . " WHERE attendeeID = %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)))';

		$associations = $wpdb->get_results( $wpdb->prepare( $sql, $attendee->id, $attendee->id ) );
		$assoc_names  = '';
		foreach ( $associations as $assc ) {
			$assocName = stripslashes( $assc->name );
			$assocName = rsvp_pro_handle_text_encoding( $assocName );
			if ( ! empty( $assoc_names ) ) {
				$assoc_names .= ', ';
			}
			$assoc_names .= trim( $assocName );
		}
		$csv .= trim( $assoc_names ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_passcode', rsvp_pro_require_passcode( $event_id ) ) ) {
		$csv .= '"' . ( ( $attendee->passcode ) ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_alternate_passcode', rsvp_pro_require_passcode( $event_id ) ) ) {
		$csv .= '"' . ( ( $attendee->alternate_passcode ) ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_custom_message', true ) ) {
		$csv .= '"' . ( str_replace( '"', '""', stripslashes( $attendee->personalGreeting ) ) ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_email', true ) ) {
		$csv .= '"' . stripslashes( $attendee->email ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_num_guests_allowed', true ) ) {
		$csv .= '"' . $attendee->numGuests . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_note', true ) ) {
		$csv .= '"' . ( str_replace( '"', '""', stripslashes( $attendee->note ) ) ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_primary_attendee', true ) ) {
		$csv .= '"' . ( ( $attendee->primaryAttendee == 'Y' ) ? 'Yes' : 'No' ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_additional_attendee', true ) ) {
		$csv .= '"' . ( ( $attendee->additionalAttendee == 'Y' ) ? 'Yes' : 'No' ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_rsvp_date', true ) ) {
		$csv .= '"';
		if ( ! empty( $attendee->rsvpDate ) ) {
			$csv .= date( 'm/d/Y H:i:s', strToTime( $attendee->rsvpDate ) );
		}
		$csv .= '",';
	}

	$qRs = $wpdb->get_results(
		$wpdb->prepare(
			'SELECT q.id, question, permissionLevel, questionType,  
				(SELECT GROUP_CONCAT(answer) FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE questionID = q.id AND attendeeID = %d) AS answer,
				(SELECT COUNT(*) FROM ' . PRO_QUESTION_ATTENDEES_TABLE . ' WHERE questionID = q.id = attendeeID = %d) AS accessCount
				FROM ' . PRO_QUESTIONS_TABLE . ' q
				INNER JOIN ' . PRO_QUESTION_TYPE_TABLE . ' qt ON qt.id = q.questionTypeID 
			WHERE q.rsvpEventID = %d ORDER BY sortOrder, q.id',
			$attendee->id,
			$attendee->id,
			( $is_sub_event ) ? $sub_event_id : $event_id
		)
	);
	if ( count( $qRs ) > 0 ) {
		foreach ( $qRs as $q ) {
			if ( rsvp_pro_admin_export_include_column( 'export_custom_question_' . $q->id, true ) ) {
				if ( ! empty( $q->answer ) ) {
					if ( QT_PRO_FILE === $q->questionType ) {
						$csv .= '"' . wp_get_attachment_url( $q->answer ) . '",';
					} else {
						$csv .= '"' . stripslashes( $q->answer ) . '",';	
					}
				} else {
					$csv .= '"",';
				}

				if ( $q->permissionLevel == 'private' ) {
					$csv .= '"' . ( ( $q->accessCount > 0 ) ? 'Y' : 'N' ) . '",';
				}
			}
		}
	}

	if ( rsvp_pro_admin_export_include_column( 'export_prefill_url', ( $custom_link_base != '' ) ) ) {
		if ( rsvp_pro_require_only_passcode_to_register( $event_id ) ) {
			$csv .= '"' . sprintf( $custom_link_base, urlencode( stripslashes( $attendee->passcode ) ) ) . '",';
		} elseif ( rsvp_pro_require_passcode( $event_id ) ) {
			$csv .= '"' . sprintf( $custom_link_base, urlencode( stripslashes( $attendee->firstName ) ), urlencode( stripslashes( $attendee->lastName ) ), urlencode( stripslashes( $attendee->passcode ) ) ) . '",';
		} else {
			$csv .= '"' . sprintf( $custom_link_base, urlencode( stripslashes( $attendee->firstName ) ), urlencode( stripslashes( $attendee->lastName ) ) ) . '",';
		}
	}

	if ( $include_sub_info ) {
		$sql  = 'SELECT e.id, eventName, rsvpStatus
				FROM ' . PRO_EVENT_TABLE . ' e
				LEFT JOIN ' . PRO_ATTENDEE_SUB_EVENTS_TABLE . ' se ON se.rsvpEventID = e.id AND se.rsvpAttendeeID = %d
				WHERE parentEventID = %d
				ORDER BY e.id ';
		$subs = $wpdb->get_results( $wpdb->prepare( $sql, $attendee->id, $event_id ) );

		foreach ( $subs as $s ) {
			$csv .= '"' . stripslashes( $s->rsvpStatus ) . '",';

			$qRs = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT q.id, question, permissionLevel,
						(SELECT GROUP_CONCAT(answer) FROM ' . PRO_ATTENDEE_ANSWERS . ' WHERE questionID = q.id AND attendeeID = %d) AS answer,
						(SELECT COUNT(*) FROM ' . PRO_QUESTION_ATTENDEES_TABLE . ' WHERE questionID = q.id = attendeeID = %d) AS accessCount
						FROM ' . PRO_QUESTIONS_TABLE . ' q
					WHERE q.rsvpEventID = %d ORDER BY sortOrder, q.id',
					$attendee->id,
					$attendee->id,
					$s->id
				)
			);
			if ( count( $qRs ) > 0 ) {
				foreach ( $qRs as $q ) {
					if ( ! empty( $q->answer ) ) {
						$csv .= '"' . stripslashes( $q->answer ) . '",';
					} else {
						$csv .= '"",';
					}

					if ( $q->permissionLevel == 'private' ) {
						$csv .= '"' . ( ( $q->accessCount > 0 ) ? 'Y' : 'N' ) . '",';
					}
				}
			}
		}
	}

	if ( rsvp_pro_admin_export_include_column( 'export_checked_in', ( rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_ALLOW_CHECKINS ) === 'Y' ) ) ) {
		$csv .= '"' . ( ( $attendee->checked_in == 'Y' ) ? 'Yes' : 'No' ) . '",';
	}

	if ( rsvp_pro_admin_export_include_column( 'export_change_log', false ) ) {
		$csv             .= '"';
		$sql              = 'SELECT changes, change_date FROM ' . PRO_ATTENDEE_CHANGELOG . ' WHERE attendeeID = %d ';
		$changes          = $wpdb->get_results( $wpdb->prepare( $sql, $attendee->id ) );
		$changed_to_label = rsvp_pro_get_admin_string( 'changed_to_label' );
		foreach ( $changes as $c ) {
			$csv .= date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $c->change_date ) ) . ': ';

			$attendee_changes = json_decode( stripslashes( $c->changes ) );
			foreach ( $attendee_changes as $change ) {
				if ( is_object( $change ) ) {
					$csv .= $change->field . ': ' . $change->old_value .
							' ' . $changed_to_label .
							' ' . $change->new_value . "\r\n";
				}
			}
			$csv .= "\r\n-------\r\n";
		}

		$csv .= '",';
	}

	$csv .= "\r\n";

	return $csv;
}

/**
 * Checks to see if the current field should be included in the export.
 *
 * @param  string  $column_name The columns name form field we should be checking
 * @param  boolean $include_by_default If we should include this column by default
 *
 * @return boolean                     True if we should include the column, false otherwise
 */
function rsvp_pro_admin_export_include_column( $column_name, $include_by_default = true ) {
	// If there are no $_POST elements then that means the export was called directly with
	// a link and there was no chance for a user to select the fields to export so we
	// should use the default value
	if ( count( $_POST ) > 0 ) {
		if ( isset( $_POST[ $column_name ] ) && ( 'Y' === $_POST[ $column_name ] ) ) {
			return true;
		}

		return false;
	}

	return $include_by_default;
}

/**
 * Saves the selected export columns for this event so that they can be reused again next time a user
 * wants to export.
 *
 * @param  int $event_id The event ID we want to saved the exported columns for.
 */
function rsvp_pro_save_export_columns( $event_id ) {
	if ( 0 < count( $_POST ) ) {
		$saved_columns = array();
		foreach ( $_POST as $key => $value ) {
			if ( 0 === strpos( $key, 'export_' ) ) {
				$saved_columns[] = $key;
			}
		}

		$options = new Rsvp_Pro_Event_Options( $event_id );
		$options->set_export_columns( $saved_columns );
		$options->save_options();
	}
}

/**
 * Displays the attendee export form so users can select which fields they can
 * export.
 *
 * @param  int $event_id The event to show the export information for.
 */
function rsvp_pro_admin_export_attendees_form( $event_id ) {
	global $wpdb;
	$selected_columns = array(
		'export_salutation',
		'export_first_name',
		'export_last_name',
		'export_suffix',
		'export_rsvp_status',
		'export_passcode',
		'export_associated_attendees',
		'export_custom_message',
		'export_email',
		'export_num_guests_allowed',
		'export_note',
		'export_primary_attendee',
		'export_additional_attendee',
		'export_rsvp_date',
		'export_prefill_url',
		'export_checked_in',
	);
	$sql              = 'SELECT id, question FROM ' . PRO_QUESTIONS_TABLE . ' WHERE rsvpEventID = %d ORDER BY sortOrder';
	$custom_questions = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
	foreach ( $custom_questions as $cq ) {
		$selected_columns[] = 'export_custom_question_' . $cq->id;
	}

	$saved_columns = rsvp_pro_get_event_option( $event_id, RSVP_PRO_OPTION_SAVED_EXPORT_COLUMNS );
	if ( is_array( $saved_columns ) && ( 0 < count( $saved_columns ) ) ) {
		$selected_columns = $saved_columns;
	}
	?>
	<div class="wrap">
		<h2><?php echo rsvp_pro_get_event_name( $event_id ); ?> -
			<?php echo rsvp_pro_get_admin_string( 'export_attendees_label' ); ?></h2>
	</div>
	<div class="wrap">
		<form name="attendee_export_form" method="post"
			  action="<?php echo admin_url( 'admin.php?page=rsvp-pro-top-level&action=export&eventID=' . $event_id ); ?>">
			<?php
			if ( isset( $_POST['sortValue'] ) && ! empty( $_POST['sortValue'] ) ) {
				?>
				<input type="hidden" name="sortValue" value="<?php echo esc_attr( $_POST['sortValue'] ); ?>"/>
				<?php
			}

			if ( isset( $_POST['exportSortDirection'] ) && ! empty( $_POST['exportSortDirection'] ) ) {
				?>
				<input type="hidden" name="exportSortDirection"
					   value="<?php echo esc_attr( $_POST['exportSortDirection'] ); ?>"/>
				<?php
			}
			?>
			<p><?php echo rsvp_pro_get_admin_string( 'export_select_columns_text' ); ?></p>
			<p>
				<label>
					<input type="checkbox" name="export_salutation"
						   value="Y" <?php echo in_array( 'export_salutation', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'salutation_text' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_first_name"
						   value="Y" <?php echo in_array( 'export_first_name', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'first_name_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_last_name"
						   value="Y" <?php echo in_array( 'export_last_name', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'last_name_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_suffix"
						   value="Y" <?php echo in_array( 'export_suffix', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'suffix_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_rsvp_status"
						   value="Y" <?php echo in_array( 'export_rsvp_status', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'rsvp_status_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_passcode"
						   value="Y" <?php echo in_array( 'export_passcode', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'passcode_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_alternate_passcode"
						   value="Y" <?php echo in_array( 'export_alternate_passcode', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'alternate_passcode_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_associated_attendees"
						   value="Y" <?php echo in_array( 'export_associated_attendees', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'associated_attendees_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_custom_message"
						   value="Y" <?php echo in_array( 'export_custom_message', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'custom_message_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_email"
						   value="Y" <?php echo in_array( 'export_email', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_frontend_string( 'email_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_num_guests_allowed"
						   value="Y" <?php echo in_array( 'export_num_guests_allowed', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'number_guests_allowed_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_note"
						   value="Y" <?php echo in_array( 'export_note', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'note_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_primary_attendee"
						   value="Y" <?php echo in_array( 'export_primary_attendee', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'primary_attendee_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_additional_attendee"
						   value="Y" <?php echo in_array( 'export_additional_attendee', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'additional_attendee_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_rsvp_date"
						   value="Y" <?php echo in_array( 'export_rsvp_date', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'rsvp_date_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_prefill_url"
						   value="Y" <?php echo in_array( 'export_prefill_url', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'prefill_url_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_checked_in"
						   value="Y" <?php echo in_array( 'export_checked_in', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'checked_in_label' ); ?>
				</label>
			</p>
			<p>
				<label>
					<input type="checkbox" name="export_change_log"
						   value="Y" <?php echo in_array( 'export_change_log', $selected_columns ) ? 'checked' : ''; ?> />
					<?php echo rsvp_pro_get_admin_string( 'change_log_label' ); ?>
				</label>
			</p>
			<?php
			$sql              = 'SELECT id, question FROM ' . PRO_QUESTIONS_TABLE . ' WHERE rsvpEventID = %d ORDER BY sortOrder';
			$custom_questions = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
			foreach ( $custom_questions as $cq ) {
				?>
				<p>
					<label>
						<input type="checkbox" name="export_custom_question_<?php echo $cq->id; ?>"
							   value="Y" <?php echo in_array( 'export_custom_question_' . $cq->id, $selected_columns ) ? 'checked' : ''; ?> />
						<?php echo esc_html( stripslashes( $cq->question ) ); ?>
					</label>
				</p>
				<?php
			}
			?>
			<br/>
			<p>
				<input type="submit" class="button-primary"
					   value="<?php echo rsvp_pro_get_admin_string( 'export_attendees_label' ); ?>"/>
			</p>
		</form>
	</div>
	<?php
}
