<?php
/** @var array<int,array<string,mixed>> $trips */
/** @var array<int,array<string,mixed>> $routes */
/** @var array<string,mixed>|null $edit */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$trip_date_value = '';
if ( ! empty( $edit['trip_date'] ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', (string) $edit['trip_date'] ) ) {
	$trip_date_value = (string) $edit['trip_date'];
}

$filter_month_ym = (string) ( $_GET['month'] ?? gmdate( 'Y-m' ) );
$filter_year     = (int) gmdate( 'Y' );
$filter_month    = (int) gmdate( 'n' );
if ( preg_match( '/^(\d{4})-(\d{2})$/', $filter_month_ym, $ym ) ) {
	$filter_year  = (int) $ym[1];
	$filter_month = (int) $ym[2];
}
$month_labels = Datvetau_Booking_Admin_Format::vietnamese_month_labels();

$route_labels = array();
foreach ( $routes as $r ) {
	$route_labels[ (int) $r['id'] ] = (string) $r['label'];
}

$trip_form_open = (bool) $edit;

$trips_filter_reset_url = admin_url( 'admin.php?page=datvetau-booking-trips' );
if ( $edit ) {
	$trips_filter_reset_url = add_query_arg( 'edit', (int) $edit['id'], $trips_filter_reset_url );
}
?>
<div class="wrap">
	<h1><?php esc_html_e( 'Chuyến tàu', 'datvetaucaotoc-booking' ); ?></h1>
	<?php if ( ! empty( $_GET['saved'] ) ) : ?><div class="notice notice-success"><p><?php esc_html_e( 'Đã lưu.', 'datvetaucaotoc-booking' ); ?></p></div><?php endif; ?>
	<?php if ( ! empty( $_GET['deleted'] ) ) : ?><div class="notice notice-success"><p><?php esc_html_e( 'Đã xóa chuyến.', 'datvetaucaotoc-booking' ); ?></p></div><?php endif; ?>
	<?php
	if ( isset( $_GET['bulk_deleted'] ) && '' !== (string) $_GET['bulk_deleted'] ) {
		$n = (int) $_GET['bulk_deleted'];
		if ( $n > 0 ) {
			printf(
				'<div class="notice notice-success"><p>%s</p></div>',
				esc_html(
					sprintf(
						/* translators: %d number of trips deleted */
						_n( 'Đã xóa %d chuyến.', 'Đã xóa %d chuyến.', $n, 'datvetaucaotoc-booking' ),
						$n
					)
				)
			);
		}
	}
	?>

	<details
		class="datvetau-admin-card datvetau-admin-card--trip-form"
		id="datvetau-trip-form-details"
		<?php echo $trip_form_open ? 'open' : ''; ?>
	>
		<summary class="datvetau-admin-card__title datvetau-admin-card__summary">
			<?php echo $edit ? esc_html__( 'Sửa chuyến', 'datvetaucaotoc-booking' ) : esc_html__( 'Thêm chuyến', 'datvetaucaotoc-booking' ); ?>
			<?php if ( ! $edit ) : ?>
				<span class="datvetau-admin-card__summary-hint"><?php esc_html_e( '(bấm để mở form)', 'datvetaucaotoc-booking' ); ?></span>
			<?php endif; ?>
		</summary>
		<div class="datvetau-admin-card__body">
	<form method="post">
		<?php wp_nonce_field( 'datvetau_trip_save' ); ?>
		<input type="hidden" name="datvetau_trip_save" value="1" />
		<?php if ( $edit ) : ?><input type="hidden" name="trip_id" value="<?php echo (int) $edit['id']; ?>" /><?php endif; ?>
		<table class="form-table">
			<tr>
				<th scope="row"><label for="datvetau-trip-route"><?php esc_html_e( 'Tuyến', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<select name="route_id" id="datvetau-trip-route" required>
						<?php foreach ( $routes as $r ) : ?>
							<option value="<?php echo (int) $r['id']; ?>" <?php selected( (int) ( $edit['route_id'] ?? 0 ), (int) $r['id'] ); ?>><?php echo esc_html( (string) $r['label'] ); ?></option>
						<?php endforeach; ?>
					</select>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-trip-date"><?php esc_html_e( 'Ngày', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<input
						name="trip_date"
						id="datvetau-trip-date"
						type="date"
						required
						value="<?php echo esc_attr( $trip_date_value ); ?>"
					/>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-departure-time"><?php esc_html_e( 'Giờ đi', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<input
						name="departure_time"
						id="datvetau-departure-time"
						type="time"
						required
						value="<?php echo esc_attr( substr( (string) ( $edit['departure_time'] ?? '12:00' ), 0, 5 ) ); ?>"
					/>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-arrival-time"><?php esc_html_e( 'Giờ đến', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<input
						name="arrival_time"
						id="datvetau-arrival-time"
						type="time"
						required
						value="<?php echo esc_attr( substr( (string) ( $edit['arrival_time'] ?? '14:00' ), 0, 5 ) ); ?>"
					/>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-operator"><?php esc_html_e( 'Hãng tàu', 'datvetaucaotoc-booking' ); ?></label></th>
				<td><input name="operator_name" id="datvetau-operator" class="regular-text" value="<?php echo esc_attr( (string) ( $edit['operator_name'] ?? 'Phú Quốc Express' ) ); ?>" /></td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-operator-logo"><?php esc_html_e( 'Logo hãng', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<?php
					Datvetau_Booking_Admin_UI::media_url_field(
						array(
							'id'    => 'datvetau-operator-logo',
							'name'  => 'operator_logo_url',
							'value' => (string) ( $edit['operator_logo_url'] ?? '' ),
						)
					);
					?>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-seat-class"><?php esc_html_e( 'Hạng ghế', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<select name="seat_class" id="datvetau-seat-class">
						<option value="eco" <?php selected( ( $edit['seat_class'] ?? 'eco' ), 'eco' ); ?>>Eco</option>
						<option value="vip" <?php selected( ( $edit['seat_class'] ?? '' ), 'vip' ); ?>>VIP</option>
					</select>
				</td>
			</tr>
			<?php
			$edit_adult = (int) ( $edit['price_adult'] ?? $edit['price_adult_eco_base'] ?? 315000 );
			?>
			<tr>
				<th scope="row"><label for="datvetau-adult-price"><?php esc_html_e( 'Giá vé người lớn (VND)', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<input name="price_adult" id="datvetau-adult-price" type="number" min="0" step="1000" required value="<?php echo esc_attr( (string) $edit_adult ); ?>" />
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-child-price"><?php esc_html_e( 'Giá vé trẻ em (VND)', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<input name="price_child" id="datvetau-child-price" type="number" min="0" step="1000" required value="<?php echo esc_attr( (string) ( $edit['price_child'] ?? '225000' ) ); ?>" />
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-senior-price"><?php esc_html_e( 'Giá vé cao tuổi (VND)', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<input name="price_senior" id="datvetau-senior-price" type="number" min="0" step="1000" required value="<?php echo esc_attr( (string) ( $edit['price_senior'] ?? '280000' ) ); ?>" />
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Số ghế', 'datvetaucaotoc-booking' ); ?></th>
				<td>
					<label><?php esc_html_e( 'Tối đa', 'datvetaucaotoc-booking' ); ?>
						<input name="capacity" type="number" min="0" value="<?php echo esc_attr( (string) ( $edit['capacity'] ?? '100' ) ); ?>" />
					</label>
					<label style="margin-left:1rem;"><?php esc_html_e( 'Còn trống', 'datvetaucaotoc-booking' ); ?>
						<input name="seats_remaining" type="number" min="0" value="<?php echo esc_attr( (string) ( $edit['seats_remaining'] ?? '100' ) ); ?>" />
					</label>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="datvetau-trip-status"><?php esc_html_e( 'Trạng thái chuyến', 'datvetaucaotoc-booking' ); ?></label></th>
				<td>
					<select name="status" id="datvetau-trip-status">
						<option value="active" <?php selected( ( $edit['status'] ?? 'active' ), 'active' ); ?>><?php esc_html_e( 'Đang bán', 'datvetaucaotoc-booking' ); ?></option>
						<option value="cancelled" <?php selected( ( $edit['status'] ?? '' ), 'cancelled' ); ?>><?php esc_html_e( 'Hủy chuyến', 'datvetaucaotoc-booking' ); ?></option>
					</select>
				</td>
			</tr>
		</table>
		<?php submit_button( __( 'Lưu chuyến', 'datvetaucaotoc-booking' ) ); ?>
	</form>
		</div>
	</details>

	<section class="datvetau-admin-card datvetau-admin-card--trip-list">
		<h2 class="datvetau-admin-card__title"><?php esc_html_e( 'Danh sách chuyến', 'datvetaucaotoc-booking' ); ?></h2>

		<form method="get" class="datvetau-admin-filter-bar" id="datvetau-trips-filter-form">
			<input type="hidden" name="page" value="datvetau-booking-trips" />
			<?php if ( $edit ) : ?>
				<input type="hidden" name="edit" value="<?php echo (int) $edit['id']; ?>" />
			<?php endif; ?>
			<div class="datvetau-admin-filter-bar__fields">
				<label class="datvetau-admin-filter-bar__field">
					<span class="datvetau-admin-filter-bar__label"><?php esc_html_e( 'Tuyến', 'datvetaucaotoc-booking' ); ?></span>
					<select name="route_id">
						<option value=""><?php esc_html_e( 'Tất cả tuyến', 'datvetaucaotoc-booking' ); ?></option>
						<?php foreach ( $routes as $r ) : ?>
							<option value="<?php echo (int) $r['id']; ?>" <?php selected( (int) ( $_GET['route_id'] ?? 0 ), (int) $r['id'] ); ?>><?php echo esc_html( (string) $r['label'] ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<label class="datvetau-admin-filter-bar__field" for="datvetau-filter-month">
					<span class="datvetau-admin-filter-bar__label"><?php esc_html_e( 'Tháng', 'datvetaucaotoc-booking' ); ?></span>
					<select name="filter_month" id="datvetau-filter-month">
						<?php foreach ( $month_labels as $num => $label ) : ?>
							<option value="<?php echo (int) $num; ?>" <?php selected( $filter_month, (int) $num ); ?>><?php echo esc_html( $label ); ?></option>
						<?php endforeach; ?>
					</select>
				</label>
				<label class="datvetau-admin-filter-bar__field" for="datvetau-filter-year">
					<span class="datvetau-admin-filter-bar__label"><?php esc_html_e( 'Năm', 'datvetaucaotoc-booking' ); ?></span>
					<select name="filter_year" id="datvetau-filter-year">
						<?php for ( $y = (int) gmdate( 'Y' ) - 1; $y <= (int) gmdate( 'Y' ) + 3; ++$y ) : ?>
							<option value="<?php echo (int) $y; ?>" <?php selected( $filter_year, $y ); ?>><?php echo (int) $y; ?></option>
						<?php endfor; ?>
					</select>
				</label>
				<input type="hidden" name="month" value="<?php echo esc_attr( sprintf( '%04d-%02d', $filter_year, $filter_month ) ); ?>" id="datvetau-filter-month-value" />
				<div class="datvetau-admin-filter-bar__actions">
					<?php submit_button( __( 'Lọc', 'datvetaucaotoc-booking' ), 'secondary', '', false ); ?>
					<a class="button datvetau-admin-btn-reset" href="<?php echo esc_url( $trips_filter_reset_url ); ?>">
						<?php esc_html_e( 'Reset', 'datvetaucaotoc-booking' ); ?>
					</a>
				</div>
			</div>
		</form>

	<form method="post" id="datvetau-trips-bulk-form">
		<?php wp_nonce_field( 'datvetau_trips_bulk_delete' ); ?>
		<input type="hidden" name="redirect_route_id" value="<?php echo esc_attr( (string) ( $_GET['route_id'] ?? '' ) ); ?>" />
		<input type="hidden" name="redirect_month" value="<?php echo esc_attr( $filter_month_ym ); ?>" />
		<div class="tablenav top" style="margin-bottom:8px;">
			<div class="alignleft actions bulkactions">
				<?php
				submit_button(
					__( 'Xóa hàng loạt', 'datvetaucaotoc-booking' ),
					'delete',
					'datvetau_trips_bulk_delete',
					false,
					array(
						'id'    => 'datvetau-trips-bulk-delete-btn',
						'class' => 'button button-delete datvetau-admin-btn-delete',
					)
				);
				?>
			</div>
		</div>
	<table class="widefat striped">
		<thead>
			<tr>
				<td id="cb" class="manage-column column-cb check-column">
					<label class="screen-reader-text" for="datvetau-select-all-trips"><?php esc_html_e( 'Chọn tất cả', 'datvetaucaotoc-booking' ); ?></label>
					<input id="datvetau-select-all-trips" type="checkbox" />
				</td>
				<th><?php esc_html_e( 'Ngày', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Tên chuyến', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Giờ đi', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Giờ đến', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Hạng', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Giá vé (người lớn)', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Giá vé (trẻ em)', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Giá vé (cao tuổi)', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'ghế trống / Tối đa', 'datvetaucaotoc-booking' ); ?></th>
				<th><?php esc_html_e( 'Trạng thái', 'datvetaucaotoc-booking' ); ?></th>
				<th></th>
			</tr>
		</thead>
		<tbody>
		<?php if ( ! $trips ) : ?>
			<tr><td colspan="12"><?php esc_html_e( 'Không có chuyến trong kỳ lọc.', 'datvetaucaotoc-booking' ); ?></td></tr>
		<?php else : ?>
		<?php foreach ( $trips as $t ) : ?>
			<tr>
				<th scope="row" class="check-column">
					<label class="screen-reader-text" for="trip-cb-<?php echo (int) $t['id']; ?>">
						<?php
						printf(
							/* translators: %d trip ID */
							esc_html__( 'Chọn chuyến %d', 'datvetaucaotoc-booking' ),
							(int) $t['id']
						);
						?>
					</label>
					<input
						id="trip-cb-<?php echo (int) $t['id']; ?>"
						class="datvetau-trip-cb"
						type="checkbox"
						name="trip_ids[]"
						value="<?php echo (int) $t['id']; ?>"
					/>
				</th>
				<td><?php echo esc_html( Datvetau_Booking_Admin_Format::date_to_display( (string) $t['trip_date'] ) ); ?></td>
				<td><?php echo esc_html( $route_labels[ (int) $t['route_id'] ] ?? '—' ); ?></td>
				<td><?php echo esc_html( substr( (string) $t['departure_time'], 0, 5 ) ); ?></td>
				<td><?php echo esc_html( substr( (string) $t['arrival_time'], 0, 5 ) ); ?></td>
				<td><?php echo esc_html( strtoupper( (string) $t['seat_class'] ) ); ?></td>
				<td><?php echo esc_html( number_format_i18n( (int) ( $t['price_adult'] ?? $t['price_adult_eco_base'] ?? 0 ) ) ); ?></td>
				<td><?php echo esc_html( number_format_i18n( (int) ( $t['price_child'] ?? 0 ) ) ); ?></td>
				<td><?php echo esc_html( number_format_i18n( (int) ( $t['price_senior'] ?? 0 ) ) ); ?></td>
				<td><?php echo (int) $t['seats_remaining']; ?> / <?php echo (int) $t['capacity']; ?></td>
				<td><?php echo esc_html( Datvetau_Booking_Admin_Format::trip_status_label( (string) $t['status'] ) ); ?></td>
				<td>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=datvetau-booking-trips&edit=' . (int) $t['id'] ) ); ?>"><?php esc_html_e( 'Sửa', 'datvetaucaotoc-booking' ); ?></a>
					|
					<a class="datvetau-admin-action-delete" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=datvetau-booking-trips&datvetau_delete_trip=' . (int) $t['id'] ), 'datvetau_delete_trip_' . (int) $t['id'] ) ); ?>" onclick="return confirm('<?php echo esc_js( __( 'Xóa chuyến này?', 'datvetaucaotoc-booking' ) ); ?>');"><?php esc_html_e( 'Xóa', 'datvetaucaotoc-booking' ); ?></a>
				</td>
			</tr>
		<?php endforeach; ?>
		<?php endif; ?>
		</tbody>
	</table>
	</form>
	</section>
	<script>
	(function () {
		var filterForm = document.getElementById('datvetau-trips-filter-form');
		var m = document.getElementById('datvetau-filter-month');
		var y = document.getElementById('datvetau-filter-year');
		var h = document.getElementById('datvetau-filter-month-value');
		if (filterForm && m && y && h) {
			function syncMonthHidden() {
				var mm = String(m.value).padStart(2, '0');
				h.value = y.value + '-' + mm;
			}
			m.addEventListener('change', syncMonthHidden);
			y.addEventListener('change', syncMonthHidden);
			filterForm.addEventListener('submit', syncMonthHidden);
		}

		var form = document.getElementById('datvetau-trips-bulk-form');
		var selectAll = document.getElementById('datvetau-select-all-trips');
		if (!form || !selectAll) return;

		function rowCheckboxes() {
			return form.querySelectorAll('input.datvetau-trip-cb');
		}

		selectAll.addEventListener('change', function () {
			rowCheckboxes().forEach(function (cb) {
				cb.checked = selectAll.checked;
			});
		});

		form.addEventListener('change', function (e) {
			if (!e.target || !e.target.classList || !e.target.classList.contains('datvetau-trip-cb')) return;
			var boxes = rowCheckboxes();
			var all = boxes.length > 0;
			boxes.forEach(function (cb) {
				if (!cb.checked) all = false;
			});
			selectAll.checked = all;
		});

		form.addEventListener('submit', function (e) {
			var submitter = e.submitter;
			if (!submitter || submitter.name !== 'datvetau_trips_bulk_delete') return;
			var checked = form.querySelectorAll('input.datvetau-trip-cb:checked');
			if (!checked.length) {
				e.preventDefault();
				window.alert(<?php echo wp_json_encode( __( 'Vui lòng chọn ít nhất một chuyến.', 'datvetaucaotoc-booking' ) ); ?>);
				return;
			}
			var msg = <?php echo wp_json_encode( __( 'Xóa %d chuyến đã chọn? Hành động này không thể hoàn tác.', 'datvetaucaotoc-booking' ) ); ?>;
			if (!window.confirm(msg.replace('%d', String(checked.length)))) {
				e.preventDefault();
			}
		});
	})();
	</script>
</div>
