<?php
/**
 * Vehicle media data accessors — gallery image IDs, self-hosted + external videos.
 *
 * The live admin UI for these fields is rendered inside `VehicleDataMetaBox`
 * via `MetaBoxes\Sections\GallerySection` and `MetaBoxes\Sections\VideoSection`,
 * which read/write the same meta keys defined here. This class is the shared
 * read surface used by those sections plus `Frontend\MediaSliderRenderer`.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin;

defined( 'ABSPATH' ) || exit;

class VehicleMediaMetaBox {

	/**
	 * Post meta key for gallery image IDs (JSON array).
	 */
	public const META_GALLERY = '_trx_ad_gallery';

	/**
	 * Post meta key for self-hosted video attachment IDs (JSON array).
	 */
	public const META_VIDEOS_SELF = '_trx_ad_videos_self';

	/**
	 * Post meta key for external video URLs (JSON array).
	 */
	public const META_VIDEOS_EXTERNAL = '_trx_ad_videos_external';

	/**
	 * Get gallery attachment IDs for a vehicle.
	 *
	 * @param int $postId Post ID.
	 * @return int[]
	 */
	public static function getGalleryIds( int $postId ): array {
		return self::decodeIntArray( get_post_meta( $postId, self::META_GALLERY, true ) );
	}

	/**
	 * Get self-hosted video attachment IDs for a vehicle.
	 *
	 * @param int $postId Post ID.
	 * @return int[]
	 */
	public static function getSelfVideos( int $postId ): array {
		return self::decodeIntArray( get_post_meta( $postId, self::META_VIDEOS_SELF, true ) );
	}

	/**
	 * Get external video URLs for a vehicle.
	 *
	 * @param int $postId Post ID.
	 * @return string[]
	 */
	public static function getExternalVideos( int $postId ): array {
		$raw = get_post_meta( $postId, self::META_VIDEOS_EXTERNAL, true );

		if ( empty( $raw ) || ! is_string( $raw ) ) {
			return array();
		}

		$decoded = json_decode( $raw, true );

		return is_array( $decoded ) ? array_filter( array_map( 'strval', $decoded ) ) : array();
	}

	/**
	 * Render embed iframe for a video URL (YouTube, Vimeo, or generic).
	 *
	 * @param string $url Video URL.
	 * @return string HTML iframe or empty string.
	 */
	public static function renderVideoEmbed( string $url ): string {
		if ( $url === '' ) {
			return '';
		}

		// YouTube.
		if ( preg_match( '/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $url, $m ) ) {
			return sprintf(
				'<iframe width="360" height="203" src="https://www.youtube.com/embed/%s" frameborder="0" allowfullscreen loading="lazy"></iframe>',
				esc_attr( $m[1] )
			);
		}

		// Vimeo.
		if ( preg_match( '/vimeo\.com\/(?:video\/)?(\d+)/', $url, $m ) ) {
			return sprintf(
				'<iframe width="360" height="203" src="https://player.vimeo.com/video/%s" frameborder="0" allowfullscreen loading="lazy"></iframe>',
				esc_attr( $m[1] )
			);
		}

		// Fallback: show link.
		return sprintf(
			'<a href="%s" target="_blank" rel="noopener">%s</a>',
			esc_url( $url ),
			esc_html( $url )
		);
	}

	/**
	 * Decode a JSON-encoded array of integers from post meta.
	 *
	 * @param mixed $raw Raw meta value.
	 * @return int[]
	 */
	private static function decodeIntArray( mixed $raw ): array {
		if ( empty( $raw ) || ! is_string( $raw ) ) {
			return array();
		}

		$decoded = json_decode( $raw, true );

		return is_array( $decoded ) ? array_filter( array_map( 'absint', $decoded ) ) : array();
	}
}
