<?php
/**
 * Admin View: Bookings Export
 *
 * Mirrors the WooCommerce core product export page so the look-and-feel matches
 * (centered card under .wrap.woocommerce, .woocommerce-exporter form, progress + button).
 *
 * @package WooCommerce Bookings
 * @since   3.6.0
 * @version 3.6.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$exporter        = new WC_Bookings_CSV_Exporter();
$default_columns = $exporter->get_default_column_names();
$request_filters = WC_Bookings_Admin_Exporters::get_request_filters();
$has_filters     = ! empty( $request_filters );

$booking_ids_to_export    = array();
$is_exporting_booking_ids = false;

if ( ! empty( $_GET['booking_ids'] ) ) {
	check_admin_referer( 'export-selected-bookings' );

	$ids_raw                  = explode( ',', sanitize_text_field( wp_unslash( $_GET['booking_ids'] ) ) );
	$booking_ids_to_export    = array_values( array_filter( array_map( 'absint', $ids_raw ) ) );
	$is_exporting_booking_ids = ! empty( $booking_ids_to_export );
}

// When exporting an explicit selection, list-table filter carryover is irrelevant.
if ( $is_exporting_booking_ids ) {
	$has_filters     = false;
	$request_filters = array();
}

$bookable_products = ! $is_exporting_booking_ids ? WC_Bookings_Admin::get_booking_products() : array();
$booking_statuses  = ! $is_exporting_booking_ids
	? array_merge(
		get_wc_booking_statuses( null, true ),
		get_wc_booking_statuses( 'user', true ),
		get_wc_booking_statuses( 'cancel', true )
	)
	: array();

// Human-readable labels for the carried-over filters, used in the inline notice.
$filter_descriptions = array();
if ( $has_filters ) {
	if ( ! empty( $request_filters['m'] ) && 6 === strlen( (string) $request_filters['m'] ) ) {
		$filter_year           = substr( (string) $request_filters['m'], 0, 4 );
		$filter_month          = substr( (string) $request_filters['m'], 4, 2 );
		$ts                    = strtotime( $filter_year . '-' . $filter_month . '-01' );
		$filter_descriptions[] = sprintf(
			/* translators: %s: month/year label e.g. April 2026 */
			__( 'Month: %s', 'woocommerce-bookings' ),
			$ts ? date_i18n( 'F Y', $ts ) : esc_html( $request_filters['m'] )
		);
	}

	if ( ! empty( $request_filters['post_status'] ) ) {
		$statuses              = function_exists( 'get_wc_booking_statuses' )
			? array_merge(
				get_wc_booking_statuses( null, true ),
				get_wc_booking_statuses( 'user', true ),
				get_wc_booking_statuses( 'cancel', true )
			)
			: array();
		$status_label          = isset( $statuses[ $request_filters['post_status'] ] ) ? $statuses[ $request_filters['post_status'] ] : $request_filters['post_status'];
		$filter_descriptions[] = sprintf(
			/* translators: %s: booking status label */
			__( 'Status: %s', 'woocommerce-bookings' ),
			$status_label
		);
	}

	if ( ! empty( $request_filters['filter_bookings'] ) ) {
		$filter_id             = absint( $request_filters['filter_bookings'] );
		$filter_post           = $filter_id ? get_post( $filter_id ) : null;
		$filter_label          = $filter_post ? $filter_post->post_title : '#' . $filter_id;
		$filter_descriptions[] = sprintf(
			/* translators: %s: bookable product or resource title */
			__( 'Product: %s', 'woocommerce-bookings' ),
			$filter_label
		);
	}
}

$clear_filters_url = remove_query_arg( WC_Bookings_Admin_Exporters::FILTER_PARAMS );
?>
<style>
	.woocommerce-exporter .woocommerce-exporter-date-range {
		display: grid;
		grid-template-columns: minmax(0, 220px) minmax(0, 220px);
		gap: 8px 16px;
		margin-top: 8px;
		max-width: 460px;
	}
	.woocommerce-exporter .woocommerce-exporter-date-range label {
		display: flex;
		flex-direction: column;
		font-weight: 500;
		gap: 4px;
	}
	.woocommerce-exporter .woocommerce-exporter-date-range input[type="date"] {
		width: 100%;
		box-sizing: border-box;
	}
</style>
<div class="wrap woocommerce">
	<h1><?php esc_html_e( 'Export Bookings', 'woocommerce-bookings' ); ?></h1>

	<?php if ( $is_exporting_booking_ids ) : ?>
		<?php
		$clear_selection_url = remove_query_arg( array( 'booking_ids', '_wpnonce' ) );
		$count               = count( $booking_ids_to_export );
		$selection_notice    = sprintf(
			/* translators: %1$d: Number of bookings, %2$s: URL to clear selection. */
			_n(
				'You are about to export %1$d booking. To export all bookings, <a href="%2$s">clear your selection</a>.',
				'You are about to export %1$d bookings. To export all bookings, <a href="%2$s">clear your selection</a>.',
				$count,
				'woocommerce-bookings'
			),
			$count,
			esc_url( $clear_selection_url )
		);
		?>
		<div id="bookings-export-selection-notice" class="notice notice-info inline">
			<p><?php echo wp_kses_post( $selection_notice ); ?></p>
		</div>
	<?php elseif ( $has_filters ) : ?>
		<div id="bookings-export-filters-notice" class="notice notice-info inline">
			<p>
				<?php
				printf(
					/* translators: 1: list of filters separated by middots, 2: URL to clear filters. */
					wp_kses_post( __( 'Filters applied from Bookings list &mdash; %1$s. <a href="%2$s">Clear filters</a> to export all bookings.', 'woocommerce-bookings' ) ),
					esc_html( implode( ' &middot; ', $filter_descriptions ) ),
					esc_url( $clear_filters_url )
				);
				?>
			</p>
		</div>
	<?php endif; ?>

	<div class="woocommerce-exporter-wrapper">
		<form class="woocommerce-exporter">
			<?php
			// Hidden inputs preserve either the explicit booking-ID selection or the carried-over list-table filters.
			if ( $is_exporting_booking_ids ) {
				printf( '<input type="hidden" name="booking_ids" value="%s" />', esc_attr( implode( ',', $booking_ids_to_export ) ) );
			} else {
				foreach ( $request_filters as $name => $value ) {
					printf( '<input type="hidden" name="%s" value="%s" />', esc_attr( $name ), esc_attr( $value ) );
				}
			}
			?>
			<header>
				<span class="spinner is-active"></span>
				<h2><?php esc_html_e( 'Export bookings to a CSV file', 'woocommerce-bookings' ); ?></h2>
				<p>
					<?php
					if ( $is_exporting_booking_ids ) {
						esc_html_e( 'This tool generates and downloads a CSV file containing the selected bookings.', 'woocommerce-bookings' );
					} else {
						esc_html_e( 'This tool generates and downloads a CSV file containing your bookings.', 'woocommerce-bookings' );
					}
					?>
				</p>
			</header>
			<section>
				<table class="form-table woocommerce-exporter-options">
					<tbody>
						<tr>
							<th scope="row">
								<label for="woocommerce-exporter-columns"><?php esc_html_e( 'Which columns should be exported?', 'woocommerce-bookings' ); ?></label>
							</th>
							<td>
								<select id="woocommerce-exporter-columns" class="woocommerce-exporter-columns wc-enhanced-select" style="width:100%;" multiple data-placeholder="<?php esc_attr_e( 'Export all columns', 'woocommerce-bookings' ); ?>">
									<?php foreach ( $default_columns as $column_id => $column_name ) : ?>
										<option value="<?php echo esc_attr( $column_id ); ?>"><?php echo esc_html( $column_name ); ?></option>
									<?php endforeach; ?>
								</select>
							</td>
						</tr>
						<?php if ( ! $is_exporting_booking_ids ) : ?>
						<tr>
							<th scope="row">
								<label for="woocommerce-exporter-products"><?php esc_html_e( 'Bookable products', 'woocommerce-bookings' ); ?></label>
							</th>
							<td>
								<select id="woocommerce-exporter-products" class="woocommerce-exporter-products wc-enhanced-select" style="width:100%;" multiple data-placeholder="<?php esc_attr_e( 'Export all bookable products', 'woocommerce-bookings' ); ?>">
									<?php foreach ( $bookable_products as $product ) : ?>
										<option value="<?php echo esc_attr( $product->get_id() ); ?>"><?php echo esc_html( $product->get_name() ); ?></option>
									<?php endforeach; ?>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="woocommerce-exporter-statuses"><?php esc_html_e( 'Booking statuses', 'woocommerce-bookings' ); ?></label>
							</th>
							<td>
								<select id="woocommerce-exporter-statuses" class="woocommerce-exporter-statuses wc-enhanced-select" style="width:100%;" multiple data-placeholder="<?php esc_attr_e( 'Export all statuses', 'woocommerce-bookings' ); ?>">
									<?php foreach ( $booking_statuses as $status_key => $status_label ) : ?>
										<option value="<?php echo esc_attr( $status_key ); ?>"><?php echo esc_html( $status_label ); ?></option>
									<?php endforeach; ?>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="woocommerce-exporter-date-range-toggle"><?php esc_html_e( 'Custom date range?', 'woocommerce-bookings' ); ?></label>
							</th>
							<td>
								<input type="checkbox" id="woocommerce-exporter-date-range-toggle" value="1" />
								<label for="woocommerce-exporter-date-range-toggle"><?php esc_html_e( 'Yes, only export bookings within a specific range', 'woocommerce-bookings' ); ?></label>
								<div class="woocommerce-exporter-date-range" style="display:none;">
									<label for="woocommerce-exporter-date-from">
										<span><?php esc_html_e( 'From', 'woocommerce-bookings' ); ?></span>
										<input type="date" id="woocommerce-exporter-date-from" class="woocommerce-exporter-date-from" />
									</label>
									<label for="woocommerce-exporter-date-to">
										<span><?php esc_html_e( 'To', 'woocommerce-bookings' ); ?></span>
										<input type="date" id="woocommerce-exporter-date-to" class="woocommerce-exporter-date-to" />
									</label>
								</div>
							</td>
						</tr>
							<?php if ( $has_filters ) : ?>
						<tr>
							<th scope="row">
								<label for="woocommerce-exporter-filtered"><?php esc_html_e( 'Limit to filtered bookings?', 'woocommerce-bookings' ); ?></label>
							</th>
							<td>
								<input type="checkbox" id="woocommerce-exporter-filtered" name="apply_filters" value="1" checked />
								<label for="woocommerce-exporter-filtered"><?php esc_html_e( 'Yes, only export bookings matching the Bookings list filters above', 'woocommerce-bookings' ); ?></label>
							</td>
						</tr>
						<?php endif; ?>
						<?php endif; // ! $is_exporting_booking_ids ?>
						<tr>
							<th scope="row">
								<label for="woocommerce-exporter-meta"><?php esc_html_e( 'Export custom meta?', 'woocommerce-bookings' ); ?></label>
							</th>
							<td>
								<input type="checkbox" id="woocommerce-exporter-meta" value="1" />
								<label for="woocommerce-exporter-meta"><?php esc_html_e( 'Yes, export all custom meta', 'woocommerce-bookings' ); ?></label>
							</td>
						</tr>
						<?php
						/**
						 * Fires inside the bookings exporter options table to let third parties inject extra rows.
						 *
						 * @since 3.6.0
						 */
						do_action( 'woocommerce_bookings_export_row' );
						?>
					</tbody>
				</table>
				<progress class="woocommerce-exporter-progress" max="100" value="0"></progress>
			</section>
			<div class="wc-actions">
				<button type="submit" class="woocommerce-exporter-button button button-primary" value="<?php esc_attr_e( 'Generate CSV', 'woocommerce-bookings' ); ?>"><?php esc_html_e( 'Generate CSV', 'woocommerce-bookings' ); ?></button>
			</div>
		</form>
	</div>
</div>
