<?php
/**
 * Frontend oEmbed Improvements
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Frontend;

use SEOvaultSEO\Core\Options;
use SEOvaultSEO\Utils\Formatter;

/**
 * Alters oEmbed response data using SEOvault metadata.
 */
class OEmbed {

	/**
	 * Initialize oEmbed filter.
	 */
	public static function init() {
		if ( ! \SEOvaultSEO\Compatibility\Detector::should_output_seo() ) {
			return;
		}

		add_filter( 'oembed_response_data', array( __CLASS__, 'alter_response_data' ), 10, 2 );
	}

	/**
	 * Alter oEmbed response data.
	 *
	 * @hook oembed_response_data 10
	 *
	 * @param array    $data The response data.
	 * @param \WP_Post $post The post object.
	 * @return array Possibly altered $data.
	 */
	public static function alter_response_data( $data, $post ) {

		if ( Options::is_oembed_use_seo_title() ) {
			$title = (
				Options::is_og_enabled()
					? Formatter::get_effective_social_title( $post->ID )
					: Formatter::get_effective_title( $post->ID )
			);

			if ( ! empty( $title ) ) {
				$data['title'] = $title;
			}
		}

		if ( Options::is_oembed_use_social_image() ) {
			$image_details = false;

			$thumbnail_id = (int) get_post_thumbnail_id( $post->ID );
			if ( $thumbnail_id ) {
				$image_details = wp_get_attachment_image_src( $thumbnail_id, 'full' );
			}

			if ( ! $image_details ) {
				$image_url = Formatter::get_effective_og_image( $post->ID );

				if ( ! empty( $image_url ) ) {
					$attachment_id = attachment_url_to_postid( $image_url );

					if ( $attachment_id ) {
						$image_details = wp_get_attachment_image_src( $attachment_id, 'full' );
					}
				}
			}

			if ( $image_details && $image_details[0] && $image_details[1] && $image_details[2] ) {
				$data['thumbnail_url']    = $image_details[0];
				$data['thumbnail_width']  = $image_details[1];
				$data['thumbnail_height'] = $image_details[2];
			}
		}

		if ( Options::is_oembed_remove_author() ) {
			unset( $data['author_url'], $data['author_name'] );
		}

		return $data;
	}
}
