<?php

namespace SoftMultimediaPlayer;

defined( 'ABSPATH' ) || exit();

class Shortcode {

	/**
	 * @var null
	 */
	private static $instance = null;

	/**
	 * Shortcode constructor.
	 */
	public function __construct() {
		add_shortcode( 'multimedia_player', array( $this, 'player' ) );
	}

	/**
	 * @param $atts
	 *
	 * @return false|string
	 * @since 1.0.0
	 */
	public function player( $atts ) {
		$is_preview = isset( $_GET['preview'] );

		$atts = shortcode_atts( array(
			'id'          => '',
			'player_type' => 'shortcode',
		), $atts );

		$id     = $atts['id'];
		$player = smp_get_players( $id );

		if ( empty( $player['status'] ) && ! $is_preview ) {
			return;
		}

		$player_type = $atts['player_type'];

		$config       = $player['config'];
		$config['id'] = $id;

		$items = $config['items'];

		$enable_schema = filter_var( isset( $config['schema'] ) ? $config['schema'] : false, FILTER_VALIDATE_BOOLEAN );

		if ( $enable_schema && ! is_admin() && ! defined( 'REST_REQUEST' )) {

			$schema_data = array();

			foreach ( $items as $item ) {
				$thumbnail     = ! empty( $item['thumbnail'] ) ? $item['thumbnail'] : site_url( '/' );
				$schema_data[] = array(
					'@context'     => 'https://schema.org',
					'@type'        => 'VideoObject',
					'name'         => esc_html( $item['title'] ),
					'description'  => esc_html( $item['title'] ),
					'thumbnailUrl' => esc_url( $thumbnail ),
					'url'          => esc_url( $item['source'] ),
					'uploadDate'   => esc_html( $player['created_at'] ),
				);
			}

			echo '<script type="application/ld+json">' . wp_json_encode( $schema_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) . '</script>';
		}

		if ( ! empty( $items ) ) {
			foreach ( $items as $key => $item ) {

				$item = (array) $item;

				$source = ! empty( $item['source'] ) ? $item['source'] : '';

				$items[ $key ]['source'] = apply_filters( 'soft_multimedia_player/source', $source );
			}

			$config['items'] = $items;
		}


		// Enqueue frontend scripts
		Enqueue::instance()->frontend_scripts();

		return sprintf( '<div class="multimedia_player" data-player-type="%1$s" data-data="%2$s"></div>', esc_attr( $player_type ), esc_attr( base64_encode( wp_json_encode( $config ) ) ) );

	}

	/**
	 * @return Shortcode|null
	 */
	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}
}

Shortcode::instance();
