<?php
/**
 * Kurs Cards Template
 *
 * Displays kurse in a responsive card grid with optional filter.
 *
 * Variables available:
 *
 * @var WP_Query              $kurse             WP_Query object with kurs posts.
 * @var bool                  $show_filter       Whether to show the filter bar.
 * @var int                   $columns           Number of columns (2, 3, or 4).
 * @var array<int, WP_Term>   $categories        Array of WP_Term objects for kurs_category.
 * @var array<string, string> $months            Array of available months (YYYY-MM => Label).
 * @var array<string, string> $produktarten      Array of Produktarten (ID => Label).
 * @var string                $filter_category   Currently selected category slug.
 * @var string                $filter_month      Currently selected month (YYYY-MM).
 * @var string                $filter_produktart Currently selected produktart ID.
 *
 * @package KursBooking
 * @since   1.0.0
 */

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

$current_url = remove_query_arg( array( 'kurs_category', 'kurs_month', 'kurs_produktart' ) );

// Get module settings.
$modules       = get_option( 'kurs_booking_modules', array() );
$show_category = isset( $modules['show_category'] ) ? (bool) $modules['show_category'] : true;
?>

<div class="kb-cards-wrapper">
	<?php if ( $show_filter && ( ! empty( $categories ) || ! empty( $months ) || ! empty( $produktarten ) ) ) : ?>
	<div class="kb-cards-filter">
		<form class="kb-filter-form" method="get" action="<?php echo esc_url( $current_url ); ?>">
			<?php if ( ! empty( $produktarten ) && count( $produktarten ) > 1 ) : ?>
			<div class="kb-filter-group">
				<label for="kb-filter-produktart" class="kb-filter-label">
					<span class="dashicons dashicons-tag"></span>
					<?php esc_html_e( 'Service-Typ', 'kurs-booking' ); ?>
				</label>
				<select name="kurs_produktart" id="kb-filter-produktart" class="kb-filter-select">
					<option value=""><?php esc_html_e( 'Alle Service-Typen', 'kurs-booking' ); ?></option>
					<?php foreach ( $produktarten as $value => $label ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $filter_produktart, $value ); ?>>
							<?php echo esc_html( $label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>
			<?php endif; ?>

			<?php if ( ! empty( $categories ) ) : ?>
			<div class="kb-filter-group">
				<label for="kb-filter-category" class="kb-filter-label">
					<span class="dashicons dashicons-category"></span>
					<?php esc_html_e( 'Kategorie', 'kurs-booking' ); ?>
				</label>
				<select name="kurs_category" id="kb-filter-category" class="kb-filter-select">
					<option value=""><?php esc_html_e( 'Alle Kategorien', 'kurs-booking' ); ?></option>
					<?php foreach ( $categories as $category ) : ?>
						<option value="<?php echo esc_attr( $category->slug ); ?>" <?php selected( $filter_category, $category->slug ); ?>>
							<?php echo esc_html( $category->name ); ?> (<?php echo esc_html( (string) $category->count ); ?>)
						</option>
					<?php endforeach; ?>
				</select>
			</div>
			<?php endif; ?>

			<?php if ( ! empty( $months ) ) : ?>
			<div class="kb-filter-group">
				<label for="kb-filter-month" class="kb-filter-label">
					<span class="dashicons dashicons-calendar-alt"></span>
					<?php esc_html_e( 'Monat', 'kurs-booking' ); ?>
				</label>
				<select name="kurs_month" id="kb-filter-month" class="kb-filter-select">
					<option value=""><?php esc_html_e( 'Alle Monate', 'kurs-booking' ); ?></option>
					<?php foreach ( $months as $value => $label ) : ?>
						<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $filter_month, $value ); ?>>
							<?php echo esc_html( $label ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</div>
			<?php endif; ?>

			<div class="kb-filter-actions">
				<button type="submit" class="kb-filter-btn kb-filter-btn--primary">
					<span class="dashicons dashicons-filter"></span>
					<?php esc_html_e( 'Filtern', 'kurs-booking' ); ?>
				</button>
				<?php if ( ! empty( $filter_category ) || ! empty( $filter_month ) || ! empty( $filter_produktart ) ) : ?>
				<a href="<?php echo esc_url( $current_url ); ?>" class="kb-filter-btn kb-filter-btn--secondary">
					<span class="dashicons dashicons-dismiss"></span>
					<?php esc_html_e( 'Zuruecksetzen', 'kurs-booking' ); ?>
				</a>
				<?php endif; ?>
			</div>
		</form>
	</div>
	<?php endif; ?>

	<?php if ( $kurse->have_posts() ) : ?>
	<div class="kb-cards-grid kb-cards-grid--<?php echo esc_attr( (string) $columns ); ?>-cols">
		<?php
		while ( $kurse->have_posts() ) :
			$kurse->the_post();
			$kurs_id = get_the_ID();

			// Get meta data.
			$start_date     = Kurs_Booking_Kurs::get_meta( $kurs_id, 'start_date', '' );
			$end_date       = Kurs_Booking_Kurs::get_meta( $kurs_id, 'end_date', '' );
			$start_time     = Kurs_Booking_Kurs::get_meta( $kurs_id, 'start_time', '' );
			$location       = Kurs_Booking_Kurs::get_meta( $kurs_id, 'location', '' );
			$produktart     = Kurs_Booking_Kurs::get_meta( $kurs_id, 'produktart', 'kurs' );
			$kurs_type      = Kurs_Booking_Kurs::get_meta( $kurs_id, 'type', 'vor_ort' );
			$booking_enabled = Kurs_Booking_Kurs::get_meta( $kurs_id, 'booking_enabled', '1' );
			$varianten      = Kurs_Booking_Kurs::get_varianten( $kurs_id );

			// Calculate price range.
			$prices = array_column( $varianten, 'preis' );
			$min_price = ! empty( $prices ) ? min( $prices ) : 0;
			$max_price = ! empty( $prices ) ? max( $prices ) : 0;

			// Format date.
			$date_display = '';
			if ( ! empty( $start_date ) ) {
				$date_timestamp = strtotime( $start_date );
				if ( $date_timestamp ) {
					$date_display = wp_date( 'D, j. F Y', $date_timestamp );
					if ( ! empty( $end_date ) && $end_date !== $start_date ) {
						$end_timestamp = strtotime( $end_date );
						if ( $end_timestamp ) {
							$date_display = wp_date( 'j.', $date_timestamp ) . ' - ' . wp_date( 'j. F Y', $end_timestamp );
						}
					}
				}
			} elseif ( 'videokurs' === $produktart ) {
				$date_display = __( 'Sofort verfuegbar', 'kurs-booking' );
			}

			// Get category.
			$terms         = get_the_terms( $kurs_id, 'kurs_category' );
			$category_name = '';
			$category_url  = '';
			if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
				$category_name = $terms[0]->name;
				$category_url  = get_term_link( $terms[0] );
				if ( is_wp_error( $category_url ) ) {
					$category_url = '';
				}
			}

			// Check availability.
			$max_capacity = (int) Kurs_Booking_Kurs::get_meta( $kurs_id, 'max_participants', 0 );
			$booked_count = Kurs_Booking_Kurs::get_bookings_count( $kurs_id );
			$is_sold_out  = $max_capacity > 0 && $booked_count >= $max_capacity;
			$spots_left   = $max_capacity > 0 ? max( 0, $max_capacity - $booked_count ) : -1;

			// Sprint 8.3: Produktart badge - dynamisch aus Dienstleistungen.
			$produktart_label = Kurs_Booking_Dienstleistungen::get_name( $produktart );

			// Type icons.
			$type_icons = array(
				'vor_ort' => 'dashicons-location',
				'online'  => 'dashicons-video-alt2',
				'hybrid'  => 'dashicons-randomize',
			);
			$type_icon = $type_icons[ $kurs_type ] ?? 'dashicons-location';
			?>
			<article class="kb-card<?php echo $is_sold_out ? ' kb-card--sold-out' : ''; ?>">
				<div class="kb-card__image">
					<?php if ( has_post_thumbnail() ) : ?>
						<a href="<?php the_permalink(); ?>">
							<?php the_post_thumbnail( 'medium_large', array( 'class' => 'kb-card__img' ) ); ?>
						</a>
					<?php else : ?>
						<a href="<?php the_permalink(); ?>" class="kb-card__placeholder">
							<span class="dashicons dashicons-calendar-alt"></span>
						</a>
					<?php endif; ?>

					<?php if ( $is_sold_out ) : ?>
						<span class="kb-card__badge kb-card__badge--sold-out">
							<?php esc_html_e( 'Ausgebucht', 'kurs-booking' ); ?>
						</span>
					<?php elseif ( $spots_left > 0 && $spots_left <= 5 ) : ?>
						<span class="kb-card__badge kb-card__badge--limited">
							<?php
							/* translators: %d: number of spots left */
							printf( esc_html__( 'Nur noch %d Plaetze', 'kurs-booking' ), (int) $spots_left );
							?>
						</span>
					<?php endif; ?>

					<span class="kb-card__type-badge kb-card__type-badge--<?php echo esc_attr( $produktart ); ?>">
						<?php echo esc_html( $produktart_label ); ?>
					</span>
				</div>

				<div class="kb-card__content">
					<?php if ( $show_category && ! empty( $category_name ) ) : ?>
						<?php if ( ! empty( $category_url ) ) : ?>
							<a href="<?php echo esc_url( $category_url ); ?>" class="kb-card__category"><?php echo esc_html( $category_name ); ?></a>
						<?php else : ?>
							<span class="kb-card__category"><?php echo esc_html( $category_name ); ?></span>
						<?php endif; ?>
					<?php endif; ?>

					<h3 class="kb-card__title">
						<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
					</h3>

					<div class="kb-card__meta">
						<?php if ( ! empty( $date_display ) ) : ?>
						<div class="kb-card__meta-item">
							<span class="dashicons dashicons-calendar-alt"></span>
							<span><?php echo esc_html( $date_display ); ?></span>
						</div>
						<?php endif; ?>

						<?php if ( ! empty( $start_time ) ) : ?>
						<div class="kb-card__meta-item">
							<span class="dashicons dashicons-clock"></span>
							<span><?php echo esc_html( $start_time ); ?> <?php esc_html_e( 'Uhr', 'kurs-booking' ); ?></span>
						</div>
						<?php endif; ?>

						<?php if ( ! empty( $location ) ) : ?>
						<div class="kb-card__meta-item">
							<span class="dashicons <?php echo esc_attr( $type_icon ); ?>"></span>
							<span><?php echo esc_html( $location ); ?></span>
						</div>
						<?php elseif ( 'online' === $kurs_type || 'webinar' === $produktart ) : ?>
						<div class="kb-card__meta-item">
							<span class="dashicons dashicons-video-alt2"></span>
							<span><?php esc_html_e( 'Online via Zoom', 'kurs-booking' ); ?></span>
						</div>
						<?php endif; ?>
					</div>

					<?php if ( has_excerpt() ) : ?>
					<p class="kb-card__excerpt"><?php echo esc_html( wp_trim_words( get_the_excerpt(), 15 ) ); ?></p>
					<?php endif; ?>

					<div class="kb-card__footer">
						<div class="kb-card__price">
							<?php if ( $min_price > 0 ) : ?>
								<?php if ( $min_price === $max_price ) : ?>
									<span class="kb-card__price-value"><?php echo esc_html( number_format( $min_price, 2, ',', '.' ) ); ?> &euro;</span>
								<?php else : ?>
									<span class="kb-card__price-prefix"><?php esc_html_e( 'ab', 'kurs-booking' ); ?></span>
									<span class="kb-card__price-value"><?php echo esc_html( number_format( $min_price, 2, ',', '.' ) ); ?> &euro;</span>
								<?php endif; ?>
							<?php else : ?>
								<span class="kb-card__price-free"><?php esc_html_e( 'Kostenlos', 'kurs-booking' ); ?></span>
							<?php endif; ?>
						</div>

						<a href="<?php the_permalink(); ?>" class="kb-card__btn">
							<?php
							if ( $is_sold_out ) {
								esc_html_e( 'Details ansehen', 'kurs-booking' );
							} elseif ( 'einzelcoaching' === $produktart ) {
								esc_html_e( 'Anfragen', 'kurs-booking' );
							} else {
								esc_html_e( 'Kostenpflichtig buchen', 'kurs-booking' );
							}
							?>
							<span class="dashicons dashicons-arrow-right-alt2"></span>
						</a>
					</div>
				</div>
			</article>
			<?php
		endwhile;
		wp_reset_postdata();
		?>
	</div>
	<?php else : ?>
	<div class="kb-cards-empty">
		<span class="dashicons dashicons-calendar-alt"></span>
		<h3><?php esc_html_e( 'Keine Veranstaltungen gefunden', 'kurs-booking' ); ?></h3>
		<p><?php esc_html_e( 'Aktuell sind keine Veranstaltungen verfuegbar, die Ihren Filterkriterien entsprechen.', 'kurs-booking' ); ?></p>
		<?php if ( ! empty( $filter_category ) || ! empty( $filter_month ) || ! empty( $filter_produktart ) ) : ?>
		<a href="<?php echo esc_url( $current_url ); ?>" class="kb-btn kb-btn--secondary">
			<?php esc_html_e( 'Filter zuruecksetzen', 'kurs-booking' ); ?>
		</a>
		<?php endif; ?>
	</div>
	<?php endif; ?>
</div>
