<?php
/**
 * Video section — self-hosted (media library) + external URLs.
 *
 * Extracted from VehicleDataMetaBox per QUALITY-IMPROVEMENT-PLAN.md §T2-2.
 *
 * @package ThemeREX\AutoDealer\Admin\MetaBoxes\Sections
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\MetaBoxes\Sections;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Admin\MetaBoxes\AbstractVehicleDataSection;
use ThemeREX\AutoDealer\Admin\VehicleMediaMetaBox;

final class VideoSection extends AbstractVehicleDataSection {

	public function getKey(): string {
		return 'video';
	}

	public function render( \WP_Post $post ): void {
		$selfVideos     = VehicleMediaMetaBox::getSelfVideos( $post->ID );
		$externalVideos = VehicleMediaMetaBox::getExternalVideos( $post->ID );
		?>
		<!-- Self-hosted -->
		<div class="trx-ad-video-section">
			<h4><?php esc_html_e( 'Self-Hosted Videos', 'trx-auto-dealer' ); ?></h4>
			<p class="description"><?php esc_html_e( 'Upload video files (MP4 recommended) from the media library.', 'trx-auto-dealer' ); ?></p>

			<div class="trx-ad-video-repeater" id="trx-ad-self-video-list">
				<?php foreach ( $selfVideos as $attachId ) : ?>
					<?php $filename = basename( (string) get_attached_file( $attachId ) ); ?>
					<?php
					if ( $filename === '' ) {
						continue; }
					?>
					<div class="trx-ad-video-row" data-id="<?php echo esc_attr( (string) $attachId ); ?>">
						<span class="dashicons dashicons-media-video"></span>
						<span class="trx-ad-video-filename"><?php echo esc_html( $filename ); ?></span>
						<button type="button" class="trx-ad-video-row-remove" title="<?php esc_attr_e( 'Remove', 'trx-auto-dealer' ); ?>">
							<span class="dashicons dashicons-no-alt"></span>
						</button>
					</div>
				<?php endforeach; ?>
			</div>

			<input type="hidden" name="trx_ad_videos_self" id="trx-ad-self-video-ids" value="<?php echo esc_attr( implode( ',', $selfVideos ) ); ?>">

			<button type="button" class="button" id="trx-ad-self-video-add" style="margin-top:8px;">
				<span class="dashicons dashicons-upload" style="vertical-align:middle;margin-top:-2px;"></span>
				<?php esc_html_e( 'Upload Video', 'trx-auto-dealer' ); ?>
			</button>
		</div>

		<hr style="margin:20px 0;">

		<!-- External -->
		<div class="trx-ad-video-section">
			<h4><?php esc_html_e( 'External Videos', 'trx-auto-dealer' ); ?></h4>
			<p class="description"><?php esc_html_e( 'Add YouTube, Vimeo, or any video URL. Preview is generated automatically.', 'trx-auto-dealer' ); ?></p>

			<div class="trx-ad-ext-video-repeater" id="trx-ad-ext-video-list">
				<?php foreach ( $externalVideos as $url ) : ?>
					<div class="trx-ad-ext-video-row">
						<div class="trx-ad-ext-video-input-row">
							<input type="url" name="trx_ad_videos_external[]" value="<?php echo esc_attr( $url ); ?>"
									class="widefat trx-ad-ext-video-url" placeholder="<?php esc_attr_e( 'https://www.youtube.com/watch?v=... or https://vimeo.com/...', 'trx-auto-dealer' ); ?>">
							<button type="button" class="trx-ad-ext-video-remove" title="<?php esc_attr_e( 'Remove', 'trx-auto-dealer' ); ?>">
								<span class="dashicons dashicons-no-alt"></span>
							</button>
						</div>
						<div class="trx-ad-video-embed-preview">
							<?php echo wp_kses( VehicleMediaMetaBox::renderVideoEmbed( $url ), \ThemeREX\AutoDealer\allowedHtml() ); ?>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<button type="button" class="button" id="trx-ad-ext-video-add" style="margin-top:8px;">
				<span class="dashicons dashicons-plus-alt2" style="vertical-align:middle;margin-top:-2px;"></span>
				<?php esc_html_e( 'Add Video URL', 'trx-auto-dealer' ); ?>
			</button>
		</div>
		<?php
	}

	public function save( int $postId ): void {
		// Re-verify the meta-box nonce here as well as in the VehicleDataMetaBox
		// dispatcher -- defense in depth, and each save path is independently
		// auditable (wp.org 2026-07 review round 2).
		if (
			! isset( $_POST['_trx_ad_vehicle_data_nonce'] )
			|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST['_trx_ad_vehicle_data_nonce'] ) ), 'trx_ad_vehicle_data_save' )
		) {
			return;
		}

		// Self-hosted.
		$rawVideoIds = isset( $_POST['trx_ad_videos_self'] )
			? sanitize_text_field( wp_unslash( (string) $_POST['trx_ad_videos_self'] ) )
			: '';

		if ( $rawVideoIds !== '' ) {
			$videoIds = array_filter( array_map( 'absint', explode( ',', $rawVideoIds ) ) );
			update_post_meta( $postId, VehicleMediaMetaBox::META_VIDEOS_SELF, wp_json_encode( array_values( $videoIds ) ) );
		} else {
			delete_post_meta( $postId, VehicleMediaMetaBox::META_VIDEOS_SELF );
		}

		// External. Sanitized at the read: unslash + esc_url_raw per entry,
		// non-array input degrades to an empty list.
		$rawUrls = isset( $_POST['trx_ad_videos_external'] ) && is_array( $_POST['trx_ad_videos_external'] )
			? array_map( 'esc_url_raw', wp_unslash( (array) $_POST['trx_ad_videos_external'] ) )
			: array();

		$urls = array();
		foreach ( $rawUrls as $url ) {
			$clean = esc_url_raw( (string) $url );
			if ( $clean !== '' ) {
				$urls[] = $clean;
			}
		}

		if ( ! empty( $urls ) ) {
			update_post_meta( $postId, VehicleMediaMetaBox::META_VIDEOS_EXTERNAL, wp_json_encode( $urls ) );
		} else {
			delete_post_meta( $postId, VehicleMediaMetaBox::META_VIDEOS_EXTERNAL );
		}
	}
}
