<?php

namespace Shortcake_Bakery\Shortcodes;

class PDF extends Shortcode {

	public static function get_shortcode_ui_args() {
		$shortcode_attrs = array(
			'label'          => esc_html__( 'PDF', 'shortcake-bakery' ),
			'listItemImage'  => 'dashicons-media-document',
			'attrs'          => array(
				array(
					'label'       => esc_html__( 'Select or upload PDF', 'shortcake-bakery' ),
					'attr'        => 'attachment',
					'type'        => 'attachment',
					'libraryType' => 'application/pdf',
				),
				array(
					'label'       => esc_html__( '...or embed from URL', 'shortcake-bakery' ),
					'attr'        => 'url',
					'type'        => 'text',
				),
			),
		);

		/*
		 * Filter whether to enable the CORS proxy option on the [pdf]
		 * shortcode. (This behavior is disabled by default.)
		 *
		 * @param bool Returning true on this hook will enable this option.
		 */
		if ( apply_filters( 'shortcake_bakery_pdf_enable_cors_proxy', false ) ) {

			$shortcode_attrs['attrs'][] = array(
				'label'  => esc_html__( 'Proxy through local domain?', 'shortcake-bakery' ),
				'attr'   => 'proxy',
				'type'   => 'checkbox',
				'description' => esc_html__(
					"External PDFs require proper Access-Control headers in order to embed. \nIf you are seeing 'An error occurred while loading the PDF' errors, try this.",
					'shortcake-bakery'
				),
			);
		}

		return $shortcode_attrs;
	}

	/**
	 * Attach filters and actions for this shortcode
	 *
	 */
	public static function setup_actions() {
		add_filter( 'media_send_to_editor', array( get_called_class(), 'filter_media_send_to_editor' ), 10, 2 );
		add_filter( 'post_mime_types', array( get_called_class(), 'filter_post_mime_types' ) );
	}

	/**
	 * Filters the markup sent to the editor if a PDF is added directly through
	 * the media manager; replace it with this shortcode.
	 *
	 * @param string $html Markup generated by media_uplaod_form_handler()
	 * @param int $attachment_id Post ID of attachment being sent to editor
	 */
	public static function filter_media_send_to_editor( $html, $attachment_id ) {
		if ( 'application/pdf' !== get_post_mime_type( $attachment_id ) ) {
			return $html;
		}

		return '[' . self::get_shortcode_tag() . ' attachment="' . esc_attr( $attachment_id ) . '" /]';
	}

	/**
	 * Adds "PDF Documents" to the mime-type filters in the media library.
	 *
	 * Allows the PDF shortcode UI to select only .pdf documents to select between.
	 */
	public static function filter_post_mime_types( $post_mime_types ) {

		if ( ! isset( $post_mime_types['application/pdf'] ) ) {
			$post_mime_types['application/pdf'] = array(
				__( 'PDF documents', 'shortcake-bakery' ),
				__( 'Manage PDFs', 'shortcake-bakery' ),
				/* translators: PDF count. */
				_n_noop( 'PDF <span class="count">(%s)</span>', 'PDF <span class="count">(%s)</span>', 'shortcake-bakery' ),
			);
		}

		return $post_mime_types;
	}

	public static function callback( $attrs, $content = '' ) {

		if ( ! empty( $attrs['attachment'] ) && 'application/pdf' === get_post_mime_type( absint( $attrs['attachment'] ) ) ) {
			$url = get_attached_file( absint( $attrs['attachment'] ) );
		} elseif ( ! empty( $attrs['url'] ) ) {
			$url = esc_url_raw( $attrs['url'] );
		} else {
			return '';
		}

		$url_for_parse = ( 0 === strpos( $url, '//' ) ) ? 'http:' . $url :  $url;
		$scheme = self::parse_url( $url_for_parse, PHP_URL_SCHEME );

		$ext = pathinfo( $url, PATHINFO_EXTENSION );
		if ( 'pdf' !== strtolower( $ext ) ) {
			return '';
		}

		if ( ! empty( $attrs['proxy'] ) && $attrs['proxy'] ) {
			$url = self::asset_proxy_url( $url );
		}

		$viewer_url = SHORTCAKE_BAKERY_URL_ROOT . 'assets/lib/pdfjs/web/viewer.html';
		$source = add_query_arg( 'file', rawurlencode( $url ), $viewer_url );

		return '<iframe class="shortcake-bakery-responsive" data-true-height="800px" data-true-width="600px" width="600px" height="800px" frameBorder="0" src="' . esc_url( $source ) . '"></iframe>';
	}

	/**
	 * Get the admin-ajax URL to proxy a PDF through local site.
	 *
	 * @param string URL
	 * @return string URL
	 */
	private static function asset_proxy_url( $url ) {
		$asset_proxy_url = add_query_arg(
			array(
				'action' => 'shortcake_bakery_asset_proxy',
				'_nonce' => wp_create_nonce( 'asset-proxy-' . $url ),
				'url'    => $url,
			),
			admin_url( 'admin-ajax.php' )
		);

		/*
		 * Filter the proxied asset URL.
		 *
		 * Can be used to define an external proxy for cross-origin PDFs.
		 *
		 * @param string URL of proxied resource
		 * @param string URL of original PDF asset
		 */
		return apply_filters( 'shortcake_bakery_pdf_asset_proxy_url', $asset_proxy_url, $url );
	}

}
