<?php
/**
 * Oembed
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Resets;

/**
 * Make video embeds responsive.
 *
 * @param string $html Current oEmbed markup.
 * @param object $data Data from the oEmbed provider.
 * @return string Optimized oEmbed markup.
 */
function oembed_html( string $html, $data ) : string {
	// Verify oembed data (as done in the oEmbed data2html code).
	if ( ! is_object( $data ) || empty( $data->type ) || is_admin() ) {
		return $html;
	}

	// Verify that it is a video.
	if ( 'video' !== $data->type ) {
		return $html;
	}

	// Calculate padding bottom percentage.
	$ratio = ( $data->height / $data->width ) * 100;

	// Strip width and height from html.
	$html = preg_replace( '/(width|height)="\d*"\s/', '', $html );

	// Return code.
	return '<div class="wysiwyg-video-embed" style="padding-bottom: ' . $ratio . '%;">' . $html . '</div>';
}
add_filter( 'oembed_dataparse', __NAMESPACE__ . '\oembed_html', 10, 2 );
