<?php
/**
 * Video Admin Page
 *
 * Admin interface for uploading and managing videos.
 * Supports drag & drop upload with progress tracking.
 *
 * @package KursBooking
 * @since   1.3.0
 */

declare(strict_types=1);

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

/**
 * Class Kurs_Booking_Video_Admin
 *
 * Handles the admin video upload page.
 */
class Kurs_Booking_Video_Admin {

	/**
	 * Page slug
	 */
	public const PAGE_SLUG = 'kurs-video-upload';

	/**
	 * Initialize the video admin
	 */
	public static function init(): void {
		add_action( 'admin_menu', array( __CLASS__, 'add_menu_page' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
	}

	/**
	 * Add admin menu page
	 */
	public static function add_menu_page(): void {
		add_submenu_page(
			'edit.php?post_type=kurs',
			__( 'Video hochladen', 'kurs-booking' ),
			__( 'Video hochladen', 'kurs-booking' ),
			'upload_kurs_videos',
			self::PAGE_SLUG,
			array( __CLASS__, 'render_page' )
		);
	}

	/**
	 * Enqueue admin assets
	 *
	 * @param string $hook_suffix Current admin page hook.
	 */
	public static function enqueue_assets( string $hook_suffix ): void {
		// Only on our page.
		if ( 'kurs_page_' . self::PAGE_SLUG !== $hook_suffix ) {
			return;
		}

		// Video upload JavaScript.
		wp_enqueue_script(
			'kurs-booking-video-upload',
			KURS_BOOKING_URL . 'assets/js/video-upload.js',
			array( 'jquery' ),
			KURS_BOOKING_VERSION,
			array(
				'strategy'  => 'defer',
				'in_footer' => true,
			)
		);

		// Localize script.
		wp_localize_script(
			'kurs-booking-video-upload',
			'kursVideoUpload',
			array(
				'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
				'nonce'         => wp_create_nonce( 'kurs_video_upload' ),
				'chunkSize'     => 5 * 1024 * 1024, // 5MB chunks.
				'maxFileSize'   => 2 * 1024 * 1024 * 1024, // 2GB.
				'allowedTypes'  => array( 'video/mp4', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska' ),
				'allowedExts'   => array( 'mp4', 'mov', 'avi', 'mkv' ),
				'i18n'          => array(
					'dropzone'         => __( 'Video hierher ziehen oder klicken zum Auswaehlen', 'kurs-booking' ),
					'uploading'        => __( 'Wird hochgeladen...', 'kurs-booking' ),
					'processing'       => __( 'Wird verarbeitet...', 'kurs-booking' ),
					'complete'         => __( 'Fertig!', 'kurs-booking' ),
					'error'            => __( 'Fehler', 'kurs-booking' ),
					'invalidType'      => __( 'Ungültiger Dateityp. Erlaubt: MP4, MOV, AVI, MKV', 'kurs-booking' ),
					'fileTooLarge'     => __( 'Datei zu groß. Maximum: 2GB', 'kurs-booking' ),
					'selectKurs'       => __( 'Bitte wählen Sie einen Kurs aus', 'kurs-booking' ),
					'uploadAnother'    => __( 'Weiteres Video hochladen', 'kurs-booking' ),
					'cancel'           => __( 'Abbrechen', 'kurs-booking' ),
					'retry'            => __( 'Erneut versuchen', 'kurs-booking' ),
					'connectionError'  => __( 'Verbindungsfehler. Bitte prüfen Sie Ihre Internetverbindung.', 'kurs-booking' ),
					'serverError'      => __( 'Serverfehler. Bitte versuchen Sie es später erneut.', 'kurs-booking' ),
				),
			)
		);

		// Video admin CSS.
		wp_enqueue_style(
			'kurs-booking-video-admin',
			KURS_BOOKING_URL . 'assets/css/video-admin.css',
			array(),
			KURS_BOOKING_VERSION
		);
	}

	/**
	 * Render admin page
	 */
	public static function render_page(): void {
		// Check permission.
		if ( ! current_user_can( 'upload_kurs_videos' ) ) {
			wp_die( esc_html__( 'Sie haben keine Berechtigung für diese Seite.', 'kurs-booking' ) );
		}

		// Check if video service is configured.
		$service_configured = Kurs_Booking_Video_Service::is_configured();

		// Get available kurse for dropdown.
		$kurse = self::get_available_kurse();

		// Get recent uploads.
		$recent_videos = self::get_recent_videos( 10 );

		?>
		<div class="wrap kb-video-admin">
			<h1 class="wp-heading-inline">
				<span class="dashicons dashicons-video-alt3"></span>
				<?php esc_html_e( 'Video hochladen', 'kurs-booking' ); ?>
			</h1>
			<hr class="wp-header-end">

			<?php if ( ! $service_configured ) : ?>
				<div class="notice notice-error">
					<p>
						<strong><?php esc_html_e( 'Video-Service nicht konfiguriert', 'kurs-booking' ); ?></strong><br>
						<?php esc_html_e( 'Bitte konfigurieren Sie die Video-Service API in den Einstellungen.', 'kurs-booking' ); ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=kurs-booking-settings&tab=video' ) ); ?>">
							<?php esc_html_e( 'Zu den Einstellungen', 'kurs-booking' ); ?>
						</a>
					</p>
				</div>
			<?php else : ?>

				<div class="kb-video-upload-container">
					<!-- Upload Form -->
					<div class="kb-video-upload-form">
						<h2><?php esc_html_e( 'Neues Video hochladen', 'kurs-booking' ); ?></h2>

						<!-- Kurs Selection -->
						<div class="kb-form-row">
							<label for="kb-video-kurs"><?php esc_html_e( 'Kurs zuordnen', 'kurs-booking' ); ?></label>
							<select id="kb-video-kurs" class="kb-select">
								<option value=""><?php esc_html_e( '-- Kurs auswählen (optional) --', 'kurs-booking' ); ?></option>
								<?php foreach ( $kurse as $kurs ) : ?>
									<option value="<?php echo esc_attr( (string) $kurs->ID ); ?>">
										<?php echo esc_html( $kurs->post_title ); ?>
										<?php
										$date = get_post_meta( $kurs->ID, '_kurs_start_date', true );
										if ( $date ) {
											echo ' (' . esc_html( wp_date( 'd.m.Y', strtotime( $date ) ) ) . ')';
										}
										?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="description">
								<?php esc_html_e( 'Optional: Video direkt einem Kurs zuordnen.', 'kurs-booking' ); ?>
							</p>
						</div>

						<!-- Video Title -->
						<div class="kb-form-row">
							<label for="kb-video-title"><?php esc_html_e( 'Video-Titel', 'kurs-booking' ); ?></label>
							<input type="text" id="kb-video-title" class="kb-input" placeholder="<?php esc_attr_e( 'Wird aus Dateiname generiert', 'kurs-booking' ); ?>">
							<p class="description">
								<?php esc_html_e( 'Optional: Leer lassen für automatischen Titel aus Dateiname.', 'kurs-booking' ); ?>
							</p>
						</div>

						<!-- Dropzone -->
						<div class="kb-dropzone" id="kb-dropzone">
							<div class="kb-dropzone-content">
								<span class="dashicons dashicons-cloud-upload"></span>
								<p class="kb-dropzone-text"><?php esc_html_e( 'Video hierher ziehen', 'kurs-booking' ); ?></p>
								<p class="kb-dropzone-subtext"><?php esc_html_e( 'oder klicken zum Auswählen', 'kurs-booking' ); ?></p>
								<p class="kb-dropzone-formats"><?php esc_html_e( 'MP4, MOV, AVI, MKV (max. 2GB)', 'kurs-booking' ); ?></p>
							</div>
							<input type="file" id="kb-video-file" accept="video/mp4,video/quicktime,video/x-msvideo,video/x-matroska,.mp4,.mov,.avi,.mkv" hidden>
						</div>

						<!-- Progress -->
						<div class="kb-upload-progress" id="kb-upload-progress" style="display: none;">
							<div class="kb-progress-info">
								<span class="kb-progress-filename" id="kb-progress-filename"></span>
								<span class="kb-progress-percent" id="kb-progress-percent">0%</span>
							</div>
							<div class="kb-progress-bar">
								<div class="kb-progress-fill" id="kb-progress-fill" style="width: 0;"></div>
							</div>
							<div class="kb-progress-status" id="kb-progress-status">
								<?php esc_html_e( 'Wird hochgeladen...', 'kurs-booking' ); ?>
							</div>
							<button type="button" class="button kb-cancel-btn" id="kb-cancel-upload">
								<?php esc_html_e( 'Abbrechen', 'kurs-booking' ); ?>
							</button>
						</div>

						<!-- Success Message -->
						<div class="kb-upload-success" id="kb-upload-success" style="display: none;">
							<span class="dashicons dashicons-yes-alt"></span>
							<p><?php esc_html_e( 'Video erfolgreich hochgeladen!', 'kurs-booking' ); ?></p>
							<p class="kb-success-note"><?php esc_html_e( 'Das Video wird jetzt verarbeitet. Dies kann einige Minuten dauern.', 'kurs-booking' ); ?></p>
							<div class="kb-success-actions">
								<a href="#" class="button button-primary" id="kb-view-video"><?php esc_html_e( 'Video ansehen', 'kurs-booking' ); ?></a>
								<button type="button" class="button" id="kb-upload-another"><?php esc_html_e( 'Weiteres Video', 'kurs-booking' ); ?></button>
							</div>
						</div>

						<!-- Error Message -->
						<div class="kb-upload-error" id="kb-upload-error" style="display: none;">
							<span class="dashicons dashicons-warning"></span>
							<p id="kb-error-message"></p>
							<button type="button" class="button" id="kb-retry-upload"><?php esc_html_e( 'Erneut versuchen', 'kurs-booking' ); ?></button>
						</div>
					</div>

					<!-- Recent Uploads -->
					<div class="kb-recent-uploads">
						<h2><?php esc_html_e( 'Letzte Uploads', 'kurs-booking' ); ?></h2>

						<?php if ( empty( $recent_videos ) ) : ?>
							<p class="kb-no-videos"><?php esc_html_e( 'Noch keine Videos hochgeladen.', 'kurs-booking' ); ?></p>
						<?php else : ?>
							<div class="kb-video-list" id="kb-video-list">
								<?php foreach ( $recent_videos as $video ) : ?>
									<?php echo wp_kses_post( self::render_video_item( $video ) ); ?>
								<?php endforeach; ?>
							</div>
						<?php endif; ?>

						<p class="kb-all-videos-link">
							<a href="<?php echo esc_url( admin_url( 'edit.php?post_type=kurs-video' ) ); ?>">
								<?php esc_html_e( 'Alle Videos anzeigen', 'kurs-booking' ); ?> &rarr;
							</a>
						</p>
					</div>
				</div>

			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Get available kurse for the current user.
	 *
	 * @return array<int, WP_Post> Array of WP_Post objects.
	 */
	private static function get_available_kurse(): array {
		$args = array(
			'post_type'      => 'kurs',
			'posts_per_page' => -1,
			'orderby'        => 'meta_value',
			'meta_key'       => '_kurs_start_date',
			'order'          => 'DESC',
			'post_status'    => array( 'publish', 'draft', 'private' ),
		);

		// If user is not admin, only show their own kurse.
		if ( ! current_user_can( 'manage_kurs_videos' ) ) {
			$args['author'] = get_current_user_id();
		}

		return get_posts( $args );
	}

	/**
	 * Get recent video uploads.
	 *
	 * @param int $limit Number of videos to retrieve.
	 * @return array<int, WP_Post> Array of WP_Post objects.
	 */
	private static function get_recent_videos( int $limit = 10 ): array {
		$args = array(
			'post_type'      => Kurs_Booking_Video::POST_TYPE,
			'posts_per_page' => $limit,
			'orderby'        => 'date',
			'order'          => 'DESC',
			'post_status'    => 'any',
		);

		// If user is not admin, filter by their uploads.
		if ( ! current_user_can( 'manage_kurs_videos' ) ) {
			$args['author'] = get_current_user_id();
		}

		return get_posts( $args );
	}

	/**
	 * Render a single video item for the list
	 *
	 * @param WP_Post $video Video post object.
	 * @return string HTML output.
	 */
	private static function render_video_item( WP_Post $video ): string {
		$status        = get_post_meta( $video->ID, '_video_status', true ) ?: Kurs_Booking_Video::STATUS_DRAFT;
		$duration      = (int) get_post_meta( $video->ID, '_video_duration', true );
		$thumbnail_url = get_post_meta( $video->ID, '_video_thumbnail_url', true );
		$edit_url      = get_edit_post_link( $video->ID );

		ob_start();
		?>
		<div class="kb-video-item" data-video-id="<?php echo esc_attr( (string) $video->ID ); ?>">
			<div class="kb-video-thumb">
				<?php if ( $thumbnail_url ) : ?>
					<img src="<?php echo esc_url( $thumbnail_url ); ?>" alt="">
				<?php else : ?>
					<span class="dashicons dashicons-video-alt3"></span>
				<?php endif; ?>
			</div>
			<div class="kb-video-info">
				<a href="<?php echo esc_url( (string) $edit_url ); ?>" class="kb-video-title">
					<?php echo esc_html( $video->post_title ); ?>
				</a>
				<div class="kb-video-meta">
					<?php echo wp_kses_post( Kurs_Booking_Video::get_status_badge( $status ) ); ?>
					<?php if ( $duration > 0 ) : ?>
						<span class="kb-video-duration"><?php echo esc_html( Kurs_Booking_Video::format_duration( $duration ) ); ?></span>
					<?php endif; ?>
					<span class="kb-video-date"><?php echo esc_html( get_the_date( 'd.m.Y H:i', $video ) ); ?></span>
				</div>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}
}
