<?php
/**
 * admin/settings-page.php
 * Admin settings & Cars/Orders pages
 */

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


/**
 * -------------------------------------------------------------------------
 * Register settings
 * -------------------------------------------------------------------------
 */
add_action( 'admin_init', 'execvitr_register_settings' );
function execvitr_register_settings() {
	register_setting( 'execvitr_settings_group', 'execvitr_email',           [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_google_api_key',  [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_country',         [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_currency',        [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_km_price', [ 'sanitize_callback' => 'floatval' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_minimum_price', [ 'sanitize_callback' => 'floatval' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_max_distance', [ 'sanitize_callback' => 'floatval' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_whatsapp_number', [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_notify_admin',    [ 'sanitize_callback' => 'sanitize_email' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_notify_whatsapp', [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_distance_unit',   [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_enable_cash',     [ 'sanitize_callback' => 'sanitize_text_field' ] );
	register_setting( 'execvitr_settings_group', 'execvitr_enable_card',     [ 'sanitize_callback' => 'sanitize_text_field' ] );

	register_setting( 'execvitr_settings_group', 'execvitr_min_booking_hours', [ 'sanitize_callback' => 'absint' ] );

	// Cars option (array)
	register_setting(
		'execvitr_cars_group',
		'execvitr_cars',
		[
			'type'              => 'array',
			'sanitize_callback' => 'execvitr_sanitize_cars_option',
			'default'           => [],
		]
	);
}

/**
 * -------------------------------------------------------------------------
 * Settings page
 * -------------------------------------------------------------------------
 */
function execvitr_settings_page_html() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	echo '<div class="notice notice-info is-dismissible">';
	echo '<p><strong>' . esc_html__( '🚀 Setup Completed!', 'executive-vip-transfer-service' ) . '</strong></p>';
	echo '<p>' . wp_kses_post(
		sprintf(
			/* translators: %s: shortcode */
			__( 'You can now use the %s shortcode on any page to display the booking form.', 'executive-vip-transfer-service' ),
			'<code>[execvitr_form]</code>'
		)
	) . '</p>';

	$page_id = get_option( 'execvitr_form_page_id' ); // migrated
	if ( $page_id && get_post_status( $page_id ) === 'publish' ) {
		$url = get_permalink( $page_id );

		echo '<p>' . wp_kses_post(
			sprintf(
				/* translators: %s: URL of the automatically created page */
				__( '✅ Automatically created page: %s', 'executive-vip-transfer-service' ),
				'<a href="' . esc_url( $url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( $url ) . '</a>'
			)
		) . '</p>';
	}

	echo '</div>';
	?>

	<div class="wrap execvitr-admin execvitr-admin--settings">
		<h1><?php echo esc_html__( 'Executive VIP Transfer Settings', 'executive-vip-transfer-service' ); ?></h1>
		<form method="post" action="options.php">
			<?php settings_fields( 'execvitr_settings_group' ); ?>
			<?php do_settings_sections( 'execvitr_settings_group' ); ?>

			<table class="form-table">

				<tr>
					<th><?php echo esc_html__( 'Google Maps API Key', 'executive-vip-transfer-service' ); ?></th>
					<td>
						<input type="text" name="execvitr_google_api_key" value="<?php echo esc_attr( get_option( 'execvitr_google_api_key' ) ); ?>" class="vts-wide-input" />
						<p class="description">
							<?php echo esc_html__( 'Enter your Google Maps API Key to enable address autocomplete and distance calculation.', 'executive-vip-transfer-service' ); ?><br>
							<?php echo esc_html__( 'Required APIs that must be enabled from your Google Cloud Console:', 'executive-vip-transfer-service' ); ?>
						<ul class="vts-desc-list">
							<li><strong><?php echo esc_html__( 'Maps JavaScript API', 'executive-vip-transfer-service' ); ?></strong></li>
							<li><strong><?php echo esc_html__( 'Places API', 'executive-vip-transfer-service' ); ?></strong></li>
							<li><strong><?php echo esc_html__( 'Distance Matrix API', 'executive-vip-transfer-service' ); ?></strong></li>
						</ul>
						<?php
						echo wp_kses_post(
							sprintf(
								/* translators: 1: link start, 2: link end */
								__( 'Get your key at %1$sGoogle Cloud Console%2$s. Don’t forget to restrict the key for security.', 'executive-vip-transfer-service' ),
								'<a href="https://console.cloud.google.com/" target="_blank" rel="noopener noreferrer">',
								'</a>'
							)
						);
						?>
						</p>
					</td>
				</tr>

				<?php
				$selected_country = get_option( 'execvitr_country', 'TR' );
				$countries        = [
					'TR' => __( 'Turkey', 'executive-vip-transfer-service' ),
					'US' => __( 'United States', 'executive-vip-transfer-service' ),
					'GB' => __( 'United Kingdom', 'executive-vip-transfer-service' ),
					'DE' => __( 'Germany', 'executive-vip-transfer-service' ),
					'FR' => __( 'France', 'executive-vip-transfer-service' ),
					'IT' => __( 'Italy', 'executive-vip-transfer-service' ),
					'ES' => __( 'Spain', 'executive-vip-transfer-service' ),
					'CA' => __( 'Canada', 'executive-vip-transfer-service' ),
					'AU' => __( 'Australia', 'executive-vip-transfer-service' ),
					'NL' => __( 'Netherlands', 'executive-vip-transfer-service' ),
					'BE' => __( 'Belgium', 'executive-vip-transfer-service' ),
					'CH' => __( 'Switzerland', 'executive-vip-transfer-service' ),
					'AT' => __( 'Austria', 'executive-vip-transfer-service' ),
					'AE' => __( 'United Arab Emirates', 'executive-vip-transfer-service' ),
					'RU' => __( 'Russia', 'executive-vip-transfer-service' ),
					'IN' => __( 'India', 'executive-vip-transfer-service' ),
					'CN' => __( 'China', 'executive-vip-transfer-service' ),
					'JP' => __( 'Japan', 'executive-vip-transfer-service' ),
					'BR' => __( 'Brazil', 'executive-vip-transfer-service' ),
					'ZA' => __( 'South Africa', 'executive-vip-transfer-service' ),
					'PL' => __( 'Poland', 'executive-vip-transfer-service' ),
					'SE' => __( 'Sweden', 'executive-vip-transfer-service' ),
					'NO' => __( 'Norway', 'executive-vip-transfer-service' ),
					'FI' => __( 'Finland', 'executive-vip-transfer-service' ),
					'DK' => __( 'Denmark', 'executive-vip-transfer-service' ),
					'GR' => __( 'Greece', 'executive-vip-transfer-service' ),
					'RO' => __( 'Romania', 'executive-vip-transfer-service' ),
					'PT' => __( 'Portugal', 'executive-vip-transfer-service' ),
					'MX' => __( 'Mexico', 'executive-vip-transfer-service' ),
					'AR' => __( 'Argentina', 'executive-vip-transfer-service' ),
					'ID' => __( 'Indonesia', 'executive-vip-transfer-service' ),
					'MY' => __( 'Malaysia', 'executive-vip-transfer-service' ),
					'KR' => __( 'South Korea', 'executive-vip-transfer-service' ),
					'UA' => __( 'Ukraine', 'executive-vip-transfer-service' ),
					'IL' => __( 'Israel', 'executive-vip-transfer-service' ),
					'IR' => __( 'Iran', 'executive-vip-transfer-service' ),
					'SA' => __( 'Saudi Arabia', 'executive-vip-transfer-service' ),
				];
				?>
				<tr>
					<th><?php echo esc_html__( 'Country', 'executive-vip-transfer-service' ); ?></th>
					<td>
						<select name="execvitr_country" class="vts-wide-input">
							<?php foreach ( $countries as $code => $label ) : ?>
								<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $selected_country, $code ); ?>>
									<?php echo esc_html( $label ); ?>
								</option>
							<?php endforeach; ?>
						</select>
						<p class="description"><?php echo esc_html__( 'Google Maps autocomplete is limited to the selected country.', 'executive-vip-transfer-service' ); ?></p>
					</td>
				</tr>

				<?php
				$selected_currency = get_option( 'execvitr_currency', 'USD' );
				$currencies        = [
					'USD' => __( '$ US Dollar', 'executive-vip-transfer-service' ),
					'EUR' => __( '€ Euro', 'executive-vip-transfer-service' ),
					'GBP' => __( '£ British Pound', 'executive-vip-transfer-service' ),
					'TRY' => __( '₺ Turkish Lira', 'executive-vip-transfer-service' ),
					'CAD' => __( 'C$ Canadian Dollar', 'executive-vip-transfer-service' ),
					'AUD' => __( 'A$ Australian Dollar', 'executive-vip-transfer-service' ),
					'CHF' => __( 'CHF Swiss Franc', 'executive-vip-transfer-service' ),
					'JPY' => __( '¥ Japanese Yen', 'executive-vip-transfer-service' ),
					'CNY' => __( '¥ Chinese Yuan', 'executive-vip-transfer-service' ),
					'AED' => __( 'د.إ UAE Dirham', 'executive-vip-transfer-service' ),
					'INR' => __( '₹ Indian Rupee', 'executive-vip-transfer-service' ),
					'BRL' => __( 'R$ Brazilian Real', 'executive-vip-transfer-service' ),
					'ZAR' => __( 'R South African Rand', 'executive-vip-transfer-service' ),
					'KRW' => __( '₩ South Korean Won', 'executive-vip-transfer-service' ),
					'MXN' => __( '$ Mexican Peso', 'executive-vip-transfer-service' ),
				];
				?>
				<tr>
					<th><?php echo esc_html__( 'Currency', 'executive-vip-transfer-service' ); ?></th>
					<td>
						<select name="execvitr_currency" class="vts-wide-input">
							<?php foreach ( $currencies as $code => $label ) : ?>
								<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $selected_currency, $code ); ?>>
									<?php echo esc_html( $label ); ?>
								</option>
							<?php endforeach; ?>
						</select>
						<p class="description"><?php echo esc_html__( 'All prices and symbols will be displayed in the selected currency.', 'executive-vip-transfer-service' ); ?></p>
					</td>
				</tr>

				<tr>
					<th><?php echo esc_html__( 'Distance Unit', 'executive-vip-transfer-service' ); ?></th>
					<td>
						<?php $unit = get_option( 'execvitr_distance_unit', 'km' ); ?>
						<select name="execvitr_distance_unit" class="vts-wide-input">
							<option value="km" <?php selected( $unit, 'km' ); ?>><?php echo esc_html__( 'Kilometers (km)', 'executive-vip-transfer-service' ); ?></option>
							<option value="mi" <?php selected( $unit, 'mi' ); ?>><?php echo esc_html__( 'Miles (mi)', 'executive-vip-transfer-service' ); ?></option>
						</select>
						<p class="description"><?php echo esc_html__( 'Controls distance display and pricing calculations.', 'executive-vip-transfer-service' ); ?></p>
					</td>
				</tr>

				<tr>
					<th>
						<?php
						$unit = get_option( 'execvitr_distance_unit', 'km' );
						echo esc_html( $unit === 'mi' ? __( 'Mile Based Pricing', 'executive-vip-transfer-service' ) : __( 'Km Based Pricing', 'executive-vip-transfer-service' ) );
						?>
					</th>
					<td>
						<input type="number" name="execvitr_km_price" value="<?php echo esc_attr( get_option( 'execvitr_km_price' ) ); ?>" step="0.01" />
						<p class="description"><?php echo esc_html( $unit === 'mi' ? __( 'When Miles is selected, this value is treated as price per mile.', 'executive-vip-transfer-service' ) : __( 'Price per kilometer.', 'executive-vip-transfer-service' ) ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php echo esc_html__( 'Minimum Service Pricing', 'executive-vip-transfer-service' ); ?></th>
					<td><input type="number" name="execvitr_minimum_price" value="<?php echo esc_attr( get_option( 'execvitr_minimum_price' ) ); ?>" step="0.01" /></td>
				</tr>
				<tr>
					<th>
						<?php
						$unit = get_option( 'execvitr_distance_unit', 'km' );
						echo esc_html( $unit === 'mi' ? __( 'Maximum Distance (mi)', 'executive-vip-transfer-service' ) : __( 'Maximum Distance (km)', 'executive-vip-transfer-service' ) );
						?>
					</th>
					<td>
						<input type="number" name="execvitr_max_distance" value="<?php echo esc_attr( get_option( 'execvitr_max_distance' ) ); ?>" />
						<p class="description"><?php echo esc_html__( 'Bookings beyond this distance are blocked in the form.', 'executive-vip-transfer-service' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php echo esc_html__( 'Minimum Advance Booking (hours)', 'executive-vip-transfer-service' ); ?></th>
					<td>
						<input type="number" name="execvitr_min_booking_hours" min="0" step="1" value="<?php echo esc_attr( get_option( 'execvitr_min_booking_hours', 0 ) ); ?>" />
						<p class="description"><?php echo esc_html__( 'Customers will only be able to select a pickup date/time at least X hours from now. Set 0 to disable.', 'executive-vip-transfer-service' ); ?></p>
					</td>
				</tr>

				<tr>
					<th><?php echo esc_html__( 'Cash Payment', 'executive-vip-transfer-service' ); ?></th>
					<td>
						<?php $cash = get_option( 'execvitr_enable_cash', 'yes' ); ?>
						<select name="execvitr_enable_cash" class="vts-wide-input">
							<option value="yes" <?php selected( $cash, 'yes' ); ?>><?php echo esc_html__( 'Enabled', 'executive-vip-transfer-service' ); ?></option>
							<option value="no" <?php selected( $cash, 'no' ); ?>><?php echo esc_html__( 'Disabled', 'executive-vip-transfer-service' ); ?></option>
						</select>
						<p class="description"><?php echo esc_html__( 'Show or hide the Cash option in the booking form.', 'executive-vip-transfer-service' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php echo esc_html__( 'Card Payment', 'executive-vip-transfer-service' ); ?></th>
					<td>
						<?php $card = get_option( 'execvitr_enable_card', 'yes' ); ?>
						<select name="execvitr_enable_card" class="vts-wide-input">
							<option value="yes" <?php selected( $card, 'yes' ); ?>><?php echo esc_html__( 'Enabled', 'executive-vip-transfer-service' ); ?></option>
							<option value="no" <?php selected( $card, 'no' ); ?>><?php echo esc_html__( 'Disabled', 'executive-vip-transfer-service' ); ?></option>
						</select>
						<p class="description"><?php echo esc_html__( 'Show or hide the Card option in the booking form.', 'executive-vip-transfer-service' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php echo esc_html__( 'Contact Number', 'executive-vip-transfer-service' ); ?></th>
					<td><input type="text" name="execvitr_whatsapp_number" value="<?php echo esc_attr( get_option( 'execvitr_whatsapp_number' ) ); ?>" placeholder="<?php echo esc_attr__( '90XXXXXXXXXX', 'executive-vip-transfer-service' ); ?>" /></td>
				</tr>
				<tr class="execvitr-row-notify-email">
  <th><?php echo esc_html__( 'Order Notification Email', 'executive-vip-transfer-service' ); ?></th>
  <td>
    <input type="email" class="vts-wide-input execvitr-email-input" name="execvitr_notify_admin"
      value="<?php echo esc_attr( get_option( 'execvitr_notify_admin' ) ); ?>"
      placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>" />
    <p class="description"><?php echo esc_html__( 'If set, reservation emails will be sent to this address instead of the site admin email.', 'executive-vip-transfer-service' ); ?></p>
  </td>
</tr>

			</table>

			<?php submit_button( __( 'Submit', 'executive-vip-transfer-service' ) ); ?>
		</form>
	</div>
	<?php
}




/**
 * -------------------------------------------------------------------------
 * Orders page (Admin)
 * -------------------------------------------------------------------------
 */
function execvitr_orders_page_html() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$currency_code = get_option( 'execvitr_currency', 'USD' );
	$symbols       = [
		'USD' => '$',
		'EUR' => '€',
		'GBP' => '£',
		'TRY' => '₺',
		'CAD' => 'C$',
		'AUD' => 'A$',
		'CHF' => 'CHF',
		'JPY' => '¥',
		'CNY' => '¥',
		'AED' => 'د.إ',
		'INR' => '₹',
		'BRL' => 'R$',
		'ZAR' => 'R',
		'KRW' => '₩',
		'MXN' => '$',
	];
	$currency_symbol = $symbols[ $currency_code ] ?? '$';

	// Helper: return first non-empty meta
	$get_meta_any = static function( WC_Order $order, array $keys, $default = '' ) {
		foreach ( $keys as $k ) {
			$v = $order->get_meta( $k );
			if ( $v !== '' && $v !== null ) {
				return $v;
			}
		}
		return $default;
	};

	// Helper: booking json (order meta or item meta)
	$get_booking = static function( WC_Order $order ): array {
		$booking = [];

		$booking_json = (string) $order->get_meta( '_execvitr_booking_json' );
		if ( $booking_json ) {
			$decoded = json_decode( $booking_json, true );
			if ( is_array( $decoded ) ) {
				return $decoded;
			}
		}

		// Fallback: item meta _execvitr_booking_json
		foreach ( $order->get_items() as $item ) {
			if ( ! is_a( $item, 'WC_Order_Item_Product' ) ) continue;
			$ij = (string) $item->get_meta( '_execvitr_booking_json', true );
			if ( $ij ) {
				$decoded = json_decode( $ij, true );
				if ( is_array( $decoded ) ) {
					return $decoded;
				}
			}
		}

		return $booking;
	};

	// Helper: parse pickup datetime (ISO or "Y-m-d H:i" etc) -> pretty
	$pretty_datetime = static function( string $raw ): string {
		$raw = trim( $raw );
		if ( $raw === '' ) return '';

		$tz = function_exists( 'wp_timezone' )
			? wp_timezone()
			: new DateTimeZone( get_option( 'timezone_string' ) ?: 'UTC' );

		try {
			// If "Y-m-d H:i" add seconds for safe parse in local tz
			if ( preg_match( '/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}$/', $raw ) ) {
				$dt = new DateTimeImmutable( $raw . ':00', $tz );
			} else {
				// ISO or other valid formats
				$dt = new DateTimeImmutable( $raw );
				$dt = $dt->setTimezone( $tz );
			}

			return wp_date(
				get_option( 'date_format' ) . ' ' . get_option( 'time_format' ),
				$dt->getTimestamp(),
				$tz
			);
		} catch ( Exception $e ) {
			return $raw;
		}
	};

	// Optional: show only booking product orders
	$product_id = (int) get_option( 'execvitr_product_id', 0 );

	// UI: sorting
	$sort_by = isset( $_GET['sort_by'] ) ? sanitize_key( (string) $_GET['sort_by'] ) : 'order_date';
	$sort_dir = isset( $_GET['sort_dir'] ) ? strtoupper( sanitize_key( (string) $_GET['sort_dir'] ) ) : 'DESC';
	if ( ! in_array( $sort_dir, [ 'ASC', 'DESC' ], true ) ) {
		$sort_dir = 'DESC';
	}
	if ( ! in_array( $sort_by, [ 'order_date', 'pickup_date' ], true ) ) {
		$sort_by = 'order_date';
	}

	$args = [
		'limit'   => 50,
		'orderby' => 'date',
		'order'   => $sort_dir,
	];

	// If product configured, filter to orders containing it
	if ( $product_id > 0 ) {
		$args['product_id'] = $product_id;
	}

	$orders = function_exists( 'wc_get_orders' ) ? wc_get_orders( $args ) : [];

	// If sorting by pickup date, do it in PHP (pickup may be stored in booking json/meta)
	if ( $sort_by === 'pickup_date' && ! empty( $orders ) ) {
		$get_pickup_ts = static function( WC_Order $order ) use ( $get_booking, $get_meta_any ): int {
			$booking = $get_booking( $order );
			$pickup_raw = '';
			if ( ! empty( $booking['pickup_datetime'] ) ) {
				$pickup_raw = (string) $booking['pickup_datetime'];
			}
			if ( $pickup_raw === '' ) {
				$pickup_raw = (string) $get_meta_any( $order, [ '_cc_pickup_datetime', '_cc_arrival_time', '_cc_arrival_time_iso', '_execvitr_date' ], '' );
			}
			$pickup_raw = trim( $pickup_raw );
			if ( $pickup_raw === '' ) {
				$dt = $order->get_date_created();
				return $dt ? (int) $dt->getTimestamp() : 0;
			}
			try {
				$tz = function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( get_option( 'timezone_string' ) ?: 'UTC' );
				if ( preg_match( '/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}$/', $pickup_raw ) ) {
					$dt = new DateTimeImmutable( $pickup_raw . ':00', $tz );
				} else {
					$dt = new DateTimeImmutable( $pickup_raw );
					$dt = $dt->setTimezone( $tz );
				}
				return (int) $dt->getTimestamp();
			} catch ( Exception $e ) {
				$dt = $order->get_date_created();
				return $dt ? (int) $dt->getTimestamp() : 0;
			}
		};

		usort( $orders, static function( $a, $b ) use ( $get_pickup_ts, $sort_dir ) {
			$ta = $get_pickup_ts( $a );
			$tb = $get_pickup_ts( $b );
			if ( $ta === $tb ) return 0;
			if ( $sort_dir === 'ASC' ) {
				return ( $ta < $tb ) ? -1 : 1;
			}
			return ( $ta > $tb ) ? -1 : 1;
		} );
	}

	echo '<div class="wrap execvitr-admin execvitr-admin--orders"><h1 class="execvitr-title">' . esc_html__( 'VIP Transfer Orders', 'executive-vip-transfer-service' ) . '</h1>';

	// Notices
	if ( isset( $_GET['deleted'] ) ) {
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Reservation deleted.', 'executive-vip-transfer-service' ) . '</p></div>';
	}
	if ( isset( $_GET['error'] ) && sanitize_key( (string) $_GET['error'] ) === 'nonce' ) {
		echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Security check failed. Please try again.', 'executive-vip-transfer-service' ) . '</p></div>';
	}
	if ( isset( $_GET['error'] ) && sanitize_key( (string) $_GET['error'] ) === 'trash_failed' ) {
		echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Could not delete the reservation. Please check your user permissions and try again.', 'executive-vip-transfer-service' ) . '</p></div>';
	}

	// Controls: sort
	$base_url = admin_url( 'admin.php?page=execvitr-orders' );
	$keep = [ 'page' => 'execvitr-orders' ];
	$sort_action = add_query_arg( $keep, admin_url( 'admin.php' ) );
	?>
	<div class="execvitr-orders-toolbar" style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:10px 0 14px;">
		<form method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
			<input type="hidden" name="page" value="execvitr-orders" />
			<label>
				<span class="screen-reader-text"><?php esc_html_e( 'Sort by', 'executive-vip-transfer-service' ); ?></span>
				<select name="sort_by">
					<option value="order_date" <?php selected( $sort_by, 'order_date' ); ?>><?php esc_html_e( 'Order date', 'executive-vip-transfer-service' ); ?></option>
					<option value="pickup_date" <?php selected( $sort_by, 'pickup_date' ); ?>><?php esc_html_e( 'Pickup date', 'executive-vip-transfer-service' ); ?></option>
				</select>
			</label>
			<label>
				<span class="screen-reader-text"><?php esc_html_e( 'Direction', 'executive-vip-transfer-service' ); ?></span>
				<select name="sort_dir">
					<option value="DESC" <?php selected( $sort_dir, 'DESC' ); ?>><?php esc_html_e( 'Newest first', 'executive-vip-transfer-service' ); ?></option>
					<option value="ASC" <?php selected( $sort_dir, 'ASC' ); ?>><?php esc_html_e( 'Oldest first', 'executive-vip-transfer-service' ); ?></option>
				</select>
			</label>
			<button type="submit" class="button"><?php esc_html_e( 'Apply', 'executive-vip-transfer-service' ); ?></button>
		</form>

	</div>
	<?php

	if ( empty( $orders ) ) {
		echo '<p>' . esc_html__( 'No orders yet.', 'executive-vip-transfer-service' ) . '</p></div>';
		return;
	}

	echo '<table class="widefat fixed striped vts-table vts-table--orders execvitr-table">';
	echo '<thead><tr>
			<th>' . esc_html__( 'ID', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Name', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'From → To', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Passengers', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Luggage', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Pickup Date & Time', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Car', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Total', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Status', 'executive-vip-transfer-service' ) . '</th>
			<th>' . esc_html__( 'Actions', 'executive-vip-transfer-service' ) . '</th>
		</tr></thead><tbody>';

	foreach ( $orders as $order ) {
		if ( ! $order || ! is_a( $order, 'WC_Order' ) ) continue;

		$id      = $order->get_id();
		$status  = wc_get_order_status_name( $order->get_status() );

		$booking = $get_booking( $order );

		// --- Route (booking_json > new meta > old meta) ---
		$from_raw = '';
		$to_raw   = '';

		if ( ! empty( $booking['pickup_location'] ) )  $from_raw = (string) $booking['pickup_location'];
		if ( ! empty( $booking['dropoff_location'] ) ) $to_raw   = (string) $booking['dropoff_location'];

		if ( $from_raw === '' ) $from_raw = (string) $get_meta_any( $order, [ '_execvitr_pickup', '_cc_address_from' ], '' );
		if ( $to_raw === '' )   $to_raw   = (string) $get_meta_any( $order, [ '_execvitr_drop', '_cc_address_to' ], '' );

		// --- Name / Email / Phone (billing first) ---
		$billing_name = trim( (string) $order->get_billing_first_name() . ' ' . (string) $order->get_billing_last_name() );
		$display_name = $billing_name;

		if ( $display_name === '' ) {
			$nm = (string) $get_meta_any( $order, [ '_cc_sender_name' ], '' );
			$sn = (string) $get_meta_any( $order, [ '_cc_sender_surname' ], '' );
			$display_name = trim( $nm . ' ' . $sn );
		}

		if ( $display_name === '' && ! empty( $booking['sender_name'] ) ) {
			$display_name = trim(
				(string) ( $booking['sender_name'] ?? '' ) . ' ' . (string) ( $booking['sender_surname'] ?? '' )
			);
		}

		$email = (string) $order->get_billing_email();
		if ( $email === '' ) {
			$email = (string) $get_meta_any( $order, [ '_cc_user_email' ], '' );
		}
		if ( $email === '' && ! empty( $booking['user_email'] ) ) {
			$email = (string) $booking['user_email'];
		}

		$phone = (string) $order->get_billing_phone();
		if ( $phone === '' ) {
			$phone = (string) $get_meta_any( $order, [ '_cc_pickup_phone' ], '' );
		}
		if ( $phone === '' && ! empty( $booking['phone'] ) ) {
			$phone = (string) $booking['phone'];
		}

		// --- Pickup datetime (booking_json > _cc_pickup_datetime > arrival ISO) ---
		$pickup_raw = '';
		if ( ! empty( $booking['pickup_datetime'] ) ) {
			$pickup_raw = (string) $booking['pickup_datetime'];
		}
		if ( $pickup_raw === '' ) {
			$pickup_raw = (string) $get_meta_any( $order, [ '_cc_pickup_datetime', '_cc_arrival_time', '_cc_arrival_time_iso', '_execvitr_date' ], '' );
		}
		$pretty_pickup = $pretty_datetime( $pickup_raw );

		// Return (optional)
		$return_raw = '';
		$is_return  = false;
		if ( isset( $booking['is_return'] ) ) {
			$is_return = (bool) $booking['is_return'];
		}
		$meta_is_return = (string) $order->get_meta( '_execvitr_is_return' );
		if ( $meta_is_return === '1' ) {
			$is_return = true;
		}
		if ( ! empty( $booking['return_datetime'] ) ) {
			$return_raw = (string) $booking['return_datetime'];
		}
		if ( $return_raw === '' ) {
			$return_raw = (string) $order->get_meta( '_execvitr_return_datetime' );
		}
		$pretty_return = $is_return && $return_raw !== '' ? $pretty_datetime( $return_raw ) : '';


		// --- Vehicle (booking_json > explicit meta > index->settings) ---
		$car_brand = '';
		if ( ! empty( $booking['car_name'] ) ) {
			$car_brand = (string) $booking['car_name'];
		}
		if ( $car_brand === '' ) {
			$car_brand = (string) ( $order->get_meta('_execvitr_vehicle') ?: $order->get_meta('_cc_car_brand') ?: $order->get_meta('car_brand') );
		}
		if ( $car_brand === '' ) {
			// IMPORTANT: WC_Order::get_meta() does NOT support a "default" parameter.
			// If meta is missing, it returns '' and casting (int)'' => 0, causing
			// all orders to show the first vehicle ("always Maybach" bug).
			$car_index = -1;
			if ( isset( $booking['car_index'] ) ) {
				$car_index = (int) $booking['car_index'];
			} else {
				$ci = $order->get_meta( '_cc_car_index' );
				$car_index = ( $ci === '' || $ci === null ) ? -1 : (int) $ci;
			}
			if ( $car_index >= 0 ) {
				$cars = get_option( 'execvitr_cars', [] );
				if ( is_array( $cars ) && isset( $cars[ $car_index ]['brand'] ) ) {
					$car_brand = (string) $cars[ $car_index ]['brand'];
				}
			}
		}

		// --- Passengers / luggage (booking_json > meta) ---
		$passengers = 0;
		$luggage    = 0;

		if ( isset( $booking['passengers'] ) ) $passengers = (int) $booking['passengers'];
		if ( isset( $booking['luggage'] ) )    $luggage    = (int) $booking['luggage'];

		if ( $passengers <= 0 ) $passengers = (int) $get_meta_any( $order, [ '_cc_passenger_count' ], 0 );
		if ( $luggage < 0 )     $luggage    = (int) $get_meta_any( $order, [ '_cc_luggage_count' ], 0 );

		// --- Total (order total first, then meta) ---
		$total_value = (float) $order->get_total();
		if ( $total_value <= 0 ) {
			$total_fee_meta = (float) $get_meta_any( $order, [ '_execvitr_total_fee', '_cc_total_price', '_cc_total_fee' ], 0 );
			if ( $total_fee_meta > 0 ) $total_value = $total_fee_meta;
		}
		$total = $currency_symbol . number_format_i18n( $total_value, 2 );

		// --- Details fields (use what email/summary uses) ---
		$pickup_details = '';
		if ( ! empty( $booking['notes'] ) ) $pickup_details = (string) $booking['notes'];
		if ( $pickup_details === '' ) $pickup_details = (string) $get_meta_any( $order, [ '_cc_pickup_details' ], '' );

		$payment_method = '';
		if ( ! empty( $booking['payment_method'] ) ) $payment_method = (string) $booking['payment_method'];
		if ( $payment_method === '' ) $payment_method = (string) $get_meta_any( $order, [ '_cc_payment_method' ], '' );

		$distance_txt = (string) $get_meta_any( $order, [ '_cc_distance_text' ], '' );
		$duration_txt = (string) $get_meta_any( $order, [ '_cc_duration' ], '' );

		// Booking may store distance/duration too
		if ( $distance_txt === '' && ! empty( $booking['distance_text'] ) ) $distance_txt = (string) $booking['distance_text'];
		if ( $duration_txt === '' && ! empty( $booking['duration'] ) )      $duration_txt = (string) $booking['duration'];

		$from = esc_html( $from_raw );
		$to   = esc_html( $to_raw );

		echo '<tr class="order-summary" data-target="details-' . esc_attr( $id ) . '">';
		echo '<td data-label="' . esc_attr__( 'ID', 'executive-vip-transfer-service' ) . '">#' . esc_html( $id ) . '</td>';
		echo '<td data-label="' . esc_attr__( 'Name', 'executive-vip-transfer-service' ) . '">' . esc_html( $display_name ) . '</td>';
		echo '<td data-label="' . esc_attr__( 'From → To', 'executive-vip-transfer-service' ) . '">' . $from . ' &rarr; ' . $to . '</td>';
		echo '<td data-label="' . esc_attr__( 'Passengers', 'executive-vip-transfer-service' ) . '">' . esc_html( $passengers ) . '</td>';
		echo '<td data-label="' . esc_attr__( 'Luggage', 'executive-vip-transfer-service' ) . '">' . esc_html( $luggage ) . '</td>';
		echo '<td data-label="' . esc_attr__( 'Pickup Date & Time', 'executive-vip-transfer-service' ) . '">' . esc_html( $pretty_pickup ) . '</td>';
		echo '<td data-label="' . esc_attr__( 'Car', 'executive-vip-transfer-service' ) . '">' . esc_html( $car_brand ) . '</td>';
		echo '<td data-label="' . esc_attr__( 'Total', 'executive-vip-transfer-service' ) . '">' . esc_html( $total ) . '</td>';
		echo '<td data-label="' . esc_attr__( 'Status', 'executive-vip-transfer-service' ) . '">' . esc_html( $status ) . '</td>';
		$edit_url = admin_url( 'admin.php?page=execvitr-order-edit&order_id=' . $id );
		$delete_nonce = wp_create_nonce( 'execvitr_delete_order_' . $id );
		echo '<td class="vts-td-right">';
		echo '<div class="execvitr-actions">'
			. '<button type="button" class="toggle-details button" aria-expanded="false" aria-controls="details-' . esc_attr( $id ) . '">+</button>'
			. '<div class="execvitr-actions-stack">'
				. '<a class="button" href="' . esc_url( $edit_url ) . '">' . esc_html__( 'Edit', 'executive-vip-transfer-service' ) . '</a>';
		// Use POST for delete to avoid host/security rules that block admin-post GET actions.
		echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '" class="execvitr-delete-form">'
			. '<input type="hidden" name="action" value="execvitr_delete_order" />'
			. '<input type="hidden" name="order_id" value="' . esc_attr( $id ) . '" />'
			. '<input type="hidden" name="_wpnonce" value="' . esc_attr( $delete_nonce ) . '" />'
			. '<button type="submit" class="button button-link-delete" onclick="return confirm(\'' . esc_js( __( 'Move this reservation to trash?', 'executive-vip-transfer-service' ) ) . '\');">' . esc_html__( 'Delete', 'executive-vip-transfer-service' ) . '</button>'
			. '</form>'
			. '</div>'
			. '</div>';
		echo '</td>';
		echo '</tr>';

		// Details row
		echo '<tr id="details-' . esc_attr( $id ) . '" class="order-details vts-order-details">';
		echo '<td colspan="10">';
		echo '<div class="execvitr-order-details-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px;padding:10px 5px;border-top:1px solid #ddd;background:#fafafa;">';

		$fields = [
			__( 'From', 'executive-vip-transfer-service' )               => $from_raw,
			__( 'To', 'executive-vip-transfer-service' )                 => $to_raw,
			__( 'Name', 'executive-vip-transfer-service' )               => (string) $order->get_billing_first_name(),
			__( 'Surname', 'executive-vip-transfer-service' )            => (string) $order->get_billing_last_name(),
			__( 'Email', 'executive-vip-transfer-service' )              => $email,
			__( 'Phone', 'executive-vip-transfer-service' )              => $phone,
			__( 'Pickup Date & Time', 'executive-vip-transfer-service' ) => $pretty_pickup,
			__( 'Return Date & Time', 'executive-vip-transfer-service' ) => $pretty_return,
			__( 'Vehicle', 'executive-vip-transfer-service' )            => $car_brand,
			__( 'Passengers', 'executive-vip-transfer-service' )         => (string) $passengers,
			__( 'Bags', 'executive-vip-transfer-service' )               => (string) $luggage,
			__( 'Distance', 'executive-vip-transfer-service' )           => $distance_txt,
			__( 'Estimated Duration', 'executive-vip-transfer-service' ) => $duration_txt,
			__( 'Payment Method', 'executive-vip-transfer-service' )     => $payment_method,
			__( 'Notes', 'executive-vip-transfer-service' )              => $pickup_details,
			__( 'Total', 'executive-vip-transfer-service' )              => $total,
		];

		foreach ( $fields as $label => $value ) {
			$value = is_scalar( $value ) ? (string) $value : '';
			if ( trim( $value ) === '' ) {
				continue;
			}
			echo '<div class="execvitr-field"><strong>' . esc_html( $label ) . ':</strong> ' . esc_html( $value ) . '</div>';
		}

		echo '</div>';
		echo '</td>';
		echo '</tr>';
	}

	echo '</tbody></table></div>';
}





/**
 * -------------------------------------------------------------------------
 * Contact page 
 * -------------------------------------------------------------------------
 */
function execvitr_contact_page_html() {
	echo '<div class="wrap vts-narrow-wrap">';
	echo '<h1>' . esc_html__( '📨 Executive VIP Transfer Contact', 'executive-vip-transfer-service' ) . '</h1>';
	echo '<p>' . esc_html__( 'If you need help or have suggestions, please visit our contact page below:', 'executive-vip-transfer-service' ) . '</p>';
	echo '<p><a href="https://gksoft.dev/contact" class="button button-primary" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Open Contact Page', 'executive-vip-transfer-service' ) . '</a></p>';
	echo '</div>';
}

/**
 * -------------------------------------------------------------------------
 * Cars option sanitize 
 * -------------------------------------------------------------------------
 */
function execvitr_sanitize_cars_option( $input ) {
	if ( ! is_array( $input ) ) {
		return [];
	}

	$clean = [];

	foreach ( $input as $row ) {
		if ( ! is_array( $row ) ) {
			continue;
		}

		$brand     = isset( $row['brand'] ) ? sanitize_text_field( wp_unslash( $row['brand'] ) ) : '';
		$image_id  = isset( $row['image_id'] ) ? (int) $row['image_id'] : 0;
		$passenger = isset( $row['passenger'] ) ? max( 1, (int) $row['passenger'] ) : 1;
		$luggage   = isset( $row['luggage'] ) ? max( 0, (int) $row['luggage'] ) : 0;
		$km_price  = isset( $row['km_price'] ) ? floatval( $row['km_price'] ) : 0;
		$desc      = isset( $row['description'] ) ? sanitize_textarea_field( wp_unslash( $row['description'] ) ) : '';

		// Skip fully empty rows.
		if ( '' === $brand && '' === $desc && 0 === $image_id && 1 === $passenger && 0 === $luggage && 0.0 === $km_price ) {
			continue;
		}

		$clean[] = [
			'brand'       => $brand,
			'image_id'    => $image_id,
			'passenger'   => $passenger,
			'luggage'     => $luggage,
			'km_price'    => $km_price,
			'description' => $desc,
		];
	}

	return $clean;
}

/**
 * -------------------------------------------------------------------------
 * Cars page 
 * -------------------------------------------------------------------------
 */
function execvitr_cars_page_html() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$cars = get_option( 'execvitr_cars' );
	$unit = get_option( 'execvitr_distance_unit', 'km' );
	$unit = ( $unit === 'mi' ) ? 'mi' : 'km';
	$price_label = sprintf( esc_html__( 'Distance Price (%s)', 'executive-vip-transfer-service' ), $unit );
	?>
	<div class="wrap execvitr-admin execvitr-admin--cars">
		<h1><?php esc_html_e( 'Cars', 'executive-vip-transfer-service' ); ?></h1>
		<p class="description"><?php esc_html_e( 'Add multiple company vehicles. Fields: Brand, Image, Passenger Capacity, Luggage Capacity.', 'executive-vip-transfer-service' ); ?></p>

		<form method="post" action="options.php">
			<?php settings_fields( 'execvitr_cars_group' ); ?>

			<table class="widefat fixed striped" id="vts-cars-table">
				<thead>
				<tr>
					<th><?php esc_html_e( 'Brand', 'executive-vip-transfer-service' ); ?></th>
					<th><?php esc_html_e( 'Image', 'executive-vip-transfer-service' ); ?></th>
					<th><?php esc_html_e( 'Passengers', 'executive-vip-transfer-service' ); ?></th>
					<th><?php esc_html_e( 'Luggage', 'executive-vip-transfer-service' ); ?></th>
					<th><?php echo esc_html( $price_label ); ?></th>
					<th><?php esc_html_e( 'Description', 'executive-vip-transfer-service' ); ?></th>
					<th><?php esc_html_e( 'Actions', 'executive-vip-transfer-service' ); ?></th>
				</tr>
				</thead>
				<tbody>
				<?php if ( ! empty( $cars ) ) : ?>
					<?php foreach ( $cars as $i => $car ) :
						$brand     = isset( $car['brand'] ) ? $car['brand'] : '';
						$image_id  = isset( $car['image_id'] ) ? (int) $car['image_id'] : 0;
						$passenger = isset( $car['passenger'] ) ? (int) $car['passenger'] : 1;
						$luggage   = isset( $car['luggage'] ) ? (int) $car['luggage'] : 0;
						$desc      = isset( $car['description'] ) ? (string) $car['description'] : '';
						$img_src   = $image_id ? wp_get_attachment_image_src( $image_id, 'thumbnail' ) : false;
						$km_price  = isset( $car['km_price'] ) ? (float) $car['km_price'] : 0;
						?>
						<tr class="vts-car-row">
							<td data-label="<?php echo esc_attr__( 'Brand', 'executive-vip-transfer-service' ); ?>">
								<input type="text" name="execvitr_cars[<?php echo (int) $i; ?>][brand]" value="<?php echo esc_attr( $brand ); ?>" class="regular-text" placeholder="<?php echo esc_attr__( 'Mercedes-Benz', 'executive-vip-transfer-service' ); ?>" />
							</td>
							<td data-label="<?php echo esc_attr__( 'Image', 'executive-vip-transfer-service' ); ?>">
								<div class="vts-image-field">
									<input type="hidden" class="vts-image-id" name="execvitr_cars[<?php echo (int) $i; ?>][image_id]" value="<?php echo (int) $image_id; ?>" />
									<div class="vts-image-preview">
										<?php if ( $img_src ) : ?>
											<img src="<?php echo esc_url( $img_src[0] ); ?>" alt="" class="vts-thumb" />
										<?php else : ?>
											<span class="vts-muted"><?php esc_html_e( 'No image', 'executive-vip-transfer-service' ); ?></span>
										<?php endif; ?>
									</div>
									<button type="button" class="button vts-upload-image"><?php esc_html_e( 'Choose Image', 'executive-vip-transfer-service' ); ?></button>
									<button type="button" class="button vts-remove-image"><?php esc_html_e( 'Remove', 'executive-vip-transfer-service' ); ?></button>
								</div>
							</td>
							<td data-label="<?php echo esc_attr__( 'Passengers', 'executive-vip-transfer-service' ); ?>">
								<input type="number" min="1" step="1" name="execvitr_cars[<?php echo (int) $i; ?>][passenger]" value="<?php echo (int) $passenger; ?>" />
							</td>
							<td data-label="<?php echo esc_attr__( 'Luggage', 'executive-vip-transfer-service' ); ?>">
								<input type="number" min="0" step="1" name="execvitr_cars[<?php echo (int) $i; ?>][luggage]" value="<?php echo (int) $luggage; ?>" />
							</td>
							<td data-label="<?php echo esc_attr( $price_label ); ?>">
								<input type="number" min="0" step="0.01" name="execvitr_cars[<?php echo (int) $i; ?>][km_price]" value="<?php echo esc_attr( $km_price ); ?>" />
							</td>
							<td data-label="<?php echo esc_attr__( 'Description', 'executive-vip-transfer-service' ); ?>">
								<textarea rows="2" style="width:100%;" placeholder="(internet/water/Wi-Fi/TV, etc.)" name="execvitr_cars[<?php echo (int) $i; ?>][description]"><?php echo esc_textarea( $desc ); ?></textarea>
							</td>
							<td data-label="<?php echo esc_attr__( 'Actions', 'executive-vip-transfer-service' ); ?>">
								<button type="button" class="button button-link-delete vts-remove-row">&times; <?php esc_html_e( 'Delete', 'executive-vip-transfer-service' ); ?></button>
							</td>
						</tr>
					<?php endforeach; ?>
				<?php endif; ?>
				</tbody>
				<tfoot>
				<tr>
					<td colspan="5">
						<button type="button" class="button button-primary" id="vts-add-row">+ <?php esc_html_e( 'Add Car', 'executive-vip-transfer-service' ); ?></button>
					</td>
				</tr>
				</tfoot>
			</table>

			<?php submit_button( __( 'Save Cars', 'executive-vip-transfer-service' ) ); ?>
		</form>
	</div>

	<!-- HTML template only (no JS logic here) -->
	<script type="text/html" id="vts-car-row-template">
		<tr class="vts-car-row">
			<td>
				<input type="text" name="execvitr_cars[{{i}}][brand]" value="" class="regular-text" placeholder="<?php echo esc_attr__( 'Mercedes-Benz', 'executive-vip-transfer-service' ); ?>" />
			</td>
			<td>
				<div class="vts-image-field">
					<input type="hidden" class="vts-image-id" name="execvitr_cars[{{i}}][image_id]" value="0" />
					<div class="vts-image-preview">
						<span class="vts-muted"><?php echo esc_js( __( 'No image', 'executive-vip-transfer-service' ) ); ?></span>
					</div>
					<button type="button" class="button vts-upload-image"><?php echo esc_js( __( 'Choose Image', 'executive-vip-transfer-service' ) ); ?></button>
					<button type="button" class="button vts-remove-image"><?php echo esc_js( __( 'Remove', 'executive-vip-transfer-service' ) ); ?></button>
				</div>
			</td>
			<td><input type="number" min="1" step="1" name="execvitr_cars[{{i}}][passenger]" value="1" /></td>
			<td><input type="number" min="0" step="1" name="execvitr_cars[{{i}}][luggage]" value="0" /></td>
			<td><input type="number" min="0" step="0.01" name="execvitr_cars[{{i}}][km_price]" value="0" /></td>
			<td><textarea rows="2" style="width:100%;" name="execvitr_cars[{{i}}][description]"></textarea></td>
			<td><button type="button" class="button button-link-delete vts-remove-row">&times; <?php echo esc_js( __( 'Delete', 'executive-vip-transfer-service' ) ); ?></button></td>
		</tr>
	</script>
	<?php
}

/**
 * -------------------------------------------------------------------------
 * Custom Reservation Edit Page (Admin)
 * URL: admin.php?page=execvitr-order-edit&order_id=123
 * -------------------------------------------------------------------------
 */
function execvitr_order_edit_page_html() {
	if ( ! current_user_can( 'manage_options' ) ) return;

	$order_id = isset( $_GET['order_id'] ) ? absint( wp_unslash( $_GET['order_id'] ) ) : 0;
	if ( $order_id <= 0 ) {
		echo '<div class="wrap"><h1>' . esc_html__( 'Edit Reservation', 'executive-vip-transfer-service' ) . '</h1>';
		echo '<div class="notice notice-error"><p>' . esc_html__( 'Missing order id.', 'executive-vip-transfer-service' ) . '</p></div></div>';
		return;
	}

	$order = function_exists( 'wc_get_order' ) ? wc_get_order( $order_id ) : null;
	if ( ! $order || ! is_a( $order, 'WC_Order' ) ) {
		echo '<div class="wrap"><h1>' . esc_html__( 'Edit Reservation', 'executive-vip-transfer-service' ) . '</h1>';
		echo '<div class="notice notice-error"><p>' . esc_html__( 'Order not found.', 'executive-vip-transfer-service' ) . '</p></div></div>';
		return;
	}

	$booking = [];
	$booking_json = (string) $order->get_meta( '_execvitr_booking_json' );
	if ( $booking_json ) {
		$decoded = json_decode( $booking_json, true );
		if ( is_array( $decoded ) ) $booking = $decoded;
	}

	$pickup_location  = $booking['pickup_location']  ?? (string) $order->get_meta( '_cc_pickup_location' );
	$dropoff_location = $booking['dropoff_location'] ?? (string) $order->get_meta( '_cc_dropoff_location' );
	$pickup_datetime  = $booking['pickup_datetime']  ?? (string) $order->get_meta( '_cc_pickup_datetime' );

	$is_return = ! empty( $booking['is_return'] ) || (string) $order->get_meta( '_execvitr_is_return' ) === '1';
	$return_datetime = $booking['return_datetime'] ?? (string) $order->get_meta( '_execvitr_return_datetime' );

	$passengers = isset( $booking['passengers'] ) ? (int) $booking['passengers'] : (int) $order->get_meta( '_cc_passengers' );
	$luggage    = isset( $booking['luggage'] ) ? (int) $booking['luggage'] : (int) $order->get_meta( '_cc_luggage' );

	$car_name = $booking['car_name'] ?? (string) $order->get_meta( '_cc_car_brand' );
	$payment_method = $booking['payment_method'] ?? (string) $order->get_meta( '_cc_payment_method' );

	$phone = $booking['phone'] ?? (string) $order->get_billing_phone();
	$email = $booking['user_email'] ?? (string) $order->get_billing_email();
	$notes = $booking['notes'] ?? (string) $order->get_meta( '_cc_pickup_details' );

	$distance_km   = isset( $booking['distance_km'] ) ? (float) $booking['distance_km'] : (float) $order->get_meta( '_cc_distance_km' );
	$distance_text = $booking['distance_text'] ?? (string) $order->get_meta( '_cc_distance' );
	$duration      = $booking['duration'] ?? (string) $order->get_meta( '_cc_duration' );

	$base_fee  = isset( $booking['base_fee'] ) ? (float) $booking['base_fee'] : (float) $order->get_meta( '_cc_base_fee' );
	$total_fee = isset( $booking['total_fee'] ) ? (float) $booking['total_fee'] : (float) $order->get_meta( '_cc_total_fee' );

	// Split datetimes for inputs
	$pickup_date = '';
	$pickup_time = '';
	if ( is_string( $pickup_datetime ) && preg_match( '/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})/', $pickup_datetime, $mm ) ) {
		$pickup_date = $mm[1];
		$pickup_time = $mm[2];
	}

	$return_date = '';
	$return_time = '';
	if ( is_string( $return_datetime ) && preg_match( '/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})/', $return_datetime, $mm2 ) ) {
		$return_date = $mm2[1];
		$return_time = $mm2[2];
	}

	echo '<div class="wrap execvitr-admin execvitr-admin--order-edit">';
	echo '<h1>' . esc_html__( 'Edit Reservation', 'executive-vip-transfer-service' ) . ' #' . esc_html( $order_id ) . '</h1>';

	if ( isset( $_GET['updated'] ) ) {
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Reservation updated.', 'executive-vip-transfer-service' ) . '</p></div>';
	}
	if ( isset( $_GET['error'] ) && sanitize_key( (string) $_GET['error'] ) === 'nonce' ) {
		echo '<div class="notice notice-error is-dismissible"><p>' . esc_html__( 'Security check failed. Please try again.', 'executive-vip-transfer-service' ) . '</p></div>';
	}

	$action_url = admin_url( 'admin-post.php' );

	echo '<form method="post" action="' . esc_url( $action_url ) . '" style="max-width:980px;">';
	echo '<input type="hidden" name="action" value="execvitr_update_order">';
	echo '<input type="hidden" name="order_id" value="' . esc_attr( $order_id ) . '">';
	wp_nonce_field( 'execvitr_update_order_' . $order_id, 'execvitr_update_nonce' );

	echo '<table class="form-table"><tbody>';

	// Locations
	echo '<tr><th><label>' . esc_html__( 'Pickup location', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="text" name="pickup_location" value="' . esc_attr( $pickup_location ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Dropoff location', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="text" name="dropoff_location" value="' . esc_attr( $dropoff_location ) . '"></td></tr>';

	// Pickup datetime
	echo '<tr><th><label>' . esc_html__( 'Pickup date/time', 'executive-vip-transfer-service' ) . '</label></th><td style="display:flex;gap:10px;flex-wrap:wrap;">'
		. '<input type="date" name="pickup_date" value="' . esc_attr( $pickup_date ) . '">'
		. '<input type="time" name="pickup_time" value="' . esc_attr( $pickup_time ) . '"></td></tr>';

	// Return
	echo '<tr><th><label>' . esc_html__( 'Return booking', 'executive-vip-transfer-service' ) . '</label></th><td>'
		. '<label style="display:inline-flex;align-items:center;gap:8px;">'
		. '<input type="checkbox" name="is_return" value="1" ' . checked( $is_return, true, false ) . '>'
		. esc_html__( 'Enabled', 'executive-vip-transfer-service' )
		. '</label>'
		. '</td></tr>';

	echo '<tr><th><label>' . esc_html__( 'Return date/time', 'executive-vip-transfer-service' ) . '</label></th><td style="display:flex;gap:10px;flex-wrap:wrap;">'
		. '<input type="date" name="return_date" value="' . esc_attr( $return_date ) . '">'
		. '<input type="time" name="return_time" value="' . esc_attr( $return_time ) . '">'
		. '<p class="description" style="margin:6px 0 0 0;">' . esc_html__( 'Fill only if return booking is enabled.', 'executive-vip-transfer-service' ) . '</p>'
		. '</td></tr>';

	// Counts + vehicle
	echo '<tr><th><label>' . esc_html__( 'Passengers', 'executive-vip-transfer-service' ) . '</label></th><td><input type="number" min="1" name="passengers" value="' . esc_attr( max(1, (int) $passengers ) ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Bags', 'executive-vip-transfer-service' ) . '</label></th><td><input type="number" min="0" name="luggage" value="' . esc_attr( max(0, (int) $luggage ) ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Vehicle', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="text" name="car_name" value="' . esc_attr( $car_name ) . '"></td></tr>';

	// Payment + contact
	echo '<tr><th><label>' . esc_html__( 'Payment method', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="text" name="payment_method" value="' . esc_attr( $payment_method ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Phone', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="text" name="phone" value="' . esc_attr( $phone ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Email', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="email" name="email" value="' . esc_attr( $email ) . '"></td></tr>';

	echo '<tr><th><label>' . esc_html__( 'Notes', 'executive-vip-transfer-service' ) . '</label></th><td><textarea class="large-text" rows="3" name="notes">' . esc_textarea( $notes ) . '</textarea></td></tr>';

	// Route + pricing
	echo '<tr><th><label>' . esc_html__( 'Distance (km)', 'executive-vip-transfer-service' ) . '</label></th><td><input type="number" step="0.001" name="distance_km" value="' . esc_attr( $distance_km ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Distance text', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="text" name="distance_text" value="' . esc_attr( $distance_text ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Duration', 'executive-vip-transfer-service' ) . '</label></th><td><input class="regular-text" type="text" name="duration" value="' . esc_attr( $duration ) . '"></td></tr>';

	echo '<tr><th><label>' . esc_html__( 'Base fee', 'executive-vip-transfer-service' ) . '</label></th><td><input type="number" step="0.01" name="base_fee" value="' . esc_attr( $base_fee ) . '"></td></tr>';
	echo '<tr><th><label>' . esc_html__( 'Total fee', 'executive-vip-transfer-service' ) . '</label></th><td><input type="number" step="0.01" name="total_fee" value="' . esc_attr( $total_fee ) . '"></td></tr>';

	echo '</tbody></table>';

	submit_button( __( 'Save changes', 'executive-vip-transfer-service' ) );

	echo '</form>';

	echo '<p><a class="button" href="' . esc_url( admin_url( 'admin.php?page=execvitr-orders' ) ) . '">' . esc_html__( 'Back to Orders', 'executive-vip-transfer-service' ) . '</a></p>';

	echo '</div>';
}
