<?php

/**
 * Plugin glomex_oEmbed
 *
 * @package   glomex_oEmbed
 * @author    glomex <info@glomex.com>
 * @copyright 2022 glomex
 * @license   Apache-2.0
 * @link      https://glomex.com
 */

namespace glomex_oEmbed\Internals;

/**
 * OembedHooksProvider class
 */
class OembedHooksProvider {

	/**
	 * OembedExtender object
	 *
	 * @var \glomex_oEmbed\Internals\OembedExtender
	 */
	private $oembed_extender;

	/**
	 * OembedHooksProvider construct
	 */
	public function __construct() {
		$this->oembed_extender = new OembedExtender;

		\add_filter( 'oembed_providers', array($this, 'providers'), 10 );
		\add_filter( 'oembed_fetch_url', array($this, 'fetch_url'), 10, 2 );
	}

	/**
	 * Providers hook
	 *
	 * @param array $data Providers array.
	 * @return array
	 */
	public function providers( array $data ): array {
		if ( empty( $_SERVER['QUERY_STRING'] ) ) {
			return $data;
		}

		$query_string = \filter_var( \wp_unslash( $_SERVER['QUERY_STRING'] ), FILTER_SANITIZE_FULL_SPECIAL_CHARS );

		if ( empty( $query_string ) ) {
			return $data;
		}

		\parse_str( \strval( $query_string ), $output );

		if ( empty( $output['url'] ) || \strpos( \strval( $output['url'] ), 'exchange.glomex' ) === false ) {
			return $data;
		}

		$this->oembed_extender->generate_oembed_data( \strval( $output['url'] ) );

		return \array_merge(
			$data,
			[
				'#https?:\/\/exchange\.glomex\.com\/(video|videos|playlist|playlists)\/.*#i' => [
					$this->oembed_extender->get_oembed_url(),
					true,
				],
			]
		);
	}

	/**
	 * Fetch Url hook
	 *
	 * @param string $provider Provider string ulr.
	 * @param string $url The url for the embed.
	 */
	public function fetch_url( string $provider, string $url ): string {
		if ( \strpos( $url, 'exchange.glomex' ) === false ) {
			return $provider;
		}

		$this->oembed_extender->generate_oembed_data( $url );

		if ( ! empty( $this->errorString ) ) {
			return $provider;
		}

		return \add_query_arg( 'integrationId', $this->oembed_extender->integrationId, $provider );
	}

}
