<?php
if (!defined( 'ABSPATH' ) ) {
	exit;
}
if (!class_exists( 'Pac_Da_Shortcode_In_Menus' ) ) {
	class Pac_Da_Shortcode_In_Menus {
		protected static $instance = null;
		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}
			return self::$instance;
		}
		public function __construct() {
			add_shortcode( 'pac_da_menu_shortcode', [$this, 'pac_da_add_shortcode'] );
			add_filter( 'walker_nav_menu_start_el', [$this, 'pac_da_filter_nav_menu'], 20, 2 );
			add_filter( 'megamenu_walker_nav_menu_start_el', [ $this, 'pac_da_filter_nav_menu'], 20, 2 );
			add_filter( 'clean_url', [$this, 'pac_da_show_shortcode_content'], 1, 3 );
			add_filter( 'wp_setup_nav_menu_item', [$this, 'pac_da_setup_menu_item'], 10, 1 );
		}
		public function pac_da_add_shortcode() {
			return __( 'https://wordpress.org', PAC_DA_PLUGIN_TEXT_DOMAIN );
		}
		public function pac_da_check_shortcode( $content ) {
			if ( false !== strpos( $content, '[' ) ) {
				preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER );
				if ( ! empty( $matches ) ) {
					return true;
				}
			}
			return false;
		}
		public function pac_da_filter_nav_menu( $item_output, $item ) {
			if ( ! is_object( $item ) || ! isset( $item->object ) ) {
				return $item_output;
			}
			if ( 'pac_da' !== $item->object ) {
				if ( isset( $item->post_title ) && 'FULL HTML OUTPUT' === $item->post_title ) {
					$item_output = do_shortcode( $item->url );
				} else {
					$item_output = do_shortcode( $item_output );
				}
			} elseif ( isset( $item->description ) ) {
				$item_output = do_shortcode( $item->description );
			}
			return $item_output;
		}
		public function pac_da_show_shortcode_content( $url, $original_url, $context ) {
			if ( 'display' === $context && $this->pac_da_check_shortcode( $original_url ) ) {
				return do_shortcode( $original_url );
			}
			return $url;
		}
		public function pac_da_setup_menu_item( $item ) {
			if ( ! is_object( $item ) ) {
				return $item;
			}
			if ( 'pac_da' === $item->object ) {
				$item->type_label = __( 'DA Shortcode', PAC_DA_PLUGIN_TEXT_DOMAIN );

				if ( ! empty( $item->post_content ) ) {
					$item->description = $item->post_content;
				} else {
					$item->description = get_transient( 'pac_da_description_hack_' . $item->object_id );
					delete_transient( 'pac_da_description_hack_' . $item->object_id );
				}
			}
			return $item;
		}
	}
}