<?php
/**
 * Booking Form Template - 3-Step Wizard
 *
 * @package KursBooking
 * @since   1.0.0
 *
 * @var int                        $kurs_id      Kurs post ID.
 * @var WP_Post                    $kurs         Kurs post object.
 * @var string                     $extra_class  Additional CSS classes.
 * @var array<string, string>|null $prefill_data Customer data from portal token (name, email, phone).
 */

declare(strict_types=1);

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Sprint 6.5: Prefill data from Customer Portal.
$prefill_data  = $prefill_data ?? null;
$has_prefill   = is_array( $prefill_data ) && ! empty( $prefill_data['email'] );
$prefill_name  = $has_prefill ? $prefill_data['name'] : '';
$prefill_email = $has_prefill ? $prefill_data['email'] : '';
$prefill_phone = $has_prefill ? $prefill_data['phone'] : '';

// Check if Portal integration is configured (for "Ich bin Kunde" feature).
$portal_url    = get_option( 'kurs_booking_portal_url', '' );
$portal_secret = get_option( 'kurs_booking_portal_secret', '' );
$portal_enabled = ! empty( $portal_url ) && ! empty( $portal_secret );

// Get kurs data.
$varianten       = Kurs_Booking_Kurs::get_varianten( $kurs_id );
$start_date      = Kurs_Booking_Kurs::get_meta( $kurs_id, 'start_date', '' );
$start_time      = Kurs_Booking_Kurs::get_meta( $kurs_id, 'start_time', '' );
$end_time        = Kurs_Booking_Kurs::get_meta( $kurs_id, 'end_time', '' );
$location        = Kurs_Booking_Kurs::get_meta( $kurs_id, 'location', '' );
$address         = Kurs_Booking_Kurs::get_meta( $kurs_id, 'address', '' );
$kurs_type       = Kurs_Booking_Kurs::get_meta( $kurs_id, 'type', 'vor_ort' );
$max_capacity    = (int) Kurs_Booking_Kurs::get_meta( $kurs_id, 'max_teilnehmer', 0 );
$total_booked    = Kurs_Booking_Kurs::get_bookings_count( $kurs_id );
$deposit_enabled = (bool) Kurs_Booking_Kurs::get_meta( $kurs_id, 'deposit_enabled', false );
$deposit_percent = (int) Kurs_Booking_Kurs::get_meta( $kurs_id, 'deposit_percent', 30 );

// Sprint 4.10: Get course days and global hint for per_day variants.
$kurs_days   = Kurs_Booking_Kurs::get_course_days( $kurs_id );
$global_hint = get_option( 'kurs_booking_manual_payment_hint', 'Wird vor Ort verrechnet' );

// Sprint 4.6: Check if this is a digital product (Video-Kurs).
$is_digital_product  = Kurs_Booking_Kurs::is_digital_product( $kurs_id );
$video_access_days   = Kurs_Booking_Kurs::get_video_access_days( $kurs_id );

// Sprint 8.3: Get produktart for field filtering.
$produktart = Kurs_Booking_Kurs::get_meta( $kurs_id, 'produktart', 'kurs' );

// Sprint 8.3: Custom booking fields filtered by produktart.
$custom_fields = Kurs_Booking_Field_Filter::get_fields_for_kurs( $kurs_id );

// Sprint 2.6: Get cancellation policy from individual Settings.
$cancel_free_days    = (int) get_option( 'kurs_booking_cancel_free_days', 28 );
$cancel_partial_days = (int) get_option( 'kurs_booking_cancel_partial_days', 14 );
$cancel_partial_pct  = (int) get_option( 'kurs_booking_cancel_partial_percent', 50 );
$cancel_custom_text  = get_option( 'kurs_booking_cancel_custom_text', '' );

// Sprint 2.6: Get price settings for formatting.
$price_settings = Kurs_Booking_Settings::get_price_settings();

// Format date.
$formatted_date = '';
if ( $start_date ) {
	$timestamp = strtotime( $start_date );
	if ( $timestamp ) {
		$formatted_date = wp_date( 'l, d. F Y', $timestamp );
	}
}

// Nonce.
$nonce = wp_create_nonce( Kurs_Booking_Frontend::NONCE_ACTION );
?>

<div class="kb-booking-form <?php echo esc_attr( $extra_class ); ?><?php echo $has_prefill ? ' kb-booking-form--prefilled' : ''; ?>"
	 data-kurs-id="<?php echo esc_attr( (string) $kurs_id ); ?>"
	 data-is-digital="<?php echo $is_digital_product ? '1' : '0'; ?>"
	 data-kurs-days="<?php echo esc_attr( (string) $kurs_days ); ?>"
	 data-prefill-name="<?php echo esc_attr( $prefill_name ); ?>"
	 data-prefill-email="<?php echo esc_attr( $prefill_email ); ?>"
	 data-prefill-phone="<?php echo esc_attr( $prefill_phone ); ?>"
	 data-portal-enabled="<?php echo $portal_enabled ? '1' : '0'; ?>">

	<!-- Progress Steps -->
	<div class="kb-progress" data-current-step="1">
		<span class="kb-progress__horse" id="kb-progress-horse">🏇</span>
		<div class="kb-progress__step kb-progress__step--active" data-step="1">
			<span class="kb-progress__number">1</span>
			<span class="kb-progress__label"><?php esc_html_e( 'Tickets', 'kurs-booking' ); ?></span>
		</div>
		<div class="kb-progress__line" data-line="1"></div>
		<div class="kb-progress__step" data-step="2">
			<span class="kb-progress__number">2</span>
			<span class="kb-progress__label"><?php esc_html_e( 'Daten', 'kurs-booking' ); ?></span>
		</div>
		<div class="kb-progress__line" data-line="2"></div>
		<div class="kb-progress__step" data-step="3">
			<span class="kb-progress__number">3</span>
			<span class="kb-progress__label"><?php esc_html_e( 'Bestätigen', 'kurs-booking' ); ?></span>
		</div>
	</div>

	<!-- Form Container -->
	<form class="kb-form" id="kb-booking-form-<?php echo esc_attr( (string) $kurs_id ); ?>" novalidate>
		<input type="hidden" name="action" value="kurs_booking_submit">
		<input type="hidden" name="kurs_id" value="<?php echo esc_attr( (string) $kurs_id ); ?>">
		<input type="hidden" name="produktart" value="<?php echo esc_attr( $produktart ); ?>">
		<input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">

		<!-- Honeypot: Invisible field - bots fill it, humans don't see it -->
		<div class="kb-hp-field" aria-hidden="true" style="position:absolute;left:-9999px;top:-9999px;height:0;width:0;overflow:hidden;">
			<label for="kb-website-url">Website</label>
			<input type="text" name="website_url" id="kb-website-url" tabindex="-1" autocomplete="off" value="">
			<input type="text" name="contact_phone_confirm" tabindex="-1" autocomplete="off" value="">
		</div>
		<!-- Timestamp for time-based validation -->
		<input type="hidden" name="kb_form_time" value="<?php echo esc_attr( (string) time() ); ?>">

		<!-- Step 1: Ticket Selection -->
		<div class="kb-step kb-step--active" data-step="1">
			<h3 class="kb-step__title"><?php esc_html_e( '1. Tickets wählen', 'kurs-booking' ); ?></h3>

			<div class="kb-tickets">
				<?php
				foreach ( $varianten as $index => $variante ) :
					$variant_id     = $variante['id'] ?? ( $index + 1 );
					$variant_name   = $variante['name'] ?? '';
					$variant_price  = (float) ( $variante['preis'] ?? 0 );
					$variant_limit  = (int) ( $variante['limit'] ?? 0 );
					$variant_booked = Kurs_Booking_Kurs::get_variant_bookings_count( $kurs_id, $variant_id );

					// Sprint 4.10: Get per_day, auto_invoice, and hinweis.
					$per_day      = ! empty( $variante['per_day'] );
					$auto_invoice = $variante['auto_invoice'] ?? true;
					$hinweis      = $variante['hinweis'] ?? '';
					if ( empty( $hinweis ) && ! $auto_invoice ) {
						$hinweis = $global_hint;
					}

					// Calculate availability.
					$available = 999;
					if ( $variant_limit > 0 ) {
						$available = max( 0, $variant_limit - $variant_booked );
					} elseif ( $max_capacity > 0 ) {
						$available = max( 0, $max_capacity - $total_booked );
					}

					$is_sold_out = $available < 1;
					?>
				<div class="kb-ticket <?php echo $is_sold_out ? 'kb-ticket--sold-out' : ''; ?><?php echo ! $auto_invoice ? ' kb-ticket--manual' : ''; ?>"
					 data-variant-id="<?php echo esc_attr( (string) $variant_id ); ?>"
					 data-price="<?php echo esc_attr( (string) $variant_price ); ?>"
					 data-available="<?php echo esc_attr( (string) $available ); ?>"
					 data-per-day="<?php echo $per_day ? 'true' : 'false'; ?>"
					 data-auto-invoice="<?php echo $auto_invoice ? 'true' : 'false'; ?>"
					 data-hinweis="<?php echo esc_attr( $hinweis ); ?>">

					<div class="kb-ticket__info">
						<h4 class="kb-ticket__name"><?php echo esc_html( $variant_name ); ?></h4>
						<span class="kb-ticket__price">
							<?php // Sprint 2.6: Use Settings for price formatting. ?>
							<?php echo esc_html( Kurs_Booking_Settings::format_price( $variant_price ) ); ?>
							<?php if ( $per_day ) : ?>
								<span class="kb-ticket__per-day"><?php esc_html_e( '/Tag', 'kurs-booking' ); ?></span>
							<?php endif; ?>
						</span>
						<?php if ( $per_day && $kurs_days > 1 ) : ?>
						<span class="kb-ticket__calculated-price" hidden>
							<?php
							printf(
								/* translators: 1: Price per day, 2: Number of days, 3: Total price */
								esc_html__( '(%1$s/Tag × %2$d Tage = %3$s)', 'kurs-booking' ),
								esc_html( Kurs_Booking_Settings::format_price( $variant_price ) ),
								(int) $kurs_days,
								esc_html( Kurs_Booking_Settings::format_price( $variant_price * $kurs_days ) )
							);
							?>
						</span>
						<?php endif; ?>
						<?php if ( ! $auto_invoice && $hinweis ) : ?>
						<span class="kb-ticket__hint">
							<small><?php echo esc_html( $hinweis ); ?></small>
						</span>
						<?php endif; ?>
						<span class="kb-ticket__availability">
							<?php if ( $is_sold_out ) : ?>
								<span class="kb-ticket__sold-out"><?php esc_html_e( 'Ausgebucht', 'kurs-booking' ); ?></span>
							<?php elseif ( $available < 10 ) : ?>
								<?php
								printf(
									/* translators: %d: Number of available tickets */
									esc_html__( 'Noch %d verfügbar', 'kurs-booking' ),
									(int) $available
								);
								?>
							<?php endif; ?>
						</span>
					</div>

					<div class="kb-ticket__quantity">
						<button type="button" class="kb-qty-btn kb-qty-btn--minus" <?php echo $is_sold_out ? 'disabled' : ''; ?>>−</button>
						<input type="number"
							   name="tickets[<?php echo esc_attr( (string) $variant_id ); ?>]"
							   value="0"
							   min="0"
							   max="<?php echo esc_attr( (string) min( $available, 10 ) ); ?>"
							   class="kb-qty-input"
							   <?php echo $is_sold_out ? 'disabled' : ''; ?>>
						<button type="button" class="kb-qty-btn kb-qty-btn--plus" <?php echo $is_sold_out ? 'disabled' : ''; ?>>+</button>
					</div>

					<?php // Sprint 4.10: Days input for per_day variants. ?>
					<?php if ( $per_day && $kurs_days > 1 ) : ?>
					<div class="kb-ticket__days">
						<label class="kb-ticket__days-label">
							<?php esc_html_e( 'Tage:', 'kurs-booking' ); ?>
							<input type="number"
								   name="ticket_days[<?php echo esc_attr( (string) $variant_id ); ?>]"
								   value="<?php echo esc_attr( (string) $kurs_days ); ?>"
								   min="1"
								   max="<?php echo esc_attr( (string) $kurs_days ); ?>"
								   class="kb-days-input"
								   <?php echo $is_sold_out ? 'disabled' : ''; ?>>
							<span class="kb-ticket__days-max">
								<?php
								printf(
									/* translators: %d: Maximum days */
									esc_html__( '(max. %d)', 'kurs-booking' ),
									(int) $kurs_days
								);
								?>
							</span>
						</label>
					</div>
					<?php endif; ?>

					<?php
					// Sprint 4.11: Extra field input for variants with extra_field configured.
					if ( class_exists( 'Kurs_Booking_Custom_Fields' ) && ! empty( $variante['extra_field'] ) ) {
						Kurs_Booking_Custom_Fields::render_variant_extra_input( $variante );
					}
					?>
				</div>
				<?php endforeach; ?>
			</div>

			<!-- Total Display -->
			<div class="kb-total">
				<span class="kb-total__label"><?php esc_html_e( 'Gesamt:', 'kurs-booking' ); ?></span>
				<span class="kb-total__amount" data-total="0">0,00 €</span>
			</div>

			<?php if ( $deposit_enabled ) : ?>
			<div class="kb-deposit-info">
				<span class="kb-deposit-info__label">
					<?php
					printf(
						/* translators: %d: Deposit percentage */
						esc_html__( 'Anzahlung (%d%%):', 'kurs-booking' ),
						(int) $deposit_percent
					);
					?>
				</span>
				<span class="kb-deposit-info__amount" data-deposit="0">0,00 €</span>
			</div>
			<?php endif; ?>

			<div class="kb-step__actions">
				<button type="button" class="kb-btn kb-btn--primary kb-btn--next" data-next="2" disabled>
					<?php esc_html_e( 'Weiter', 'kurs-booking' ); ?>
					<span class="kb-btn__arrow">→</span>
				</button>
			</div>
		</div>

		<!-- Step 2: Contact Data -->
		<div class="kb-step" data-step="2">
			<h3 class="kb-step__title"><?php esc_html_e( '2. Ihre Daten', 'kurs-booking' ); ?></h3>

			<?php if ( $has_prefill ) : ?>
			<!-- Sprint 6.5: Welcome message for prefilled data -->
			<div class="kb-prefill-notice kb-prefill-notice--success">
				<span class="kb-prefill-notice__icon">✓</span>
				<div class="kb-prefill-notice__content">
					<strong><?php esc_html_e( 'Willkommen zurück!', 'kurs-booking' ); ?></strong>
					<p><?php esc_html_e( 'Ihre Daten wurden automatisch ausgefüllt. Bitte überprüfen Sie die Angaben.', 'kurs-booking' ); ?></p>
				</div>
			</div>
			<?php elseif ( $portal_enabled ) : ?>
			<!-- Sprint 6.5: "Ich bin Kunde" section (only when Portal is configured and no prefill) -->
			<div class="kb-existing-customer" id="kb-existing-customer">
				<div class="kb-existing-customer__toggle">
					<button type="button" class="kb-btn kb-btn--outline kb-btn--existing-customer" id="kb-existing-customer-btn">
						<svg class="kb-btn__icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
						<?php esc_html_e( 'Ich bin bereits Kunde', 'kurs-booking' ); ?>
					</button>
					<p class="kb-existing-customer__hint">
						<?php esc_html_e( 'Schneller buchen mit gespeicherten Daten. Wenn Sie bereits Kunde sind, drücken Sie auf den Button "Ich bin bereits Kunde" oder geben Sie unter E-Mail Ihre E-Mail-Adresse ein. Das System prüft automatisch Ihre E-Mail. Sie bekommen anschließend eine E-Mail mit einem Code, welchen Sie bitte eingeben. Alles läuft vollkommen automatisch.', 'kurs-booking' ); ?>
					</p>
				</div>

				<!-- OTP Request Form (hidden initially) -->
				<div class="kb-existing-customer__form" id="kb-otp-request-form" hidden>
					<p class="kb-existing-customer__desc">
						<?php esc_html_e( 'Geben Sie Ihre E-Mail-Adresse ein. Wir senden Ihnen einen Code zur Bestätigung.', 'kurs-booking' ); ?>
					</p>
					<div class="kb-existing-customer__input-group">
						<input type="email"
							   id="kb-otp-email"
							   class="kb-input kb-input--otp-email"
							   placeholder="<?php esc_attr_e( 'Ihre E-Mail-Adresse', 'kurs-booking' ); ?>"
							   autocomplete="email">
						<button type="button" class="kb-btn kb-btn--primary kb-btn--otp-request" id="kb-otp-request-btn">
							<?php esc_html_e( 'Code senden', 'kurs-booking' ); ?>
						</button>
					</div>
					<span class="kb-error-message" id="kb-otp-request-error"></span>
				</div>

				<!-- OTP Verify Form (hidden initially) -->
				<div class="kb-existing-customer__verify" id="kb-otp-verify-form" hidden>
					<p class="kb-existing-customer__desc">
						<?php esc_html_e( 'Geben Sie den 6-stelligen Code ein, den wir an Ihre E-Mail gesendet haben.', 'kurs-booking' ); ?>
					</p>
					<div class="kb-existing-customer__input-group">
						<input type="text"
							   id="kb-otp-code"
							   class="kb-input kb-input--otp-code"
							   placeholder="______"
							   maxlength="6"
							   pattern="[0-9]{6}"
							   inputmode="numeric"
							   autocomplete="one-time-code">
						<button type="button" class="kb-btn kb-btn--primary kb-btn--otp-verify" id="kb-otp-verify-btn">
							<?php esc_html_e( 'Bestätigen', 'kurs-booking' ); ?>
						</button>
					</div>
					<span class="kb-error-message" id="kb-otp-verify-error"></span>
					<button type="button" class="kb-link kb-link--resend" id="kb-otp-resend-btn">
						<?php esc_html_e( 'Code erneut senden', 'kurs-booking' ); ?>
					</button>
				</div>

				<!-- Loading state -->
				<div class="kb-existing-customer__loading" id="kb-otp-loading" hidden>
					<span class="kb-loading__spinner kb-loading__spinner--small"></span>
					<span><?php esc_html_e( 'Bitte warten...', 'kurs-booking' ); ?></span>
				</div>
			</div>

			<hr class="kb-divider">
			<?php endif; ?>

			<!-- All Fields (Core + Custom) from Settings -->
			<?php
			foreach ( $custom_fields as $field ) :
				$field_key       = sanitize_key( $field['name'] ?? '' );
				$field_label     = $field['label'] ?? '';
				$field_type      = $field['type'] ?? 'text';
				// Settings use 'mandatory', template expects 'required' - check both.
				$field_required  = ! empty( $field['required'] ) || ! empty( $field['mandatory'] );
				// Options can be string (newline-separated) or array (already parsed).
				$raw_options     = $field['options'] ?? '';
				$field_options   = array();
				if ( ! empty( $raw_options ) ) {
					$field_options = is_array( $raw_options ) ? $raw_options : explode( "\n", $raw_options );
				}
				$field_page      = ! empty( $field['page'] ) ? absint( $field['page'] ) : 0;
				$field_condition = $field['condition'] ?? '';
				$is_core         = ! empty( $field['core'] );
				$autocomplete    = $field['autocomplete'] ?? '';
				$half_width      = ! empty( $field['half_width'] );
				$field_width     = ! empty( $field['width'] ) ? absint( $field['width'] ) : 0;

				// Build width style.
				// Custom width takes precedence, then half_width fallback.
				$width_style = '';
				$width_class = '';
				if ( $field_width > 0 && $field_width < 100 ) {
					$width_style = sprintf( ' style="width: calc(%d%% - 4px);"', $field_width );
					$width_class = ' kb-form-group--custom-width';
				} elseif ( $half_width ) {
					$width_class = ' kb-form-group--half';
				}

				// Field name attribute: core fields use direct name, others use custom_fields[name].
				$field_name_attr = $is_core ? $field_key : "custom_fields[{$field_key}]";
				$field_id        = $is_core ? "kb-{$field_key}" : "kb-custom-{$field_key}";

				// Autocomplete attribute.
				$autocomplete_attr = ! empty( $autocomplete ) ? sprintf( ' autocomplete="%s"', esc_attr( $autocomplete ) ) : '';

				// Parse condition (format: "field_name:value").
				$condition_field = '';
				$condition_value = '';
				$condition_attrs = '';
				$is_conditional  = false;
				if ( ! empty( $field_condition ) && strpos( $field_condition, ':' ) !== false ) {
					list( $condition_field, $condition_value ) = explode( ':', $field_condition, 2 );
					$condition_field = sanitize_key( $condition_field );
					$condition_value = trim( $condition_value );
					$condition_attrs = sprintf(
						' data-condition-field="%s" data-condition-value="%s"',
						esc_attr( $condition_field ),
						esc_attr( $condition_value )
					);
					$is_conditional = true;
				}
				?>

				<?php if ( 'agreement' === $field_type ) : ?>
					<?php
					// Agreement type: Checkbox with link to page - never apply width styling.
					$agreement_label = $field_label;
					if ( $field_page > 0 ) {
						$page_link  = get_permalink( $field_page );
						$page_title = get_the_title( $field_page );
						if ( $page_link && $page_title ) {
							// Replace %s placeholder with link.
							$link_html = sprintf(
								'<a href="%s" target="_blank" rel="noopener">%s</a>',
								esc_url( $page_link ),
								esc_html( $page_title )
							);
							$agreement_label = str_replace( '%s', $link_html, $agreement_label );
						}
					}
					?>
					<?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $condition_attrs is pre-escaped with esc_attr(). ?>
					<div class="kb-form-group<?php echo ! $is_core ? ' kb-form-group--custom' : ''; ?> kb-form-group--checkbox kb-form-group--agreement<?php echo $is_conditional ? ' kb-form-group--conditional' : ''; ?>"<?php echo $condition_attrs; ?><?php echo $is_conditional ? ' hidden' : ''; ?>>
						<label class="kb-checkbox-label">
							<input type="checkbox"
								   id="<?php echo esc_attr( $field_id ); ?>"
								   name="<?php echo esc_attr( $field_name_attr ); ?>"
								   value="1"
								   class="kb-checkbox"
                                   <?php echo $field_required ? 'required' : ''; ?><?php echo $autocomplete_attr; // phpcs:ignore ?>>
							<span class="kb-checkbox-text">
								<?php
								echo wp_kses(
									$agreement_label,
									array(
										'a' => array(
											'href'   => array(),
											'target' => array(),
											'rel'    => array(),
										),
									)
								);
								?>
								<?php if ( $field_required ) : ?>
									<span class="kb-required">*</span>
								<?php endif; ?>
							</span>
						</label>
						<span class="kb-error-message"></span>
					</div>

				<?php elseif ( 'checkbox' === $field_type ) : ?>
					<?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $condition_attrs is pre-escaped with esc_attr(). ?>
					<div class="kb-form-group<?php echo ! $is_core ? ' kb-form-group--custom' : ''; ?> kb-form-group--checkbox<?php echo $is_conditional ? ' kb-form-group--conditional' : ''; ?>"<?php echo $condition_attrs; ?><?php echo $is_conditional ? ' hidden' : ''; ?>>
						<label class="kb-checkbox-label">
							<input type="checkbox"
								   id="<?php echo esc_attr( $field_id ); ?>"
								   name="<?php echo esc_attr( $field_name_attr ); ?>"
								   value="1"
								   class="kb-checkbox"
                                   <?php echo $field_required ? 'required' : ''; ?><?php echo $autocomplete_attr; // phpcs:ignore ?>>
							<span class="kb-checkbox-text">
								<?php echo esc_html( $field_label ); ?>
								<?php if ( $field_required ) : ?>
									<span class="kb-required">*</span>
								<?php endif; ?>
							</span>
						</label>
						<span class="kb-error-message"></span>
					</div>

				<?php elseif ( 'p' === $field_type ) : ?>
					<?php // Info-Text: Display only, no input field. ?>
					<?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $condition_attrs is pre-escaped. ?>
					<div class="kb-form-group kb-form-group--info<?php echo $is_conditional ? ' kb-form-group--conditional' : ''; ?><?php echo $width_class; ?>"<?php echo $condition_attrs; ?><?php echo $width_style; ?><?php echo $is_conditional ? ' hidden' : ''; ?>>
						<p class="kb-info-text">
							<?php echo wp_kses_post( $field_label ); ?>
						</p>
					</div>

				<?php else : ?>
					<?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All dynamic values pre-escaped. ?>
					<div class="kb-form-group<?php echo ! $is_core ? ' kb-form-group--custom' : ''; ?><?php echo $is_conditional ? ' kb-form-group--conditional' : ''; ?><?php echo $width_class; ?>"<?php echo $condition_attrs; ?><?php echo $width_style; ?><?php echo $is_conditional ? ' hidden' : ''; ?>>
						<label for="<?php echo esc_attr( $field_id ); ?>" class="kb-label">
							<?php echo esc_html( $field_label ); ?>
							<?php if ( $field_required ) : ?>
								<span class="kb-required">*</span>
							<?php endif; ?>
						</label>

						<?php if ( 'textarea' === $field_type ) : ?>
							<textarea id="<?php echo esc_attr( $field_id ); ?>"
									  name="<?php echo esc_attr( $field_name_attr ); ?>"
									  class="kb-textarea"
									  rows="3"
                                      <?php echo $field_required ? 'required' : ''; ?><?php echo $autocomplete_attr; // phpcs:ignore ?>></textarea>

						<?php elseif ( 'select' === $field_type ) : ?>
							<select id="<?php echo esc_attr( $field_id ); ?>"
									name="<?php echo esc_attr( $field_name_attr ); ?>"
									class="kb-select"
                                    <?php echo $field_required ? 'required' : ''; ?><?php echo $autocomplete_attr; // phpcs:ignore ?>>
								<option value=""><?php esc_html_e( 'Bitte wählen...', 'kurs-booking' ); ?></option>
								<?php foreach ( $field_options as $option ) : ?>
									<option value="<?php echo esc_attr( trim( $option ) ); ?>">
										<?php echo esc_html( trim( $option ) ); ?>
									</option>
								<?php endforeach; ?>
							</select>

						<?php elseif ( 'radio' === $field_type ) : ?>
							<div class="kb-radio-group">
								<?php foreach ( $field_options as $option ) : ?>
									<label class="kb-radio-label">
										<input type="radio"
											   name="<?php echo esc_attr( $field_name_attr ); ?>"
											   value="<?php echo esc_attr( trim( $option ) ); ?>"
											   class="kb-radio"
											   <?php echo $field_required ? 'required' : ''; ?>>
										<span class="kb-radio-text"><?php echo esc_html( trim( $option ) ); ?></span>
									</label>
								<?php endforeach; ?>
							</div>

						<?php else : ?>
							<?php
							// Map custom types to HTML5 input types and add patterns.
							$input_type       = $field_type;
							$pattern_attr     = '';
							$title_attr       = '';
							$placeholder_attr = ! empty( $field['placeholder'] ) ? sprintf( ' placeholder="%s"', esc_attr( $field['placeholder'] ) ) : '';

							switch ( $field_type ) {
								case 'name':
									$input_type   = 'text';
									$pattern_attr = ' pattern="[A-Za-zÄÖÜäöüß\\s\\-]+"';
									$title_attr   = sprintf( ' title="%s"', esc_attr__( 'Nur Buchstaben, Leerzeichen und Bindestrich', 'kurs-booking' ) );
									if ( empty( $placeholder_attr ) ) {
										$placeholder_attr = sprintf( ' placeholder="%s"', esc_attr__( 'Vorname Nachname', 'kurs-booking' ) );
									}
									break;

								case 'plz':
									$input_type   = 'text';
									$pattern_attr = ' pattern="[0-9]{4,5}"';
									$title_attr   = sprintf( ' title="%s"', esc_attr__( '4-5 Ziffern (AT/DE)', 'kurs-booking' ) );
									if ( empty( $placeholder_attr ) ) {
										$placeholder_attr = sprintf( ' placeholder="%s"', esc_attr__( 'z.B. 1010 oder 80331', 'kurs-booking' ) );
									}
									break;

								case 'city':
									$input_type   = 'text';
									$pattern_attr = ' pattern="[A-Za-zÄÖÜäöüß\\s\\-]+"';
									$title_attr   = sprintf( ' title="%s"', esc_attr__( 'Nur Buchstaben, Leerzeichen und Bindestrich', 'kurs-booking' ) );
									if ( empty( $placeholder_attr ) ) {
										$placeholder_attr = sprintf( ' placeholder="%s"', esc_attr__( 'z.B. Wien oder München', 'kurs-booking' ) );
									}
									break;

								case 'iban':
									$input_type   = 'text';
									$pattern_attr = ' pattern="[A-Z]{2}[0-9]{2}[A-Z0-9]{4}[0-9]{7}([A-Z0-9]?){0,16}"';
									$title_attr   = sprintf( ' title="%s"', esc_attr__( 'Gültiges IBAN-Format (z.B. AT61 1904 3002 3457 3201)', 'kurs-booking' ) );
									if ( empty( $placeholder_attr ) ) {
										$placeholder_attr = sprintf( ' placeholder="%s"', esc_attr__( 'AT00 0000 0000 0000 0000', 'kurs-booking' ) );
									}
									break;

								case 'country':
									$input_type = 'text';
									if ( empty( $placeholder_attr ) ) {
										$placeholder_attr = sprintf( ' placeholder="%s"', esc_attr__( 'z.B. Österreich oder Deutschland', 'kurs-booking' ) );
									}
									break;

								case 'address':
									$input_type = 'text';
									if ( empty( $placeholder_attr ) ) {
										$placeholder_attr = sprintf( ' placeholder="%s"', esc_attr__( 'Straße und Hausnummer', 'kurs-booking' ) );
									}
									break;

								case 'url':
									$input_type = 'url';
									if ( empty( $placeholder_attr ) ) {
										$placeholder_attr = sprintf( ' placeholder="%s"', esc_attr__( 'https://www.beispiel.at', 'kurs-booking' ) );
									}
									break;
							}
							?>
							<input type="<?php echo esc_attr( $input_type ); ?>"
								   id="<?php echo esc_attr( $field_id ); ?>"
								   name="<?php echo esc_attr( $field_name_attr ); ?>"
								   class="kb-input"
								   <?php echo $field_required ? 'required' : ''; ?><?php echo $autocomplete_attr; // phpcs:ignore ?><?php echo $pattern_attr; // phpcs:ignore ?><?php echo $title_attr; // phpcs:ignore ?><?php echo $placeholder_attr; // phpcs:ignore ?>>
						<?php endif; ?>

						<span class="kb-error-message"></span>
					</div>
				<?php endif; ?>

			<?php endforeach; ?>

			<div class="kb-form-group">
				<label for="kb-message" class="kb-label">
					<?php esc_html_e( 'Nachricht (optional)', 'kurs-booking' ); ?>
				</label>
				<textarea id="kb-message"
						  name="message"
						  class="kb-textarea"
						  rows="3"
						  placeholder="<?php esc_attr_e( 'Haben Sie besondere Wünsche oder Fragen?', 'kurs-booking' ); ?>"></textarea>
			</div>

			<div class="kb-step__actions">
				<button type="button" class="kb-btn kb-btn--secondary kb-btn--back" data-back="1">
					<span class="kb-btn__arrow">←</span>
					<?php esc_html_e( 'Zurück', 'kurs-booking' ); ?>
				</button>
				<button type="button" class="kb-btn kb-btn--primary kb-btn--next" data-next="3">
					<?php esc_html_e( 'Weiter', 'kurs-booking' ); ?>
					<span class="kb-btn__arrow">→</span>
				</button>
			</div>
		</div>

		<!-- Step 3: Confirmation -->
		<div class="kb-step" data-step="3">
			<h3 class="kb-step__title"><?php esc_html_e( '3. Buchung bestätigen', 'kurs-booking' ); ?></h3>

			<!-- Summary -->
			<div class="kb-summary">
				<h4 class="kb-summary__section-title">
					<?php echo $is_digital_product ? esc_html__( 'Video-Kurs', 'kurs-booking' ) : esc_html__( 'Kurs', 'kurs-booking' ); ?>
				</h4>
				<div class="kb-summary__row">
					<span class="kb-summary__label">
						<?php echo $is_digital_product ? esc_html__( 'Produkt:', 'kurs-booking' ) : esc_html__( 'Kurs:', 'kurs-booking' ); ?>
					</span>
					<span class="kb-summary__value"><?php echo esc_html( get_the_title( $kurs_id ) ); ?></span>
				</div>

				<?php if ( $is_digital_product ) : ?>
				<!-- Sprint 4.6: Video-Kurs specific info -->
				<div class="kb-summary__row">
					<span class="kb-summary__label"><?php esc_html_e( 'Zugang:', 'kurs-booking' ); ?></span>
					<span class="kb-summary__value">
						<?php
						if ( $video_access_days > 0 ) {
							printf(
								/* translators: %d: Number of days */
								esc_html__( '%d Tage ab Freischaltung', 'kurs-booking' ),
								(int) $video_access_days
							);
						} else {
							esc_html_e( 'Unbegrenzter Zugang', 'kurs-booking' );
						}
						?>
					</span>
				</div>
				<div class="kb-summary__row">
					<span class="kb-summary__label"><?php esc_html_e( 'Bereitstellung:', 'kurs-booking' ); ?></span>
					<span class="kb-summary__value"><?php esc_html_e( 'Sofort nach Zahlungseingang', 'kurs-booking' ); ?></span>
				</div>

				<?php else : ?>
				<!-- Non-digital products: show date/time/location -->
				<div class="kb-summary__row">
					<span class="kb-summary__label"><?php esc_html_e( 'Datum:', 'kurs-booking' ); ?></span>
					<span class="kb-summary__value">
						<?php echo esc_html( $formatted_date ); ?>
						<?php if ( $start_time ) : ?>
							, <?php echo esc_html( $start_time ); ?>
							<?php if ( $end_time ) : ?>
								– <?php echo esc_html( $end_time ); ?>
							<?php endif; ?>
							<?php esc_html_e( 'Uhr', 'kurs-booking' ); ?>
						<?php endif; ?>
					</span>
				</div>
					<?php if ( $location && 'online' !== $kurs_type ) : ?>
				<div class="kb-summary__row">
					<span class="kb-summary__label"><?php esc_html_e( 'Ort:', 'kurs-booking' ); ?></span>
					<span class="kb-summary__value"><?php echo esc_html( $location ); ?></span>
				</div>
				<?php endif; ?>
					<?php if ( 'online' === $kurs_type || 'hybrid' === $kurs_type ) : ?>
				<div class="kb-summary__row">
					<span class="kb-summary__label"><?php esc_html_e( 'Format:', 'kurs-booking' ); ?></span>
					<span class="kb-summary__value">
						<?php
						$type_labels = array(
							'online' => __( 'Online (Zoom)', 'kurs-booking' ),
							'hybrid' => __( 'Hybrid (Vor Ort + Online)', 'kurs-booking' ),
						);
						echo esc_html( $type_labels[ $kurs_type ] ?? $kurs_type );
						?>
					</span>
				</div>
				<?php endif; ?>
				<?php endif; ?>

				<h4 class="kb-summary__section-title"><?php esc_html_e( 'Ihre Buchung', 'kurs-booking' ); ?></h4>
				<div class="kb-summary__tickets" id="kb-summary-tickets">
					<!-- Filled by JavaScript -->
				</div>

				<div class="kb-summary__total">
					<span class="kb-summary__label"><?php esc_html_e( 'Gesamtpreis:', 'kurs-booking' ); ?></span>
					<span class="kb-summary__value kb-summary__value--total" id="kb-summary-total">0,00 €</span>
				</div>

				<?php if ( $deposit_enabled ) : ?>
				<div class="kb-summary__deposit">
					<span class="kb-summary__label">
						<?php
						printf(
							/* translators: %d: Deposit percentage */
							esc_html__( 'Anzahlung (%d%%):', 'kurs-booking' ),
							(int) $deposit_percent
						);
						?>
					</span>
					<span class="kb-summary__value" id="kb-summary-deposit">0,00 €</span>
				</div>
				<div class="kb-summary__remaining">
					<span class="kb-summary__label"><?php esc_html_e( 'Restbetrag:', 'kurs-booking' ); ?></span>
					<span class="kb-summary__value" id="kb-summary-remaining">0,00 €</span>
				</div>
				<?php endif; ?>

				<h4 class="kb-summary__section-title"><?php esc_html_e( 'Ihre Daten', 'kurs-booking' ); ?></h4>
				<div class="kb-summary__contact" id="kb-summary-contact">
					<!-- Filled by JavaScript -->
				</div>
			</div>

			<?php if ( $is_digital_product ) : ?>
			<!-- Sprint 4.6: Digital Product Notice (Video-Kurs) -->
			<div class="kb-legal kb-legal--digital-product">
				<h4 class="kb-legal__title"><?php esc_html_e( 'Digitales Produkt', 'kurs-booking' ); ?></h4>
				<div class="kb-legal__content">
					<p>
						<strong><?php esc_html_e( 'Sofortige Bereitstellung:', 'kurs-booking' ); ?></strong>
						<?php
						if ( $video_access_days > 0 ) {
							printf(
								/* translators: %d: Number of days for video access */
								esc_html__( 'Nach Zahlungseingang erhalten Sie sofort Zugang zu den Videos. Der Zugang ist %d Tage gueltig.', 'kurs-booking' ),
								(int) $video_access_days
							);
						} else {
							esc_html_e( 'Nach Zahlungseingang erhalten Sie sofort unbegrenzten Zugang zu den Videos.', 'kurs-booking' );
						}
						?>
					</p>
					<p>
						<strong><?php esc_html_e( 'Keine Stornierung:', 'kurs-booking' ); ?></strong>
						<?php esc_html_e( 'Bei digitalen Produkten ist keine Stornierung moeglich, da der Zugang sofort bereitgestellt wird.', 'kurs-booking' ); ?>
					</p>
				</div>
			</div>

				<?php if ( Kurs_Booking_Settings::is_module_active( 'widerrufsrecht' ) ) : ?>
			<!-- Sprint 4.6: Withdrawal Notice for Digital Products (§356 Abs. 5 BGB) -->
			<div class="kb-legal kb-legal--withdrawal kb-legal--withdrawal-digital">
				<h4 class="kb-legal__title"><?php esc_html_e( 'Widerrufsrecht bei digitalen Inhalten', 'kurs-booking' ); ?></h4>
				<div class="kb-legal__content">
					<p>
						<?php esc_html_e( 'Sie haben das Recht, binnen 14 Tagen ohne Angabe von Gruenden diesen Vertrag zu widerrufen. Das Widerrufsrecht erlischt jedoch vorzeitig, wenn Sie ausdruecklich zustimmen, dass wir mit der Ausfuehrung des Vertrags (Bereitstellung der digitalen Inhalte) vor Ablauf der Widerrufsfrist beginnen, und Sie Ihre Kenntnis davon bestaetigt haben, dass Sie durch Ihre Zustimmung mit Beginn der Ausfuehrung Ihr Widerrufsrecht verlieren (§ 356 Abs. 5 BGB).', 'kurs-booking' ); ?>
					</p>
				</div>
			</div>
			<?php endif; ?>

			<?php else : ?>
			<!-- Sprint 2.6: Cancellation Policy from Settings (for non-digital products) -->
			<div class="kb-legal kb-legal--cancellation">
				<h4 class="kb-legal__title"><?php esc_html_e( 'Stornobedingungen', 'kurs-booking' ); ?></h4>
				<div class="kb-legal__content">
					<?php
					if ( ! empty( $cancel_custom_text ) ) {
						echo wp_kses_post( $cancel_custom_text );
					} else {
						?>
						<ul>
							<li><?php printf( esc_html__( 'Bis %d Tage vor Kursbeginn: kostenfrei', 'kurs-booking' ), (int) $cancel_free_days ); ?></li>
							<li><?php printf( esc_html__( 'Bis %1$d Tage vor Kursbeginn: %2$d%% der Kursgebühr', 'kurs-booking' ), (int) $cancel_partial_days, (int) $cancel_partial_pct ); ?></li>
							<li><?php printf( esc_html__( 'Weniger als %d Tage vorher: 100%% der Kursgebühr', 'kurs-booking' ), (int) $cancel_partial_days ); ?></li>
						</ul>
						<?php
					}
					?>
				</div>
			</div>

			<!-- Withdrawal Notice (§312g BGB) for non-digital products -->
			<div class="kb-legal kb-legal--withdrawal">
				<h4 class="kb-legal__title"><?php esc_html_e( 'Widerrufsrecht', 'kurs-booking' ); ?></h4>
				<div class="kb-legal__content">
					<p>
						<?php esc_html_e( 'Bei Dienstleistungen im Bereich Freizeitbetätigungen (hier: Reitkurs) mit spezifischem Termin besteht gemäß § 312g Abs. 2 Nr. 9 BGB kein Widerrufsrecht.', 'kurs-booking' ); ?>
					</p>
				</div>
			</div>
			<?php endif; ?>

			<!-- Sprint 2.6: AGB Acceptance from Settings -->
			<div class="kb-form-group kb-form-group--checkbox">
				<label class="kb-checkbox-label">
					<input type="checkbox"
						   name="agb_accepted"
						   value="1"
						   class="kb-checkbox"
						   required
						   id="kb-agb-accepted">
					<span class="kb-checkbox-text">
						<?php
						// Use Settings helper for AGB checkbox HTML with proper links.
						echo wp_kses(
							Kurs_Booking_Settings::get_agb_checkbox_html(),
							array(
								'a' => array(
									'href'   => array(),
									'target' => array(),
									'rel'    => array(),
								),
							)
						);
						?>
						<span class="kb-required">*</span>
					</span>
				</label>
				<span class="kb-error-message"></span>
			</div>

			<?php if ( $is_digital_product && Kurs_Booking_Settings::is_module_active( 'widerrufsrecht' ) ) : ?>
				<?php
				// Get company name for withdrawal consent text.
				$company_name = get_option( 'kurs_booking_company_name', get_bloginfo( 'name' ) );
				?>
			<!-- Sprint 4.6: Withdrawal Consent for Digital Products (§356 Abs. 5 BGB) -->
			<!-- WICHTIG: Separate Checkbox, nicht vorausgefuellt, getrennt von AGB! -->
			<div class="kb-form-group kb-form-group--checkbox kb-form-group--withdrawal-consent">
				<label class="kb-checkbox-label kb-checkbox-label--withdrawal">
					<input type="checkbox"
						   name="withdrawal_consent"
						   value="1"
						   class="kb-checkbox kb-checkbox--withdrawal"
						   required
						   id="kb-withdrawal-consent">
					<span class="kb-checkbox-text kb-checkbox-text--withdrawal">
						<?php
						printf(
							/* translators: %s: Company name */
							esc_html__( 'Ich stimme der Vertragsausfuehrung durch %s vor Ablauf der Widerrufsfrist zu und weiss, dass dadurch mein Widerrufsrecht erlischt.', 'kurs-booking' ),
							esc_html( $company_name )
						);
						?>
						<span class="kb-required">*</span>
					</span>
				</label>
				<span class="kb-error-message"></span>
			</div>
			<input type="hidden" name="is_digital_product" value="1">
			<?php elseif ( $is_digital_product ) : ?>
			<input type="hidden" name="is_digital_product" value="1">
			<?php endif; ?>

			<?php
			// Cloudflare Turnstile Spam-Schutz.
			$turnstile_enabled  = get_option( 'kurs_booking_turnstile_enabled', false );
			$turnstile_test_mode = get_option( 'kurs_booking_turnstile_test_mode', false );
			$turnstile_site_key = $turnstile_test_mode
				? '1x00000000000000000000AA' // Cloudflare Test-Key (always passes, visible).
				: get_option( 'kurs_booking_turnstile_site_key', '' );
			$turnstile_theme    = get_option( 'kurs_booking_turnstile_theme', 'auto' );

			// Im Test-Modus oder wenn echter Key vorhanden.
			if ( $turnstile_enabled && ( $turnstile_test_mode || $turnstile_site_key ) ) :
				?>
			<div class="kb-turnstile-wrapper" style="margin: 20px 0;">
				<?php if ( $turnstile_test_mode ) : ?>
				<div style="margin-bottom: 10px; padding: 8px 12px; background: #fff3cd; border-left: 4px solid #ffc107; font-size: 12px;">
					<strong><?php esc_html_e( 'Test-Modus:', 'kurs-booking' ); ?></strong>
					<?php esc_html_e( 'Turnstile verwendet Sandbox-Keys.', 'kurs-booking' ); ?>
				</div>
				<?php endif; ?>
				<div class="cf-turnstile"
					 data-sitekey="<?php echo esc_attr( $turnstile_site_key ); ?>"
					 data-theme="<?php echo esc_attr( $turnstile_theme ); ?>"
					 data-callback="kbTurnstileCallback"
					 data-error-callback="kbTurnstileError"></div>
				<span class="kb-error-message kb-turnstile-error" id="kb-turnstile-error"></span>
			</div>
			<?php endif; ?>

			<div class="kb-step__actions">
				<button type="button" class="kb-btn kb-btn--secondary kb-btn--back" data-back="2">
					<span class="kb-btn__arrow">←</span>
					<?php esc_html_e( 'Zurück', 'kurs-booking' ); ?>
				</button>
				<!-- §312j BGB: Button MUSS auf Zahlungspflicht hinweisen! -->
				<button type="submit" class="kb-btn kb-btn--primary kb-btn--submit">
					<?php esc_html_e( 'Zahlungspflichtig buchen', 'kurs-booking' ); ?>
				</button>
			</div>
		</div>

		<!-- Loading State -->
		<div class="kb-loading" hidden>
			<div class="kb-loading__spinner"></div>
			<p class="kb-loading__text"><?php esc_html_e( 'Buchung wird verarbeitet...', 'kurs-booking' ); ?></p>
		</div>

		<!-- Success State -->
		<div class="kb-success" hidden>
			<div class="kb-success__icon">✓</div>
			<h3 class="kb-success__title"><?php esc_html_e( 'Buchungsanfrage gesendet!', 'kurs-booking' ); ?></h3>
			<p class="kb-success__message">
				<?php esc_html_e( 'Vielen Dank! Bitte bestätigen Sie Ihre E-Mail-Adresse über den Link in der Bestätigungs-E-Mail.', 'kurs-booking' ); ?>
			</p>
			<p class="kb-success__booking-number"></p>
		</div>

	</form>
</div>
