<?php
/**
 * Streaming-platform embed builder for the Video block.
 *
 * Recognised platforms (YouTube, Vimeo, Dailymotion) are turned into a player
 * <iframe> with the block's playback options applied as provider-specific query
 * params. Anything else falls back to WordPress core oEmbed, which already
 * supports a long list of popular providers (TikTok, Twitch, Facebook,
 * Wistia, SoundCloud, etc.).
 *
 * @package AxcelersBlocks
 */

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

if ( ! function_exists( 'axcelersblocks_video_parse_embed' ) ) {
	/**
	 * Build a player embed URL for a known streaming platform.
	 *
	 * @param string $url  Platform page URL.
	 * @param array  $opts Playback options: autoplay, muted, loop, controls, playsinline.
	 * @return array|null { provider, id, src } or null when unrecognised.
	 */
	function axcelersblocks_video_parse_embed( string $url, array $opts ): ?array {
		$autoplay    = ! empty( $opts['autoplay'] );
		$muted       = ! empty( $opts['muted'] ) || $autoplay;
		$loop        = ! empty( $opts['loop'] );
		$controls    = ! isset( $opts['controls'] ) || $opts['controls'];
		$playsinline = ! empty( $opts['playsinline'] );

		// ── YouTube ──────────────────────────────────────────────────────────
		if ( preg_match( '#(?:youtube\.com/(?:watch\?(?:.*&)?v=|embed/|shorts/|v/)|youtu\.be/)([A-Za-z0-9_-]{11})#i', $url, $m ) ) {
			$id   = $m[1];
			$args = [ 'rel' => '0', 'playsinline' => $playsinline ? '1' : '0' ];
			if ( $autoplay )      { $args['autoplay'] = '1'; }
			if ( $muted )         { $args['mute'] = '1'; }
			if ( ! $controls )    { $args['controls'] = '0'; }
			if ( $loop )          { $args['loop'] = '1'; $args['playlist'] = $id; }
			return [ 'provider' => 'youtube', 'id' => $id, 'src' => 'https://www.youtube.com/embed/' . $id . '?' . http_build_query( $args ) ];
		}

		// ── Vimeo ────────────────────────────────────────────────────────────
		if ( preg_match( '#vimeo\.com/(?:video/|channels/[A-Za-z0-9]+/|groups/[A-Za-z0-9]+/videos/|album/\d+/video/)?(\d+)#i', $url, $m ) ) {
			$id   = $m[1];
			$args = [ 'playsinline' => $playsinline ? '1' : '0' ];
			if ( $autoplay )   { $args['autoplay'] = '1'; }
			if ( $muted )      { $args['muted'] = '1'; }
			if ( $loop )       { $args['loop'] = '1'; }
			if ( ! $controls ) { $args['controls'] = '0'; }
			return [ 'provider' => 'vimeo', 'id' => $id, 'src' => 'https://player.vimeo.com/video/' . $id . '?' . http_build_query( $args ) ];
		}

		// ── Dailymotion ──────────────────────────────────────────────────────
		if ( preg_match( '#(?:dailymotion\.com/(?:video|embed/video)/|dai\.ly/)([A-Za-z0-9]+)#i', $url, $m ) ) {
			$id   = $m[1];
			$args = [];
			if ( $autoplay )   { $args['autoplay'] = '1'; }
			if ( $muted )      { $args['mute'] = '1'; }
			if ( ! $controls ) { $args['controls'] = '0'; }
			return [ 'provider' => 'dailymotion', 'id' => $id, 'src' => 'https://www.dailymotion.com/embed/video/' . $id . ( $args ? '?' . http_build_query( $args ) : '' ) ];
		}

		return null;
	}
}

if ( ! function_exists( 'axcelersblocks_video_build_embed' ) ) {
	/**
	 * Build the embed markup (iframe) for a platform URL.
	 *
	 * @param string $url   Platform page URL.
	 * @param array  $opts  Playback options.
	 * @param string $title Accessible iframe title.
	 * @return string Embed HTML, or '' when nothing could be resolved.
	 */
	function axcelersblocks_video_build_embed( string $url, array $opts, string $title = '' ): string {
		if ( '' === $url ) { return ''; }

		$parsed = axcelersblocks_video_parse_embed( $url, $opts );
		if ( $parsed ) {
			$allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share';
			return sprintf(
				'<iframe class="axcelersblocks-video__embed" src="%1$s" title="%2$s" frameborder="0" loading="lazy" allow="%3$s" allowfullscreen></iframe>',
				esc_url( $parsed['src'] ),
				esc_attr( $title !== '' ? $title : __( 'Embedded video', 'axcelersblocks' ) ),
				esc_attr( $allow )
			);
		}

		// Fallback: WordPress oEmbed handles the rest of the popular providers.
		$oembed = wp_oembed_get( $url );
		if ( $oembed ) {
			return '<div class="axcelersblocks-video__embed-oembed">' . $oembed . '</div>';
		}

		return '';
	}
}
