<?php
/**
 * Video Player Shortcode
 *
 * Renders a Video.js player for HLS streaming with JWT authentication.
 *
 * Usage:
 *   [kurs_video buchung_id="123"]
 *   [kurs_video buchung_id="123" video_id="5"]
 *
 * @package KursBooking
 * @since   1.2.0
 */

declare(strict_types=1);

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

/**
 * Register the video player shortcode
 */
function kurs_booking_register_video_shortcode(): void {
	add_shortcode( 'kurs_video', 'kurs_booking_render_video_player' );
}
add_action( 'init', 'kurs_booking_register_video_shortcode' );

/**
 * Render the video player.
 *
 * @param array<string, mixed>|string $atts Shortcode attributes.
 * @return string HTML output.
 */
function kurs_booking_render_video_player( array|string $atts ): string {
	$atts = shortcode_atts(
		array(
			'buchung_id' => 0,
			'video_id'   => 0, // Optional: specific video post ID.
			'autoplay'   => false,
			'muted'      => false,
		),
		$atts,
		'kurs_video'
	);

	$buchung_id = absint( $atts['buchung_id'] );
	$video_id   = absint( $atts['video_id'] );

	// Validate buchung_id.
	if ( 0 === $buchung_id ) {
		return kurs_booking_video_error( __( 'Keine Buchungs-ID angegeben.', 'kurs-booking' ) );
	}

	// Get buchung.
	$buchung = get_post( $buchung_id );
	if ( ! $buchung || 'kurs-buchung' !== $buchung->post_type ) {
		return kurs_booking_video_error( __( 'Buchung nicht gefunden.', 'kurs-booking' ) );
	}

	// Check buchung status.
	$status = get_post_meta( $buchung_id, '_buchung_status', true );
	if ( 'confirmed' !== $status ) {
		return kurs_booking_video_error( __( 'Diese Buchung wurde noch nicht bestaetigt.', 'kurs-booking' ) );
	}

	// Check payment status (if sevDesk is enabled).
	// TODO: Implement payment check via sevDesk invoice status.

	// Get kurs.
	$kurs_id = (int) get_post_meta( $buchung_id, '_buchung_kurs_id', true );
	if ( ! $kurs_id ) {
		return kurs_booking_video_error( __( 'Kein Kurs zugeordnet.', 'kurs-booking' ) );
	}

	// Get videos for this kurs.
	$video_ids = Kurs_Booking_Video::get_kurs_video_ids( $kurs_id );
	if ( empty( $video_ids ) ) {
		return kurs_booking_video_error( __( 'Keine Videos fuer diesen Kurs verfuegbar.', 'kurs-booking' ) );
	}

	// If specific video requested, validate it.
	if ( $video_id > 0 ) {
		if ( ! in_array( $video_id, $video_ids, true ) ) {
			return kurs_booking_video_error( __( 'Das angeforderte Video gehoert nicht zu diesem Kurs.', 'kurs-booking' ) );
		}
		$video_ids = array( $video_id );
	}

	// Get first video (or all for playlist).
	$first_video_id = $video_ids[0];
	$video_post     = get_post( $first_video_id );

	if ( ! $video_post ) {
		return kurs_booking_video_error( __( 'Video nicht gefunden.', 'kurs-booking' ) );
	}

	// Check video status.
	$video_status = get_post_meta( $first_video_id, '_video_status', true );
	if ( Kurs_Booking_Video::STATUS_READY !== $video_status ) {
		return kurs_booking_video_info( __( 'Das Video wird noch verarbeitet. Bitte versuchen Sie es spaeter erneut.', 'kurs-booking' ) );
	}

	// Get external video ID for streaming token.
	$external_id = get_post_meta( $first_video_id, '_video_external_id', true );
	if ( empty( $external_id ) ) {
		return kurs_booking_video_error( __( 'Video-Service Fehler: Externe ID fehlt.', 'kurs-booking' ) );
	}

	// Get stream token from video service.
	$token_response = Kurs_Booking_Video_Service::get_stream_token( $external_id, $buchung_id );

	if ( is_wp_error( $token_response ) ) {
		return kurs_booking_video_error(
			sprintf(
				/* translators: %s: Error message */
				__( 'Streaming-Token konnte nicht abgerufen werden: %s', 'kurs-booking' ),
				$token_response->get_error_message()
			)
		);
	}

	$stream_url  = $token_response['stream_url'] ?? '';
	$thumbnail   = get_post_meta( $first_video_id, '_video_thumbnail_url', true );
	$duration    = (int) get_post_meta( $first_video_id, '_video_duration', true );
	$video_title = $video_post->post_title;

	// Enqueue Video.js.
	kurs_booking_enqueue_videojs();

	// Build unique player ID.
	$player_id = 'kurs-video-' . $first_video_id . '-' . wp_rand( 1000, 9999 );

	// Build attributes.
	$autoplay = filter_var( $atts['autoplay'], FILTER_VALIDATE_BOOLEAN );
	$muted    = filter_var( $atts['muted'], FILTER_VALIDATE_BOOLEAN );

	ob_start();
	?>
	<div class="kurs-video-player-container">
		<video
			id="<?php echo esc_attr( $player_id ); ?>"
			class="video-js vjs-big-play-centered vjs-theme-kurs"
			controls
			preload="auto"
			width="100%"
			<?php echo $autoplay ? 'autoplay' : ''; ?>
			<?php echo $muted ? 'muted' : ''; ?>
			<?php if ( $thumbnail ) : ?>
				poster="<?php echo esc_url( $thumbnail ); ?>"
			<?php endif; ?>
			data-setup='{}'
		>
			<source src="<?php echo esc_url( $stream_url ); ?>" type="application/x-mpegURL">
			<p class="vjs-no-js">
				<?php esc_html_e( 'Um dieses Video anzusehen, aktivieren Sie bitte JavaScript und erwaegen Sie ein Upgrade auf einen Webbrowser, der HTML5-Video unterstuetzt.', 'kurs-booking' ); ?>
			</p>
		</video>

		<div class="kurs-video-info">
			<h3 class="kurs-video-title"><?php echo esc_html( $video_title ); ?></h3>
			<?php if ( $duration > 0 ) : ?>
				<span class="kurs-video-duration">
					<?php echo esc_html( Kurs_Booking_Video::format_duration( $duration ) ); ?>
				</span>
			<?php endif; ?>
		</div>

		<?php if ( count( $video_ids ) > 1 ) : ?>
			<div class="kurs-video-playlist">
				<h4><?php esc_html_e( 'Weitere Videos', 'kurs-booking' ); ?></h4>
				<ul>
					<?php foreach ( $video_ids as $vid ) : ?>
						<?php
						$v = get_post( $vid );
						if ( ! $v ) {
							continue;
						}
						$v_thumb    = get_post_meta( $vid, '_video_thumbnail_url', true );
						$v_duration = (int) get_post_meta( $vid, '_video_duration', true );
						$v_status   = get_post_meta( $vid, '_video_status', true );
						$is_current = $vid === $first_video_id;
						?>
						<li class="<?php echo $is_current ? 'current' : ''; ?> <?php echo Kurs_Booking_Video::STATUS_READY !== $v_status ? 'not-ready' : ''; ?>">
							<?php if ( Kurs_Booking_Video::STATUS_READY === $v_status && ! $is_current ) : ?>
								<a href="?buchung=<?php echo esc_attr( (string) $buchung_id ); ?>&video=<?php echo esc_attr( (string) $vid ); ?>">
							<?php endif; ?>
								<?php if ( $v_thumb ) : ?>
									<img src="<?php echo esc_url( $v_thumb ); ?>" alt="" class="playlist-thumb">
								<?php endif; ?>
								<span class="playlist-title"><?php echo esc_html( $v->post_title ); ?></span>
								<?php if ( $v_duration > 0 ) : ?>
									<span class="playlist-duration"><?php echo esc_html( Kurs_Booking_Video::format_duration( $v_duration ) ); ?></span>
								<?php endif; ?>
							<?php if ( Kurs_Booking_Video::STATUS_READY === $v_status && ! $is_current ) : ?>
								</a>
							<?php endif; ?>
						</li>
					<?php endforeach; ?>
				</ul>
			</div>
		<?php endif; ?>
	</div>

	<script>
	(function() {
		// Initialize video player - runs immediately for AJAX-loaded content.
		function initPlayer() {
			if (typeof videojs === 'undefined') {
				// Video.js not loaded yet, wait and retry.
				setTimeout(initPlayer, 100);
				return;
			}

			var player = videojs('<?php echo esc_js( $player_id ); ?>', {
				html5: {
					vhs: {
						overrideNative: true
					}
				},
				playbackRates: [0.5, 1, 1.25, 1.5, 2],
				controlBar: {
					children: [
						'playToggle',
						'volumePanel',
						'currentTimeDisplay',
						'timeDivider',
						'durationDisplay',
						'progressControl',
						'playbackRateMenuButton',
						'fullscreenToggle'
					]
				}
			});

			// Disable right-click on video.
			player.el().addEventListener('contextmenu', function(e) {
				e.preventDefault();
				return false;
			});

			// Track first play.
			player.one('play', function() {
				console.log('Video started: <?php echo esc_js( $video_title ); ?>');
			});
		}

		// Run immediately - DOM is already ready for AJAX-loaded content.
		initPlayer();
	})();
	</script>

	<style>
	.kurs-video-player-container {
		max-width: 100%;
		margin: 20px 0;
	}
	.kurs-video-player-container .video-js {
		width: 100%;
		aspect-ratio: 16/9;
		border-radius: 8px;
		overflow: hidden;
	}
	.kurs-video-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 0;
	}
	.kurs-video-title {
		margin: 0;
		font-size: 1.2em;
	}
	.kurs-video-duration {
		color: #666;
		font-size: 0.9em;
	}
	.kurs-video-playlist {
		margin-top: 20px;
		padding: 15px;
		background: #f5f5f5;
		border-radius: 8px;
	}
	.kurs-video-playlist h4 {
		margin: 0 0 10px 0;
	}
	.kurs-video-playlist ul {
		list-style: none;
		margin: 0;
		padding: 0;
	}
	.kurs-video-playlist li {
		display: flex;
		align-items: center;
		gap: 10px;
		padding: 8px;
		border-radius: 4px;
		margin-bottom: 5px;
	}
	.kurs-video-playlist li.current {
		background: #e0e0e0;
		font-weight: bold;
	}
	.kurs-video-playlist li.not-ready {
		opacity: 0.5;
	}
	.kurs-video-playlist li a {
		display: flex;
		align-items: center;
		gap: 10px;
		text-decoration: none;
		color: inherit;
		flex: 1;
	}
	.kurs-video-playlist li a:hover {
		background: #e8e8e8;
	}
	.playlist-thumb {
		width: 80px;
		height: 45px;
		object-fit: cover;
		border-radius: 4px;
	}
	.playlist-duration {
		margin-left: auto;
		color: #666;
		font-size: 0.85em;
	}
	</style>
	<?php
	return ob_get_clean();
}

/**
 * Display error message
 *
 * @param string $message Error message.
 * @return string HTML output.
 */
function kurs_booking_video_error( string $message ): string {
	return sprintf(
		'<div class="kurs-video-error" style="padding: 20px; background: #ffe5e5; border-left: 4px solid #d63638; border-radius: 4px; margin: 20px 0;">
			<p style="margin: 0; color: #d63638;"><strong>%s</strong> %s</p>
		</div>',
		esc_html__( 'Fehler:', 'kurs-booking' ),
		esc_html( $message )
	);
}

/**
 * Display info message
 *
 * @param string $message Info message.
 * @return string HTML output.
 */
function kurs_booking_video_info( string $message ): string {
	return sprintf(
		'<div class="kurs-video-info-box" style="padding: 20px; background: #fff8e5; border-left: 4px solid #996800; border-radius: 4px; margin: 20px 0;">
			<p style="margin: 0; color: #996800;"><strong>%s</strong> %s</p>
		</div>',
		esc_html__( 'Hinweis:', 'kurs-booking' ),
		esc_html( $message )
	);
}

/**
 * Enqueue Video.js library
 */
function kurs_booking_enqueue_videojs(): void {
	// Video.js CSS.
	wp_enqueue_style(
		'video-js',
		'https://vjs.zencdn.net/8.10.0/video-js.css',
		array(),
		'8.10.0'
	);

	// Video.js Core.
	wp_enqueue_script(
		'video-js',
		'https://vjs.zencdn.net/8.10.0/video.min.js',
		array(),
		'8.10.0',
		true
	);

	// Quality selector plugin for quality switching (no CSS needed).
	wp_enqueue_script(
		'videojs-quality-levels',
		'https://cdn.jsdelivr.net/npm/videojs-contrib-quality-levels@4.0.0/dist/videojs-contrib-quality-levels.min.js',
		array( 'video-js' ),
		'4.0.0',
		true
	);

	wp_enqueue_script(
		'videojs-hls-quality-selector',
		'https://cdn.jsdelivr.net/npm/videojs-hls-quality-selector@2.0.0/dist/videojs-hls-quality-selector.min.js',
		array( 'video-js', 'videojs-quality-levels' ),
		'2.0.0',
		true
	);
}
