<?php
/**
 * Taxonomy Archive Template for kurs_category
 *
 * Displays kurse from a specific category as cards.
 *
 * @package Kurs_Booking
 */

defined( 'ABSPATH' ) || exit;

get_header();

// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Standard WordPress template pattern.
$term = get_queried_object();
?>

<div class="kb-taxonomy-archive">
	<div class="kb-taxonomy-archive__header">
		<h1 class="kb-taxonomy-archive__title"><?php echo esc_html( $term->name ); ?></h1>
		<?php if ( ! empty( $term->description ) ) : ?>
			<p class="kb-taxonomy-archive__description"><?php echo esc_html( $term->description ); ?></p>
		<?php endif; ?>
	</div>

	<div class="kb-taxonomy-archive__content">
		<?php
		// Get module settings.
		$modules       = get_option( 'kurs_booking_modules', array() );
		$show_category = isset( $modules['show_category'] ) ? (bool) $modules['show_category'] : true;

		// Build query args.
		// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Standard WordPress pagination pattern.
		$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

		$args = array(
			'post_type'      => 'kurs',
			'post_status'    => 'publish',
			'posts_per_page' => 12,
			'paged'          => $paged,
			'tax_query'      => array(
				array(
					'taxonomy' => 'kurs_category',
					'field'    => 'term_id',
					'terms'    => $term->term_id,
				),
			),
			'meta_key'       => '_kurs_start_date',
			'orderby'        => 'meta_value',
			'order'          => 'ASC',
		);

		$kurse = new WP_Query( $args );

		if ( $kurse->have_posts() ) :
			?>
			<div class="kb-cards-grid kb-cards-grid--3-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' );
					$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' );
					}

					// 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;

					// Produktart badge.
					$produktart_labels = array(
						'kurs'            => __( 'Kurs', 'kurs-booking' ),
						'workshop'        => __( 'Workshop', 'kurs-booking' ),
						'webinar'         => __( 'Webinar', 'kurs-booking' ),
						'gruppencoaching' => __( 'Gruppencoaching', 'kurs-booking' ),
						'einzelcoaching'  => __( 'Einzelcoaching', 'kurs-booking' ),
						'videokurs'       => __( 'Video-Kurs', 'kurs-booking' ),
					);
					$produktart_label = $produktart_labels[ $produktart ] ?? __( 'Veranstaltung', 'kurs-booking' );

					// 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">
							<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
			// Pagination.
			$total_pages = $kurse->max_num_pages;

			if ( $total_pages > 1 ) :
				?>
				<nav class="kb-pagination">
					<?php
					echo wp_kses_post(
						paginate_links(
							array(
								'total'     => $total_pages,
								'current'   => $paged,
								'prev_text' => '<span class="dashicons dashicons-arrow-left-alt2"></span> ' . __( 'Zurück', 'kurs-booking' ),
								'next_text' => __( 'Weiter', 'kurs-booking' ) . ' <span class="dashicons dashicons-arrow-right-alt2"></span>',
							)
						)
					);
					?>
				</nav>
			<?php endif; ?>

		<?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( 'In dieser Kategorie sind aktuell keine Veranstaltungen verfuegbar.', 'kurs-booking' ); ?></p>
			</div>
		<?php endif; ?>
	</div>
</div>

<?php
get_footer();
