<?php
/**
 * News/Notification management for Kurs-Booking.
 *
 * Manages popup notifications for courses and products.
 * Admin can select any courses to feature in popups.
 * Display is randomized from selected items.
 *
 * @package KursBooking
 * @since   1.1.0
 */

declare(strict_types=1);

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

/**
 * Class Kurs_Booking_Neuigkeit
 *
 * Handles the kurs-neuigkeit custom post type for news notifications.
 */
class Kurs_Booking_Neuigkeit {

	/**
	 * Initialize the class.
	 */
	public static function init(): void {
		add_action( 'init', array( __CLASS__, 'register_post_type' ) );
		add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );
		add_action( 'save_post_kurs-neuigkeit', array( __CLASS__, 'save_meta' ), 10, 2 );
		add_filter( 'manage_kurs-neuigkeit_posts_columns', array( __CLASS__, 'add_admin_columns' ) );
		add_action( 'manage_kurs-neuigkeit_posts_custom_column', array( __CLASS__, 'render_admin_column' ), 10, 2 );
		add_action( 'wp_footer', array( __CLASS__, 'render_frontend_popup' ) );
	}

	/**
	 * Register the neuigkeit post type.
	 */
	public static function register_post_type(): void {
		$labels = array(
			'name'               => __( 'Neuigkeiten', 'kurs-booking' ),
			'singular_name'      => __( 'Neuigkeit', 'kurs-booking' ),
			'add_new'            => __( 'Neue Neuigkeit', 'kurs-booking' ),
			'add_new_item'       => __( 'Neue Neuigkeit erstellen', 'kurs-booking' ),
			'edit_item'          => __( 'Neuigkeit bearbeiten', 'kurs-booking' ),
			'new_item'           => __( 'Neue Neuigkeit', 'kurs-booking' ),
			'view_item'          => __( 'Neuigkeit ansehen', 'kurs-booking' ),
			'search_items'       => __( 'Neuigkeiten suchen', 'kurs-booking' ),
			'not_found'          => __( 'Keine Neuigkeiten gefunden', 'kurs-booking' ),
			'not_found_in_trash' => __( 'Keine Neuigkeiten im Papierkorb', 'kurs-booking' ),
			'menu_name'          => __( 'Neuigkeiten', 'kurs-booking' ),
		);

		$args = array(
			'labels'       => $labels,
			'public'       => false,
			'show_ui'      => true,
			'show_in_menu' => 'edit.php?post_type=kurs',
			'supports'     => array( 'title', 'editor', 'thumbnail' ),
			'menu_icon'    => 'dashicons-megaphone',
			'rewrite'      => false,
			'has_archive'  => false,
		);

		register_post_type( 'kurs-neuigkeit', $args );
	}

	/**
	 * Add meta boxes to neuigkeit edit screen.
	 */
	public static function add_meta_boxes(): void {
		add_meta_box(
			'kurs_neuigkeit_settings',
			__( 'Popup-Einstellungen', 'kurs-booking' ),
			array( __CLASS__, 'render_settings_meta_box' ),
			'kurs-neuigkeit',
			'side',
			'high'
		);

		add_meta_box(
			'kurs_neuigkeit_kurse',
			__( 'Verknuepfte Kurse/Produkte', 'kurs-booking' ),
			array( __CLASS__, 'render_kurse_meta_box' ),
			'kurs-neuigkeit',
			'normal',
			'high'
		);

		add_meta_box(
			'kurs_neuigkeit_stats',
			__( 'Statistiken', 'kurs-booking' ),
			array( __CLASS__, 'render_stats_meta_box' ),
			'kurs-neuigkeit',
			'side',
			'default'
		);
	}

	/**
	 * Render the settings meta box.
	 *
	 * @param WP_Post $post Current post object.
	 */
	public static function render_settings_meta_box( WP_Post $post ): void {
		wp_nonce_field( 'kurs_neuigkeit_meta', 'kurs_neuigkeit_nonce' );

		$show_popup     = get_post_meta( $post->ID, '_neuigkeit_show_popup', true );
		$popup_start    = get_post_meta( $post->ID, '_neuigkeit_popup_start', true );
		$popup_expires  = get_post_meta( $post->ID, '_neuigkeit_popup_expires', true );
		$popup_priority = get_post_meta( $post->ID, '_neuigkeit_priority', true ) ?: '10';
		$cta_text       = get_post_meta( $post->ID, '_neuigkeit_cta_text', true ) ?: __( 'Mehr erfahren', 'kurs-booking' );
		$cta_url        = get_post_meta( $post->ID, '_neuigkeit_cta_url', true );
		?>
		<p>
			<label>
				<input type="checkbox" name="neuigkeit_show_popup" value="1" <?php checked( $show_popup, '1' ); ?>>
				<strong><?php esc_html_e( 'Als Popup anzeigen', 'kurs-booking' ); ?></strong>
			</label>
		</p>

		<p>
			<label for="neuigkeit_popup_start"><?php esc_html_e( 'Anzeigen ab:', 'kurs-booking' ); ?></label><br>
			<input type="date" id="neuigkeit_popup_start" name="neuigkeit_popup_start"
				value="<?php echo esc_attr( $popup_start ); ?>" class="widefat">
		</p>

		<p>
			<label for="neuigkeit_popup_expires"><?php esc_html_e( 'Anzeigen bis:', 'kurs-booking' ); ?></label><br>
			<input type="date" id="neuigkeit_popup_expires" name="neuigkeit_popup_expires"
				value="<?php echo esc_attr( $popup_expires ); ?>" class="widefat">
		</p>

		<p>
			<label for="neuigkeit_priority"><?php esc_html_e( 'Prioritaet:', 'kurs-booking' ); ?></label><br>
			<input type="number" id="neuigkeit_priority" name="neuigkeit_priority"
				value="<?php echo esc_attr( $popup_priority ); ?>" min="1" max="100" class="small-text">
			<span class="description"><?php esc_html_e( '1 = hoechste', 'kurs-booking' ); ?></span>
		</p>

		<hr>

		<p>
			<label for="neuigkeit_cta_text"><?php esc_html_e( 'Button-Text:', 'kurs-booking' ); ?></label><br>
			<input type="text" id="neuigkeit_cta_text" name="neuigkeit_cta_text"
				value="<?php echo esc_attr( $cta_text ); ?>" class="widefat">
		</p>

		<p>
			<label for="neuigkeit_cta_url"><?php esc_html_e( 'Button-Link (optional):', 'kurs-booking' ); ?></label><br>
			<input type="url" id="neuigkeit_cta_url" name="neuigkeit_cta_url"
				value="<?php echo esc_attr( $cta_url ); ?>" class="widefat"
				placeholder="<?php esc_attr_e( 'Leer = Link zum ersten Kurs', 'kurs-booking' ); ?>">
		</p>
		<?php
	}

	/**
	 * Render the kurse selection meta box.
	 *
	 * @param WP_Post $post Current post object.
	 */
	public static function render_kurse_meta_box( WP_Post $post ): void {
		$selected_kurse = get_post_meta( $post->ID, '_neuigkeit_kurse', true ) ?: array();
		$selected_kategorien = get_post_meta( $post->ID, '_neuigkeit_kategorien', true ) ?: array();
		$selected_produktarten = get_post_meta( $post->ID, '_neuigkeit_produktarten', true ) ?: array();
		$selection_mode = get_post_meta( $post->ID, '_neuigkeit_selection_mode', true ) ?: 'kurse';

		// Get all kurse
		$kurse = get_posts(
			array(
				'post_type'      => 'kurs',
				'posts_per_page' => -1,
				'orderby'        => 'title',
				'order'          => 'ASC',
				'post_status'    => 'publish',
			)
		);

		// Get all categories
		$kategorien = get_terms(
			array(
				'taxonomy'   => 'kurs_category',
				'hide_empty' => false,
			)
		);

		// Get produktarten from settings
		$produktarten = self::get_produktarten();
		?>
		<style>
			.kb-selection-mode { margin-bottom: 15px; padding: 10px; background: #f9f9f9; border-radius: 4px; }
			.kb-selection-mode label { margin-right: 20px; cursor: pointer; }
			.kb-selection-panel { display: none; }
			.kb-selection-panel.active { display: block; }
			.kb-kurse-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 10px; max-height: 400px; overflow-y: auto; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
			.kb-kurse-grid label { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #fff; border: 1px solid #e0e0e0; border-radius: 4px; cursor: pointer; transition: all 0.2s; }
			.kb-kurse-grid label:hover { border-color: #2271b1; background: #f0f7fc; }
			.kb-kurse-grid label.selected { background: #e8f4fc; border-color: #2271b1; }
			.kb-kurse-grid .kb-kurs-info { flex: 1; }
			.kb-kurse-grid .kb-kurs-title { font-weight: 500; display: block; }
			.kb-kurse-grid .kb-kurs-meta { font-size: 11px; color: #666; }
			.kb-kategorie-list, .kb-produktart-list { display: flex; flex-wrap: wrap; gap: 10px; padding: 10px; }
			.kb-kategorie-list label, .kb-produktart-list label { padding: 8px 16px; background: #f0f0f0; border-radius: 20px; cursor: pointer; transition: all 0.2s; }
			.kb-kategorie-list label:hover, .kb-produktart-list label:hover { background: #e0e0e0; }
			.kb-kategorie-list label.selected, .kb-produktart-list label.selected { background: #2271b1; color: #fff; }
		</style>

		<div class="kb-selection-mode">
			<strong><?php esc_html_e( 'Auswahl-Modus:', 'kurs-booking' ); ?></strong><br><br>
			<label>
				<input type="radio" name="neuigkeit_selection_mode" value="kurse" <?php checked( $selection_mode, 'kurse' ); ?>>
				<?php esc_html_e( 'Einzelne Kurse', 'kurs-booking' ); ?>
			</label>
			<label>
				<input type="radio" name="neuigkeit_selection_mode" value="kategorien" <?php checked( $selection_mode, 'kategorien' ); ?>>
				<?php esc_html_e( 'Nach Kategorie', 'kurs-booking' ); ?>
			</label>
			<label>
				<input type="radio" name="neuigkeit_selection_mode" value="produktarten" <?php checked( $selection_mode, 'produktarten' ); ?>>
				<?php esc_html_e( 'Nach Produktart', 'kurs-booking' ); ?>
			</label>
			<label>
				<input type="radio" name="neuigkeit_selection_mode" value="alle" <?php checked( $selection_mode, 'alle' ); ?>>
				<?php esc_html_e( 'Alle Kurse', 'kurs-booking' ); ?>
			</label>
		</div>

		<!-- Einzelne Kurse -->
		<div class="kb-selection-panel" data-mode="kurse">
			<p><strong><?php esc_html_e( 'Kurse auswaehlen:', 'kurs-booking' ); ?></strong></p>
			<div class="kb-kurse-grid">
				<?php foreach ( $kurse as $kurs ) :
					$produktart = get_post_meta( $kurs->ID, '_produktart', true ) ?: 'A';
					$preis = get_post_meta( $kurs->ID, '_preis', true );
					$start_date = get_post_meta( $kurs->ID, '_start_date', true );
					$is_selected = in_array( (string) $kurs->ID, $selected_kurse, true );
				?>
					<label class="<?php echo $is_selected ? 'selected' : ''; ?>">
						<input type="checkbox" name="neuigkeit_kurse[]" value="<?php echo esc_attr( (string) $kurs->ID ); ?>"
							<?php checked( $is_selected ); ?>>
						<span class="kb-kurs-info">
							<span class="kb-kurs-title"><?php echo esc_html( $kurs->post_title ); ?></span>
							<span class="kb-kurs-meta">
								<?php echo esc_html( $produktart ); ?>
								<?php if ( $preis ) : ?>
									| <?php echo esc_html( number_format( (float) $preis, 0, ',', '.' ) ); ?> EUR
								<?php endif; ?>
								<?php if ( $start_date ) : ?>
									| <?php echo esc_html( date_i18n( 'd.m.Y', strtotime( $start_date ) ) ); ?>
								<?php endif; ?>
							</span>
						</span>
					</label>
				<?php endforeach; ?>
			</div>
			<p class="description">
				<?php printf( esc_html__( '%d Kurse verfuegbar', 'kurs-booking' ), count( $kurse ) ); ?>
			</p>
		</div>

		<!-- Nach Kategorie -->
		<div class="kb-selection-panel" data-mode="kategorien">
			<p><strong><?php esc_html_e( 'Kategorien auswaehlen:', 'kurs-booking' ); ?></strong></p>
			<div class="kb-kategorie-list">
				<?php foreach ( $kategorien as $kat ) :
					$is_selected = in_array( (string) $kat->term_id, $selected_kategorien, true );
				?>
					<label class="<?php echo $is_selected ? 'selected' : ''; ?>">
						<input type="checkbox" name="neuigkeit_kategorien[]" value="<?php echo esc_attr( (string) $kat->term_id ); ?>"
							<?php checked( $is_selected ); ?> style="display: none;">
						<?php echo esc_html( $kat->name ); ?> (<?php echo esc_html( (string) $kat->count ); ?>)
					</label>
				<?php endforeach; ?>
			</div>
		</div>

		<!-- Nach Produktart -->
		<div class="kb-selection-panel" data-mode="produktarten">
			<p><strong><?php esc_html_e( 'Produktarten auswaehlen:', 'kurs-booking' ); ?></strong></p>
			<div class="kb-produktart-list">
				<?php foreach ( $produktarten as $key => $label ) :
					$is_selected = in_array( $key, $selected_produktarten, true );
				?>
					<label class="<?php echo $is_selected ? 'selected' : ''; ?>">
						<input type="checkbox" name="neuigkeit_produktarten[]" value="<?php echo esc_attr( $key ); ?>"
							<?php checked( $is_selected ); ?> style="display: none;">
						<?php echo esc_html( $label ); ?>
					</label>
				<?php endforeach; ?>
			</div>
		</div>

		<!-- Alle Kurse -->
		<div class="kb-selection-panel" data-mode="alle">
			<p>
				<span class="dashicons dashicons-info" style="color: #2271b1;"></span>
				<?php esc_html_e( 'Im Popup wird ein zufaelliger Kurs aus allen veroeffentlichten Kursen angezeigt.', 'kurs-booking' ); ?>
			</p>
		</div>

		<script>
		jQuery(function($) {
			// Selection mode toggle
			$('input[name="neuigkeit_selection_mode"]').on('change', function() {
				var mode = $(this).val();
				$('.kb-selection-panel').removeClass('active');
				$('.kb-selection-panel[data-mode="' + mode + '"]').addClass('active');
			}).filter(':checked').trigger('change');

			// Checkbox styling
			$('.kb-kurse-grid input, .kb-kategorie-list input, .kb-produktart-list input').on('change', function() {
				$(this).closest('label').toggleClass('selected', $(this).is(':checked'));
			});
		});
		</script>
		<?php
	}

	/**
	 * Render statistics meta box.
	 *
	 * @param WP_Post $post Current post object.
	 */
	public static function render_stats_meta_box( WP_Post $post ): void {
		$views    = get_post_meta( $post->ID, '_neuigkeit_views', true ) ?: 0;
		$clicks   = get_post_meta( $post->ID, '_neuigkeit_clicks', true ) ?: 0;
		$closures = get_post_meta( $post->ID, '_neuigkeit_closures', true ) ?: 0;
		?>
		<table class="widefat" style="border: none;">
			<tr>
				<td><strong><?php esc_html_e( 'Anzeigen:', 'kurs-booking' ); ?></strong></td>
				<td><?php echo esc_html( number_format( (float) $views, 0, ',', '.' ) ); ?></td>
			</tr>
			<tr>
				<td><strong><?php esc_html_e( 'Klicks:', 'kurs-booking' ); ?></strong></td>
				<td><?php echo esc_html( number_format( (float) $clicks, 0, ',', '.' ) ); ?></td>
			</tr>
			<tr>
				<td><strong><?php esc_html_e( 'Geschlossen:', 'kurs-booking' ); ?></strong></td>
				<td><?php echo esc_html( number_format( (float) $closures, 0, ',', '.' ) ); ?></td>
			</tr>
			<?php if ( $views > 0 ) : ?>
			<tr>
				<td><strong><?php esc_html_e( 'Klickrate:', 'kurs-booking' ); ?></strong></td>
				<td><?php echo esc_html( number_format( ( $clicks / $views ) * 100, 1, ',', '.' ) ); ?>%</td>
			</tr>
			<?php endif; ?>
		</table>
		<?php if ( $views > 0 ) : ?>
		<p style="margin-top: 10px;">
			<button type="button" class="button" onclick="if(confirm('<?php esc_attr_e( 'Statistiken zuruecksetzen?', 'kurs-booking' ); ?>')) { document.getElementById('reset_stats').value = '1'; }">
				<?php esc_html_e( 'Statistiken zuruecksetzen', 'kurs-booking' ); ?>
			</button>
			<input type="hidden" id="reset_stats" name="reset_stats" value="">
		</p>
		<?php endif; ?>
		<?php
	}

	/**
	 * Save meta box data.
	 *
	 * @param int     $post_id Post ID.
	 * @param WP_Post $post    Post object.
	 */
	public static function save_meta( int $post_id, WP_Post $post ): void {
		if ( ! isset( $_POST['kurs_neuigkeit_nonce'] ) ||
			 ! wp_verify_nonce( $_POST['kurs_neuigkeit_nonce'], 'kurs_neuigkeit_meta' ) ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Settings
		$show_popup = isset( $_POST['neuigkeit_show_popup'] ) ? '1' : '';
		update_post_meta( $post_id, '_neuigkeit_show_popup', $show_popup );

		$popup_start = sanitize_text_field( $_POST['neuigkeit_popup_start'] ?? '' );
		update_post_meta( $post_id, '_neuigkeit_popup_start', $popup_start );

		$popup_expires = sanitize_text_field( $_POST['neuigkeit_popup_expires'] ?? '' );
		update_post_meta( $post_id, '_neuigkeit_popup_expires', $popup_expires );

		$priority = absint( $_POST['neuigkeit_priority'] ?? 10 );
		update_post_meta( $post_id, '_neuigkeit_priority', (string) $priority );

		$cta_text = sanitize_text_field( $_POST['neuigkeit_cta_text'] ?? '' );
		update_post_meta( $post_id, '_neuigkeit_cta_text', $cta_text );

		$cta_url = esc_url_raw( $_POST['neuigkeit_cta_url'] ?? '' );
		update_post_meta( $post_id, '_neuigkeit_cta_url', $cta_url );

		// Selection mode
		$selection_mode = sanitize_key( $_POST['neuigkeit_selection_mode'] ?? 'kurse' );
		update_post_meta( $post_id, '_neuigkeit_selection_mode', $selection_mode );

		// Kurse
		$kurse = isset( $_POST['neuigkeit_kurse'] ) ? array_map( 'sanitize_text_field', (array) $_POST['neuigkeit_kurse'] ) : array();
		update_post_meta( $post_id, '_neuigkeit_kurse', $kurse );

		// Kategorien
		$kategorien = isset( $_POST['neuigkeit_kategorien'] ) ? array_map( 'sanitize_text_field', (array) $_POST['neuigkeit_kategorien'] ) : array();
		update_post_meta( $post_id, '_neuigkeit_kategorien', $kategorien );

		// Produktarten
		$produktarten = isset( $_POST['neuigkeit_produktarten'] ) ? array_map( 'sanitize_key', (array) $_POST['neuigkeit_produktarten'] ) : array();
		update_post_meta( $post_id, '_neuigkeit_produktarten', $produktarten );

		// Reset stats if requested
		if ( ! empty( $_POST['reset_stats'] ) ) {
			update_post_meta( $post_id, '_neuigkeit_views', 0 );
			update_post_meta( $post_id, '_neuigkeit_clicks', 0 );
			update_post_meta( $post_id, '_neuigkeit_closures', 0 );
		}
	}

	/**
	 * Add admin columns.
	 *
	 * @param array $columns Existing columns.
	 * @return array Modified columns.
	 */
	public static function add_admin_columns( array $columns ): array {
		$new_columns = array();
		foreach ( $columns as $key => $value ) {
			$new_columns[ $key ] = $value;
			if ( 'title' === $key ) {
				$new_columns['popup_status'] = __( 'Popup', 'kurs-booking' );
				$new_columns['kurse_count']  = __( 'Kurse', 'kurs-booking' );
				$new_columns['views']        = __( 'Views', 'kurs-booking' );
			}
		}
		return $new_columns;
	}

	/**
	 * Render admin column content.
	 *
	 * @param string $column  Column name.
	 * @param int    $post_id Post ID.
	 */
	public static function render_admin_column( string $column, int $post_id ): void {
		switch ( $column ) {
			case 'popup_status':
				$show      = get_post_meta( $post_id, '_neuigkeit_show_popup', true );
				$start     = get_post_meta( $post_id, '_neuigkeit_popup_start', true );
				$expires   = get_post_meta( $post_id, '_neuigkeit_popup_expires', true );
				$today     = current_time( 'Y-m-d' );
				$is_active = $show && ( ! $start || $start <= $today ) && ( ! $expires || $expires >= $today );

				if ( $is_active ) {
					echo '<span style="color: green;">&#9679; ' . esc_html__( 'Aktiv', 'kurs-booking' ) . '</span>';
				} elseif ( $show && $start > $today ) {
					echo '<span style="color: orange;">&#9679; ' . esc_html__( 'Geplant', 'kurs-booking' ) . '</span>';
				} elseif ( $show && $expires < $today ) {
					echo '<span style="color: gray;">&#9679; ' . esc_html__( 'Abgelaufen', 'kurs-booking' ) . '</span>';
				} else {
					echo '<span style="color: gray;">&#9675; ' . esc_html__( 'Inaktiv', 'kurs-booking' ) . '</span>';
				}
				break;

			case 'kurse_count':
				$mode = get_post_meta( $post_id, '_neuigkeit_selection_mode', true ) ?: 'kurse';
				$kurse = self::get_kurse_for_neuigkeit( $post_id );
				echo esc_html( count( $kurse ) ) . ' ' . esc_html__( 'Kurse', 'kurs-booking' );
				echo '<br><small style="color: #666;">';
				switch ( $mode ) {
					case 'alle':
						esc_html_e( '(Alle)', 'kurs-booking' );
						break;
					case 'kategorien':
						esc_html_e( '(Kategorien)', 'kurs-booking' );
						break;
					case 'produktarten':
						esc_html_e( '(Produktarten)', 'kurs-booking' );
						break;
					default:
						esc_html_e( '(Manuell)', 'kurs-booking' );
				}
				echo '</small>';
				break;

			case 'views':
				$views = get_post_meta( $post_id, '_neuigkeit_views', true ) ?: 0;
				echo esc_html( number_format( (float) $views, 0, ',', '.' ) );
				break;
		}
	}

	/**
	 * Get all kurse for a neuigkeit based on selection mode.
	 *
	 * @param int $neuigkeit_id Neuigkeit post ID.
	 * @return array Array of kurs post IDs.
	 */
	public static function get_kurse_for_neuigkeit( int $neuigkeit_id ): array {
		$mode = get_post_meta( $neuigkeit_id, '_neuigkeit_selection_mode', true ) ?: 'kurse';

		switch ( $mode ) {
			case 'alle':
				$posts = get_posts(
					array(
						'post_type'      => 'kurs',
						'posts_per_page' => -1,
						'post_status'    => 'publish',
						'fields'         => 'ids',
					)
				);
				return $posts;

			case 'kategorien':
				$kategorien = get_post_meta( $neuigkeit_id, '_neuigkeit_kategorien', true ) ?: array();
				if ( empty( $kategorien ) ) {
					return array();
				}
				$posts = get_posts(
					array(
						'post_type'      => 'kurs',
						'posts_per_page' => -1,
						'post_status'    => 'publish',
						'fields'         => 'ids',
						'tax_query'      => array(
							array(
								'taxonomy' => 'kurs_category',
								'field'    => 'term_id',
								'terms'    => $kategorien,
							),
						),
					)
				);
				return $posts;

			case 'produktarten':
				$produktarten = get_post_meta( $neuigkeit_id, '_neuigkeit_produktarten', true ) ?: array();
				if ( empty( $produktarten ) ) {
					return array();
				}
				$posts = get_posts(
					array(
						'post_type'      => 'kurs',
						'posts_per_page' => -1,
						'post_status'    => 'publish',
						'fields'         => 'ids',
						'meta_query'     => array(
							array(
								'key'     => '_produktart',
								'value'   => $produktarten,
								'compare' => 'IN',
							),
						),
					)
				);
				return $posts;

			case 'kurse':
			default:
				$kurse = get_post_meta( $neuigkeit_id, '_neuigkeit_kurse', true ) ?: array();
				return array_map( 'intval', $kurse );
		}
	}

	/**
	 * Get available produktarten from dienstleistungen or defaults.
	 *
	 * @return array Produktarten as key => label.
	 */
	private static function get_produktarten(): array {
		// Try to get from Dienstleistungen class
		if ( class_exists( 'Kurs_Booking_Dienstleistungen' ) ) {
			$dienstleistungen = Kurs_Booking_Dienstleistungen::get_all();
			if ( ! empty( $dienstleistungen ) ) {
				$result = array();
				foreach ( $dienstleistungen as $dl ) {
					$result[ $dl['key'] ] = $dl['key'] . ') ' . $dl['label'];
				}
				return $result;
			}
		}

		// Fallback to defaults
		return array(
			'A'  => 'A) Praesenz-Kurs',
			'B'  => 'B) Workshop',
			'C'  => 'C) Webinar',
			'D'  => 'D) Mental Coaching',
			'D1' => 'D1) Einzel-Coaching',
			'E'  => 'E) Video-Kurs',
			'F'  => 'F) Video-Paket',
			'G'  => 'G) Online Unterricht',
			'H'  => 'H) Video Unterricht',
			'I'  => 'I) Beratung',
		);
	}

	/**
	 * Render frontend popup.
	 */
	public static function render_frontend_popup(): void {
		// Don't show in admin
		if ( is_admin() ) {
			return;
		}

		// Check if popup module is enabled
		if ( class_exists( 'Kurs_Booking_Settings' ) &&
			 method_exists( 'Kurs_Booking_Settings', 'is_module_active' ) &&
			 ! Kurs_Booking_Settings::is_module_active( 'popup_neuigkeiten' ) ) {
			return;
		}

		$today = current_time( 'Y-m-d' );

		// Get active neuigkeiten
		$neuigkeiten = get_posts(
			array(
				'post_type'      => 'kurs-neuigkeit',
				'posts_per_page' => -1,
				'post_status'    => 'publish',
				'meta_query'     => array(
					'relation' => 'AND',
					array(
						'key'   => '_neuigkeit_show_popup',
						'value' => '1',
					),
					array(
						'relation' => 'OR',
						array(
							'key'     => '_neuigkeit_popup_start',
							'compare' => 'NOT EXISTS',
						),
						array(
							'key'     => '_neuigkeit_popup_start',
							'value'   => '',
							'compare' => '=',
						),
						array(
							'key'     => '_neuigkeit_popup_start',
							'value'   => $today,
							'compare' => '<=',
							'type'    => 'DATE',
						),
					),
					array(
						'relation' => 'OR',
						array(
							'key'     => '_neuigkeit_popup_expires',
							'compare' => 'NOT EXISTS',
						),
						array(
							'key'     => '_neuigkeit_popup_expires',
							'value'   => '',
							'compare' => '=',
						),
						array(
							'key'     => '_neuigkeit_popup_expires',
							'value'   => $today,
							'compare' => '>=',
							'type'    => 'DATE',
						),
					),
				),
				'orderby'        => 'meta_value_num',
				'meta_key'       => '_neuigkeit_priority',
				'order'          => 'ASC',
			)
		);

		if ( empty( $neuigkeiten ) ) {
			return;
		}

		// Pick random neuigkeit (weighted by priority)
		$neuigkeit = $neuigkeiten[ array_rand( $neuigkeiten ) ];

		// Check cookie
		$cookie_name = 'kb_news_' . $neuigkeit->ID;
		if ( isset( $_COOKIE[ $cookie_name ] ) ) {
			return;
		}

		// Get random kurs from selection
		$kurse = self::get_kurse_for_neuigkeit( $neuigkeit->ID );
		$random_kurs = null;
		$kurs_data = null;

		if ( ! empty( $kurse ) ) {
			$random_kurs_id = $kurse[ array_rand( $kurse ) ];
			$random_kurs = get_post( $random_kurs_id );
			if ( $random_kurs ) {
				$kurs_data = array(
					'title'      => $random_kurs->post_title,
					'url'        => get_permalink( $random_kurs->ID ),
					'preis'      => get_post_meta( $random_kurs->ID, '_preis', true ),
					'start_date' => get_post_meta( $random_kurs->ID, '_start_date', true ),
					'produktart' => get_post_meta( $random_kurs->ID, '_produktart', true ),
					'thumbnail'  => get_the_post_thumbnail_url( $random_kurs->ID, 'medium' ),
				);
			}
		}

		// Get CTA URL
		$cta_url = get_post_meta( $neuigkeit->ID, '_neuigkeit_cta_url', true );
		if ( empty( $cta_url ) && $kurs_data ) {
			$cta_url = $kurs_data['url'];
		}

		$cta_text = get_post_meta( $neuigkeit->ID, '_neuigkeit_cta_text', true ) ?: __( 'Mehr erfahren', 'kurs-booking' );

		// Track view
		$views = (int) get_post_meta( $neuigkeit->ID, '_neuigkeit_views', true );
		update_post_meta( $neuigkeit->ID, '_neuigkeit_views', $views + 1 );
		?>
		<div id="kb-news-popup" class="kb-news-popup" style="display: none;" data-neuigkeit-id="<?php echo esc_attr( (string) $neuigkeit->ID ); ?>">
			<div class="kb-news-popup__overlay"></div>
			<div class="kb-news-popup__content">
				<button type="button" class="kb-news-popup__close" aria-label="<?php esc_attr_e( 'Schliessen', 'kurs-booking' ); ?>">
					<span aria-hidden="true">&times;</span>
				</button>

				<?php if ( has_post_thumbnail( $neuigkeit->ID ) ) : ?>
					<div class="kb-news-popup__image">
						<?php echo get_the_post_thumbnail( $neuigkeit->ID, 'medium', array( 'class' => 'kb-news-popup__img' ) ); ?>
					</div>
				<?php elseif ( $kurs_data && $kurs_data['thumbnail'] ) : ?>
					<div class="kb-news-popup__image">
						<img src="<?php echo esc_url( $kurs_data['thumbnail'] ); ?>" alt="" class="kb-news-popup__img">
					</div>
				<?php endif; ?>

				<div class="kb-news-popup__body">
					<h3 class="kb-news-popup__title"><?php echo esc_html( $neuigkeit->post_title ); ?></h3>

					<?php if ( $neuigkeit->post_content ) : ?>
						<div class="kb-news-popup__text">
							<?php echo wp_kses_post( wpautop( $neuigkeit->post_content ) ); ?>
						</div>
					<?php endif; ?>

					<?php if ( $kurs_data ) : ?>
						<div class="kb-news-popup__kurs">
							<div class="kb-news-popup__kurs-title">
								<?php echo esc_html( $kurs_data['title'] ); ?>
							</div>
							<div class="kb-news-popup__kurs-meta">
								<?php if ( $kurs_data['start_date'] ) : ?>
									<span class="kb-news-popup__kurs-date">
										<span class="dashicons dashicons-calendar-alt"></span>
										<?php echo esc_html( date_i18n( 'd.m.Y', strtotime( $kurs_data['start_date'] ) ) ); ?>
									</span>
								<?php endif; ?>
								<?php if ( $kurs_data['preis'] ) : ?>
									<span class="kb-news-popup__kurs-price">
										ab <?php echo esc_html( number_format( (float) $kurs_data['preis'], 0, ',', '.' ) ); ?> EUR
									</span>
								<?php endif; ?>
							</div>
						</div>
					<?php endif; ?>

					<?php if ( $cta_url ) : ?>
						<div class="kb-news-popup__actions">
							<a href="<?php echo esc_url( $cta_url ); ?>" class="kb-news-popup__cta" data-action="click">
								<?php echo esc_html( $cta_text ); ?>
							</a>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>

		<script>
		(function() {
			var popup = document.getElementById('kb-news-popup');
			if (!popup) return;

			var neuigkeitId = popup.getAttribute('data-neuigkeit-id');
			var cookieName = 'kb_news_<?php echo esc_js( (string) $neuigkeit->ID ); ?>';
			<?php
			$modules = get_option( 'kurs_booking_modules', array() );
			$cookie_days = absint( $modules['popup_cookie_days'] ?? 1 );
			$popup_delay = absint( $modules['popup_delay'] ?? 3 );
		?>
			var cookieDays = <?php echo esc_js( (string) $cookie_days ); ?>;
			var delay = <?php echo esc_js( (string) $popup_delay ); ?> * 1000;

			// Show after delay
			setTimeout(function() {
				popup.style.display = 'flex';
				popup.classList.add('kb-news-popup--visible');
			}, delay);

			// Close handlers
			var closeBtn = popup.querySelector('.kb-news-popup__close');
			var overlay = popup.querySelector('.kb-news-popup__overlay');
			var ctaBtn = popup.querySelector('.kb-news-popup__cta');

			if (closeBtn) {
				closeBtn.addEventListener('click', function() {
					closePopup('close');
				});
			}

			if (overlay) {
				overlay.addEventListener('click', function() {
					closePopup('overlay');
				});
			}

			if (ctaBtn) {
				ctaBtn.addEventListener('click', function() {
					trackAction('click');
				});
			}

			// ESC key
			document.addEventListener('keydown', function(e) {
				if (e.key === 'Escape' && popup.style.display === 'flex') {
					closePopup('escape');
				}
			});

			function closePopup(method) {
				popup.classList.remove('kb-news-popup--visible');
				setTimeout(function() {
					popup.style.display = 'none';
				}, 300);
				setCookie(cookieName, '1', cookieDays);
				trackAction('close');
			}

			function trackAction(action) {
				// Track via AJAX if needed
				if (typeof jQuery !== 'undefined' && typeof kurs_booking_ajax !== 'undefined') {
					jQuery.post(kurs_booking_ajax.url, {
						action: 'kurs_track_popup',
						nonce: kurs_booking_ajax.nonce,
						neuigkeit_id: neuigkeitId,
						popup_action: action
					});
				}
			}

			function setCookie(name, value, days) {
				var expires = '';
				if (days) {
					var date = new Date();
					date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
					expires = '; expires=' + date.toUTCString();
				}
				document.cookie = name + '=' + value + expires + '; path=/; SameSite=Lax';
			}
		})();
		</script>
		<?php
	}

	/**
	 * Track popup action via AJAX.
	 */
	public static function ajax_track_popup(): void {
		check_ajax_referer( 'kurs_booking_nonce', 'nonce' );

		$neuigkeit_id = absint( $_POST['neuigkeit_id'] ?? 0 );
		$action       = sanitize_key( $_POST['popup_action'] ?? '' );

		if ( ! $neuigkeit_id ) {
			wp_send_json_error();
		}

		switch ( $action ) {
			case 'click':
				$clicks = (int) get_post_meta( $neuigkeit_id, '_neuigkeit_clicks', true );
				update_post_meta( $neuigkeit_id, '_neuigkeit_clicks', $clicks + 1 );
				break;

			case 'close':
				$closures = (int) get_post_meta( $neuigkeit_id, '_neuigkeit_closures', true );
				update_post_meta( $neuigkeit_id, '_neuigkeit_closures', $closures + 1 );
				break;
		}

		wp_send_json_success();
	}
}
