<?php
/**
 * Shortcode file.
 *
 * @package PLAYER\Public\Shortcode
 */

if ( ! function_exists( 'wpsplayer_shortcode' ) ) {
	/**
	 * Replace iframes by WPS PLAYER.
	 *
	 * @since 2.0.0
	 *
	 * @param array  $attr Attributes of the shortcode.
	 * @param string $content  Video shortcode content.
	 *
	 * @return string The WPS PLAYER shortcode
	 */
	function wpsplayer_shortcode( $attr, $content = '' ) {
		global $content_width;
		$post_id = get_post() ? get_the_ID() : 0;

		static $instance = 0;
		$instance++;

		/**
		 * Filters the default video shortcode output.
		 *
		 * If the filtered output isn't empty, it will be used instead of generating
		 * the default video template.
		 *
		 * @since 3.6.0
		 *
		 * @see wpsplayer_shortcode()
		 *
		 * @param string $html     Empty variable to be replaced with shortcode markup.
		 * @param array  $attr     Attributes of the shortcode. @see wpsplayer_shortcode()
		 * @param string $content  Video shortcode content.
		 * @param int    $instance Unique numeric ID of this video shortcode instance.
		 */
		$override = apply_filters( 'wpsplayer_shortcode_override', '', $attr, $content, $instance );
		if ( '' !== $override ) {
			return $override;
		}

		$video = null;

		$resolutions = array( '4k', '1080p', '720p', '480p', '360p', '240p' );

		$default_types = wp_get_video_extensions();
		$defaults_atts = array(
			'src'      => '',
			'poster'   => '',
			'loop'     => '',
			'autoplay' => '',
			'preload'  => 'auto',
			'width'    => 640,
			'height'   => 360,
			'class'    => 'wps-player-shortcode video-js vjs-big-play-centered',
		);
		foreach ( $resolutions as $resolution ) {
			$defaults_atts[ $resolution ] = '';
		}
		foreach ( $default_types as $type ) {
			$defaults_atts[ $type ] = '';
		}

		$atts = shortcode_atts( $defaults_atts, $attr, 'video' );

		$are_all_resolutions_empty = true;
		foreach ( $resolutions as $resolution ) {
			if ( '' !== $atts[ $resolution ] ) {
				$are_all_resolutions_empty = false;
			}
		}

		if ( is_admin() ) {
			// shrink the video so it isn't huge in the admin.
			if ( $atts['width'] > $defaults_atts['width'] ) {
				$atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
				$atts['width']  = $defaults_atts['width'];
			}
		} else {
			// if the video is bigger than the theme.
			if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
				$atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
				$atts['width']  = $content_width;
			}
		}

		$is_youtube    = false;
		$is_vimeo      = false;
		$yt_pattern    = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
		$vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';

		$primary = false;
		if ( ! empty( $atts['src'] ) ) {
			$is_vimeo   = ( preg_match( $vimeo_pattern, $atts['src'] ) );
			$is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
			if ( ! $is_youtube && ! $is_vimeo ) {
				$type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
				if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
					return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
				}
			}
			$primary = true;
			array_unshift( $default_types, 'src' );
		} else {

			if ( false === $are_all_resolutions_empty ) {
				$primary = true;
			} else {
				foreach ( $default_types as $ext ) {
					if ( ! empty( $atts[ $ext ] ) ) {
						$type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
						if ( strtolower( $type['ext'] ) === $ext ) {
							$primary = true;
						}
					}
				}
			}
		}

		if ( ! $primary ) {
			$videos = get_attached_media( 'video', $post_id );
			if ( empty( $videos ) ) {
				return;
			}

			$video       = reset( $videos );
			$atts['src'] = wp_get_attachment_url( $video->ID );
			if ( empty( $atts['src'] ) ) {
				return;
			}

			array_unshift( $default_types, 'src' );
		}

		/**
		 * Filters the media library used for the video shortcode.
		 *
		 * @since 3.6.0
		 *
		 * @param string $library Media library used for the video shortcode.
		 */
		$library = '';

		/**
		 * Filters the class attribute for the video shortcode output container.
		 *
		 * @since 3.6.0
		 * @since 4.9.0 The `$atts` parameter was added.
		 *
		 * @param string $class CSS class or list of space-separated classes.
		 * @param array  $atts  Array of video shortcode attributes.
		 */
		$atts['class'] = apply_filters( 'wpsplayer_shortcode_class', $atts['class'], $atts );

		$html_atts = array(
			'class'    => $atts['class'],
			'id'       => sprintf( 'video-%d-%d', $post_id, $instance ),
			'width'    => absint( $atts['width'] ),
			'height'   => absint( $atts['height'] ),
			'poster'   => esc_url( $atts['poster'] ),
			'loop'     => wp_validate_boolean( $atts['loop'] ),
			'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
			'preload'  => $atts['preload'],
		);

		foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
			if ( empty( $html_atts[ $a ] ) ) {
				unset( $html_atts[ $a ] );
			}
		}

		$attr_strings = array();
		foreach ( $html_atts as $k => $v ) {
			$attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
		}

		$html = sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );

		if ( ! empty( $atts['src'] ) ) {
			$fileurl = '';
			$source  = '<source type="%s" src="%s" />';
			foreach ( $default_types as $fallback ) {
				if ( ! empty( $atts[ $fallback ] ) ) {
					if ( empty( $fileurl ) ) {
						$fileurl = $atts[ $fallback ];
					}
					if ( 'src' === $fallback && $is_youtube ) {
						$type = array( 'type' => 'video/youtube' );
					} elseif ( 'src' === $fallback && $is_vimeo ) {
						$type = array( 'type' => 'video/vimeo' );
					} else {
						$type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
					}
					$url   = add_query_arg( '_', $instance, $atts[ $fallback ] );
					$html .= sprintf( $source, $type['type'], esc_url( $url ) );
				}
			}
		} else {
			$already_selected = false;
			foreach ( $resolutions as $resolution ) {
				if ( ! empty( $atts[ $resolution ] ) ) {
					if ( ! $already_selected ) {
						$source           = '<source type="%s" src="%s" title="%s" selected="true" />';
						$already_selected = true;
					} else {
						$source = '<source type="%s" src="%s" title="%s" />';
					}

					$type = wp_check_filetype( $atts[ $resolution ], wp_get_mime_types() );
					$url  = add_query_arg( '_', $instance, $atts[ $resolution ] );

					$html .= sprintf( $source, $type['type'], esc_url( $url ), $resolution );
				}
			}
		}

		if ( ! empty( $content ) ) {
			if ( false !== strpos( $content, "\n" ) ) {
				$content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
			}
			$html .= trim( $content );
		}

		$html .= '</video>';

		$output = sprintf( '<div class="wps-player-video">%s</div>', $html );

		/**
		 * Filters the output of the video shortcode.
		 *
		 * @since 3.6.0
		 *
		 * @param string $output  Video shortcode HTML output.
		 * @param array  $atts    Array of video shortcode attributes.
		 * @param string $video   Video file.
		 * @param int    $post_id Post ID.
		 * @param string $library Media library used for the video shortcode.
		 */
		return apply_filters( 'wpsplayer_shortcode', $output, $atts, $video, $post_id, $library );
	}
	add_shortcode( 'wpsplayer', 'wpsplayer_shortcode' );
}
