<?php
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

/**
 * Handles the importing of the attendees.
 *
 * @param int    $event_id The event ID we are importing for.
 * @param string $import_file The path to the file we want to import attendees from.
 */
function rsvp_pro_admin_import_handle_attendee_import( $event_id, $import_file ) {
	if ( isset( $_POST['delete_existing_attendees'] ) && ( 'Y' === $_POST['delete_existing_attendees'] ) ) {
		rsvp_pro_delete_attendee_from_event( $event_id );
	}

	$file_type = rsvp_pro_import_get_file_type( $import_file );
	$reader    = ReaderFactory::create( $file_type );
	$reader->open( $import_file );

	$i               = 0;
	$possible_fields = rsvp_pro_import_get_possible_fields( $event_id );
	$mapped_columns  = array();

	/*
	 * Loop the possible fields and store an array of columns to fields
	 * which we will use during the import process.
	 */
	foreach ( $possible_fields as $sections ) {
		foreach ( $sections['fields'] as $field ) {
			$field_key = $field['value'];
			if ( isset( $_POST[ $field_key ] ) && is_numeric( $_POST[ $field_key ] ) && ( 0 <= $_POST[ $field_key ] ) ) {
				$mapped_columns[ $field_key ] = $_POST[ $field_key ];
			}
		}
	}

	if ( 0 < count( $mapped_columns ) ) {
		$count = 0;

		foreach ( $reader->getSheetIterator() as $sheet ) {
			foreach ( $sheet->getRowIterator() as $row ) {
				if ( $i > 0 ) { // We want to skip the first row.
					rsvp_pro_handle_import_row( $row, $mapped_columns, $count, $event_id );
				}
				$i++;
			}
			break;
		}
		?>
		<p><strong><?php echo $count; ?></strong> <?php echo rsvp_pro_get_admin_string( 'total_imported_label' ); ?>.</p>
		<p><?php echo rsvp_pro_get_admin_string( 'continue_to_rsvp_label' ); ?> <a href="admin.php?page=rsvp-pro-top-level"><?php echo rsvp_pro_get_admin_string( 'list_label' ); ?></a></p>
		<?php
	}

	$reader->close();
}

/**
 * Stores the file temporarily and tries to parse the file to
 * allow for the user to select which column goes to which field.
 *
 * @param int $event_id The event ID we are trying to import attendees for.
 */
function rsvp_pro_admin_import_column_selection( $event_id ) {
	// Check for a file and then try to parse it.
	$file_type = rsvp_pro_import_get_file_type( $_FILES['importFile']['name'] );
	if ( null === $file_type ) {
		// TODO: Add in a message of why...
		rsvp_pro_admin_import_file_selection_form( $event_id );
		return;
	}
	$reader = ReaderFactory::create( $file_type );
	$reader->open( $_FILES['importFile']['tmp_name'] );

	foreach ( $reader->getSheetIterator() as $sheet ) {
		foreach ( $sheet->getRowIterator() as $row ) {
			$header_row = $row;
			break;
		}
		break;
	}
	$reader->close();

	$possible_fields = rsvp_pro_import_get_possible_fields( $event_id );
	$extension       = pathinfo( $_FILES['importFile']['name'], PATHINFO_EXTENSION );
	$tmp_file_name   = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp_import_' . uniqid() . '.' . $extension;
	move_uploaded_file( $_FILES['importFile']['tmp_name'], $tmp_file_name );
	$transient_name = 'rsvp_import_' . uniqid();
	set_transient( $transient_name, $tmp_file_name, 6 * HOUR_IN_SECONDS );
	?>
	<h3><?php echo rsvp_pro_get_event_name( $event_id ); ?> - 
		<?php echo rsvp_pro_get_admin_string( 'attendee_import_title_step_2' ); ?></h3>
	<form name="rsvp_import" id="rsvp_import_column_select" method="post">
		<input type="hidden" name="step" value="header_selection" />
		<input type="hidden" name="event_id" value="<?php echo esc_attr( $event_id ); ?>" />
		<input type="hidden" name="transient_key" value="<?php echo esc_attr( $transient_name ); ?>" />
		<input type="hidden" name="delete_existing_attendees" value="<?php echo ( isset( $_POST['delete_existing_attendees'] ) && ( 'Y' == $_POST['delete_existing_attendees'] ) ) ? 'Y' : 'N'; ?>" />
	<?php echo rsvp_pro_get_admin_string( 'attendee_import_column_selection_message' ); ?>
	<table class="form-table">
		<tbody>
	<?php
	foreach ( $possible_fields as $field_group ) {
		?>
			<tr>
				<th scope="row" colspan="2">
					<h3><?php echo esc_html( $field_group['friendly_name'] ); ?></h3>
				</th>
			</tr>
			<?php
			foreach ( $field_group['fields'] as $field ) {
				?>
			<tr>
				<th scope="row">
					<label for="<?php echo esc_attr( $field['value'] ); ?>"><?php echo esc_html( $field['name'] ); ?></label>
				</th>
				<td>
					<select name="<?php echo esc_attr( $field['value'] ); ?>" id="<?php echo esc_attr( $field['value'] ); ?>" size="1">
						<option value="">--</option>
					<?php
					foreach ( $header_row as $idx => $row ) {
						?>
						<option value="<?php echo esc_attr( $idx ); ?>"><?php echo esc_html( $row ); ?></option>
						<?php
					}
					?>
					</select>
				</td>
			</tr>
				<?php
			}
	}
	?>
		</tbody>
	</table>
		<p><input type="submit" value="Import Attendees" name="goRsvp" /></p>
	</form>
	<?php
}

/**
 * Displays the first step of the import process form. This will allow
 * a user to select a file to upload to be imported.
 *
 * @param  int $event_id The event ID we are importing attendees for.
 */
function rsvp_pro_admin_import_file_selection_form( $event_id ) {
	?>
	<h3><?php echo rsvp_pro_get_event_name( $event_id ); ?> - 
		<?php echo rsvp_pro_get_admin_string( 'attendee_import_title_step_1' ); ?></h3>
	<form name="rsvp_import" method="post" enctype="multipart/form-data">
		<input type="hidden" name="step" value="initial" />
		<?php wp_nonce_field( 'rsvp-import' ); ?>
	<p><?php echo rsvp_pro_get_admin_string( 'attendee_import_excel_message' ); ?></p>
	<p>
		<label>
			<?php echo rsvp_pro_get_admin_string( 'delete_attendees_import_label' ); ?>:
			<input type="checkbox" name="delete_existing_attendees" value="Y" />
		</label>
	</p>
	<p><input type="file" name="importFile" id="importFile" /></p>
	<p><input type="submit" value="Next &raquo;" name="goRsvp" /></p>
</form>
	<?php
}

/**
 * Handles importing of attendees.
 *
 * @param  int $event_id The event ID we want to import attendees for.
 */
function rsvp_pro_admin_import( $event_id ) {
	global $wpdb;

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

	require RSVP_PRO_PLUGIN_PATH . '/external-libs/spout/src/Spout/Autoloader/autoload.php';
	require RSVP_PRO_PLUGIN_PATH . '/includes/admin/import_handlers.inc.php';

	if ( isset( $_POST['step'] ) && ( 'initial' === $_POST['step'] ) && ( count( $_FILES ) > 0 ) ) {
		check_admin_referer( 'rsvp-import' );
		rsvp_pro_admin_import_column_selection( $event_id );
	} elseif ( isset( $_POST['step'] ) && ( 'header_selection' === $_POST['step'] ) && isset( $_POST['transient_key'] ) ) {
		$import_file = get_transient( $_POST['transient_key'] );

		if ( false !== $import_file && file_exists( $import_file ) ) {
			rsvp_pro_admin_import_handle_attendee_import( $event_id, $import_file );
			unlink( $import_file );
		} else {
			rsvp_pro_admin_import_file_selection_form( $event_id );
		}
	} else {
		rsvp_pro_admin_import_file_selection_form( $event_id );
	}
}

/**
 * Gets all of the possible fields people can use for importing into the database.
 *
 * @param  int $event_id The event ID we are importing attendees in for.
 * @return array           An array of possible fields people can import in for.
 */
function rsvp_pro_import_get_possible_fields( $event_id ) {
	global $wpdb;
	$possible_fields = array(
		'required'          => array(
			'friendly_name' => esc_html__('Required Fields','rsvp-pro-plugin'),
			'fields'        => array(
				array(
					'name'  => esc_html__('First name','rsvp-pro-plugin'),
					'value' => 'first_name',
				),
				array(
					'name'  => esc_html__('Last name','rsvp-pro-plugin'),
					'value' => 'last_name',
				),
			),
		),
		'additional_fields' => array(
			'friendly_name' => esc_html__('Additional Attendee Fields','rsvp-pro-plugin'),
			'fields'        => array(
				array(
					'name'  => esc_html__('Email address','rsvp-pro-plugin'),
					'value' => 'email',
				),
				array(
					'name'  => esc_html__('Salutation','rsvp-pro-plugin'),
					'value' => 'salutation',
				),
				array(
					'name'  => esc_html__('Suffix','rsvp-pro-plugin'),
					'value' => 'suffix',
				),
				array(
					'name'  => esc_html__('RSVP status','rsvp-pro-plugin'),
					'value' => 'rsvp_status',
				),
				array(
					'name'  => esc_html__('Associated Attendees','rsvp-pro-plugin'),
					'value' => 'associated_attendees',
				),
				array(
					'name'  => esc_html__('Passcode','rsvp-pro-plugin'),
					'value' => 'passcode',
				),
				array(
					'name'  => esc_html__('Alternate Passcode','rsvp-pro-plugin'),
					'value' => 'alternate_passcode',
				),
				array(
					'name'  => esc_html__('Custom message','rsvp-pro-plugin'),
					'value' => 'custom_message',
				),
				array(
					'name'  => esc_html__('Number of guests allowed per attendee','rsvp-pro-plugin'),
					'value' => 'num_guests',
				),
				array(
					'name'  => esc_html__('Note','rsvp-pro-plugin'),
					'value' => 'note',
				),
				array(
					'name'  => esc_html__('Primary attendee','rsvp-pro-plugin'),
					'value' => 'primary_attendee',
				),
				array(
					'name'  => esc_html__('Group ID','rsvp-pro-plugin'),
					'value' => 'group_id',
				),
			),
		),
	);

	if ( RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID === $event_id ) {
		$sql    = 'SELECT id, eventName FROM ' . PRO_EVENT_TABLE . ' WHERE (parentEventID IS NULL OR parentEventID = 0) AND id != %d';
		$events = $wpdb->get_results( $wpdb->prepare( $sql, RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID ) );
		foreach ( $events as $e ) {
			$tmp_field = array(
				'name'  => esc_html__('Number of guests allowed per attendee for event - ','rsvp-pro-plugin') . stripslashes_deep( $e->eventName ),
				'value' => 'num_guests_' . $e->id,
			);
			$possible_fields['additional_fields']['fields'][] = $tmp_field;
		}
	}

	$sql       = 'SELECT q.id, q.question, q.permissionLevel 
		FROM ' . PRO_QUESTIONS_TABLE . ' q 
		INNER JOIN ' . PRO_QUESTION_TYPE_TABLE . ' qt ON qt.id = q.questionTypeID 
		WHERE rsvpEventID = %d AND qt.questionType NOT IN (\'file\')';
	$questions = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
	$fields    = array();
	foreach ( $questions as $q ) {
		if ( 'private' == $q->permissionLevel ) {
			$fields[] = array(
				'name'  => esc_html__('Access to ','rsvp-pro-plugin') . htmlspecialchars( stripslashes( $q->question ) ),
				'value' => 'pq_' . $q->id,
			);
		}
		$fields[] = array(
			'name'  => esc_html__('Value for ','rsvp-pro-plugin') . htmlspecialchars( stripslashes( $q->question ) ),
			'value' => 'cq_' . $q->id,
		);
	}

	if ( 0 < count( $fields ) ) {
		$possible_fields['custom_questions'] = array(
			'friendly_name' => esc_html__('Custom Question Fields','rsvp-pro-plugin'),
			'fields'        => $fields,
		);
	}

	$sql = 'SELECT id, eventName FROM ' . PRO_EVENT_TABLE . ' WHERE (parentEventID = %d OR id = %d) AND event_access = \'select\'';

	if ( RSVP_PRO_GLOBAL_ATTENDEE_EVENT_ID === $event_id ) {
		$sql .= ' UNION SELECT id, eventName FROM ' . PRO_EVENT_TABLE . ' WHERE event_access = \'select\' ';
	}
	$subevents = $wpdb->get_results( $wpdb->prepare( $sql, $event_id, $event_id ) );
	$fields    = array();
	foreach ( $subevents as $se ) {
		$fields[] = array(
			'name'  => esc_html__('Access to - ','rsvp-pro-plugin') . esc_html( stripslashes( $se->eventName ) ),
			'value' => 'se_' . $se->id,
		);
	}

	if ( 0 < count( $fields ) ) {
		$possible_fields['subevent_access'] = array(
			'friendly_name' => esc_html__('Sub-Event Access','rsvp-pro-plugin'),
			'fields'        => $fields,
		);
	}

	$sql        = 'SELECT id, eventName FROM ' . PRO_EVENT_TABLE . ' WHERE parentEventID = %d';
	$sub_events = $wpdb->get_results( $wpdb->prepare( $sql, $event_id ) );
	foreach ( $sub_events as $se ) {
		$sql              = 'SELECT q.id, q.question, q.permissionLevel 
		FROM ' . PRO_QUESTIONS_TABLE . ' q 
		INNER JOIN ' . PRO_QUESTION_TYPE_TABLE . ' qt ON qt.id = q.questionTypeID 
		WHERE rsvpEventID = %d AND qt.questionType NOT IN (\'file\')';
		$custom_questions = $wpdb->get_results( $wpdb->prepare( $sql, $se->id ) );
		if ( count( $custom_questions ) > 0 ) {
			$tmp_fields = array();
			foreach ( $custom_questions as $cq ) {
				if ( 'private' == $cq->permissionLevel ) {
					$tmp_fields[] = array(
						'name'  => esc_html__('Access to ','rsvp-pro-plugin') . htmlspecialchars( stripslashes( $cq->question ) ),
						'value' => 'pq_' . $cq->id,
					);
				}
				$tmp_fields[] = array(
					'name'  => esc_html__('Value for ','rsvp-pro-plugin') . htmlspecialchars( stripslashes( $cq->question ) ),
					'value' => 'cq_' . $cq->id,
				);
			}
			$possible_fields[ 'subevent_questions_' . $se->id ] = array(
				'friendly_name' => esc_html( stripslashes_deep( $se->eventName ) ) . esc_html__(' Custom Question Fields','rsvp-pro-plugin'),
				'fields'        => $tmp_fields,
			);
		}
	}

	return $possible_fields;
}

/**
 * Gets the file type based on the users uploaded extension.
 *
 * @param  string $file_path The file name that the user uploaded for importing.
 * @return object            Null or the Spout type used for parsing the files.
 */
function rsvp_pro_import_get_file_type( $file_path ) {
	$ext = strtolower( pathinfo( $file_path, PATHINFO_EXTENSION ) );

	if ( 'csv' === $ext ) {
		return Type::CSV;
	} elseif ( 'xlsx' === $ext ) {
		return Type::XLSX;
	} elseif ( 'ods' === $ext ) {
		return Type::ODS;
	}

	return null;
}
