<?php
/**
 * Plugin Name: Rockthemes Mega Menu
 * Plugin URI: https://azoom.rockthemes.net
 * Description: Mega Menu system 
 * Author URI: http://themeforest.net/user/XanderRock
 */


class Rockthemes_Mega_menu{

	function __construct(){
		add_action('wp_enqueue_scripts', array( $this, 'rockthemes_mm_style_init'),9 );
		add_action('wp_enqueue_scripts', array( $this, 'rockthemes_mm_js_init') );
	}

	
	function rockthemes_mm_js_init(){
		
		wp_enqueue_script( 'megamenu-js', F_WAY. '/rock-widgets/mega-menu/js/megamenu.js', array('jquery') );
		
		wp_enqueue_script( 'rockthemes-mobile-menu', F_WAY. '/js/jquery.mmenu.min.all.js', array('jquery') );
	}
	
	function rockthemes_mm_style_init(){
		wp_enqueue_style('rockthemes-mobile-menu', F_WAY. '/css/jquery.mmenu.all.css', '');
		
		if(xr_get_option('header_location', 'top_navigation') === 'side_navigation'){
			wp_enqueue_style('rockthemes-mobile-menu-left', F_WAY. '/css/jquery.mmenu.widescreen.css', '');
			//wp_enqueue_style('rockthemes-mobile-menu-icon', F_WAY. '/css/jquery.mmenu.iconbar.css', '');
		}
	}

	
}








/*
**	Wordpress Importer Main Navigation (Menu) Meta Import
**
**	Wordpress Importer does not import navigation (menu) meta fields. We use this system
**	to import meta fields. 
**
**	Flow :
**		1 . rpb_mm_import_start:function
**				Makes $rtmegamenu global variable to hold posts
**
**		2 . rpb_mm_wp_import_hook:function
**				Gets all posts of main_nav_item post types and stores
**				these posts in $rtmegamenu global variable's 'post' array.
**
**		3 . rpb_mm_import_end:function
**				Uses $rtmegamenu global variable made in step 1
**				Uses $wp_import global variable made by Wordpress Importer
**
**	@since	:	1.0
**	@author	:	XanderRock
*/
function rpb_mm_import_start(){
	global $wp_import;

	$GLOBALS['rtmegamenu'] = array('posts' => array());	

	if(isset($_POST['import_id']) && $_POST['import_id'] != ''){
		$file = get_attached_file( (int) $_POST['import_id']);
	}else{
        $file = OPTIONS_DIR ."libs/demo.xml" ; // Get the xml file from directory 

        if(isset($GLOBALS['xroc_demo_details'])){
			$file = OPTIONS_DIR.'demos/'.$GLOBALS['xroc_demo_details']['dir_name'].'/'.$GLOBALS['xroc_demo_details']['xml_filename'];
		}
	}

	global $wp_filesystem;

	if (empty($wp_filesystem)) {
		require_once (ABSPATH . '/wp-admin/includes/file.php');
		WP_Filesystem();
	}		

	$xml_file_data = $wp_filesystem->get_contents($file);

	$dom = new DOMDocument;
	$read = $dom->loadXML( $xml_file_data);

	if(!$read) return;

	$xml = simplexml_import_dom( $dom );
	unset( $dom );

	$base_url = $xml->xpath('/rss/channel/wp:base_blog_url');
	$base_url = (string) trim( $base_url[0] );

	$GLOBALS['rtm_base_blog_url'] = $base_url;

}
add_action('import_start', 'rpb_mm_import_start');


/*
**	Stores nav_menu_item post types in a global variable named rtmegamenu['posts']
**	
**	This function uses the system in Wordpress Importer plugins wordpress-importer.php file
**	Function updated and some code referred from 
**	https://wordpress.org/support/topic/failure-to-import-post-meta-for-nav-menu-item?replies=6
**
**	@param	:	$item:Array -> Post Item
**	@return	:	$item:Array -> Same post item returns without any changes
**
**	@since	:	1.0
**	@author	:	XanderRock
*/
function rpb_mm_wp_import_hook( $item ){

	//Only remap Main navigation
	if($item['post_type'] !== 'nav_menu_item' || $item['status'] === 'draft') return $item;
	
	if(isset($GLOBALS['rtmegamenu']) && isset($GLOBALS['rtmegamenu']['posts'])){
				
		$menu_slug = false;
		if ( isset($item['terms']) ) {
			// loop through terms, assume first nav_menu term is correct menu
			foreach ( $item['terms'] as $term ) {
				if ( 'nav_menu' == $term['domain'] ) {
					$menu_slug = $term['slug'];
					break;
				}
			}
		}

		// no nav_menu term associated with this menu item
		if ( ! $menu_slug ) {
			esc_html_e( 'Menu item skipped due to missing menu slug', 'azoom' );
			echo '<br />';
			return;
		}

		$menu_id = term_exists( $menu_slug, 'nav_menu' );
		if ( ! $menu_id ) {
			printf( esc_html__( 'Menu item skipped due to invalid menu slug: %s', 'azoom' ), esc_html( $menu_slug ) );
			echo '<br />';
			return;
		} else {
			$menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
		}
		
		$new_item = $item;
		$new_item['post_menu_id'] = (int) $menu_id;
		$new_item['post_first_id'] = $new_item['post_id'];

		$menu_item_meta = array();
		
		foreach ( $item['postmeta'] as $meta ){
			$menu_item_meta[$meta['key']] = $meta['value'];
		}
		
		$args = array(
			'menu-item-object-id' => '',
			'menu-item-object' => '',
			'menu-item-parent-id' => '',
			'menu-item-position' => '',
			'menu-item-type' => '',
			'menu-item-title' => '',
			'menu-item-url' => '',
			'menu-item-description' => '',
			'menu-item-attr-title' => '',
			'menu-item-target' => '',
			'menu-item-classes' => '',
			'menu-item-xfn' => '',
			'menu-item-status' => ''
		);
		
		// Remove all default $args from $menu_item_meta array
		foreach ( $args as $a => $arg ) {
			unset( $menu_item_meta[ '_' . str_replace('-', '_', $a) ]);
		}
		// For some reason this doesn't follow the same naming convention so manually unset
		unset ( $menu_item_meta['_menu_item_menu_item_parent'] );

		$menu_item_meta = array_diff_assoc( $menu_item_meta, $args );

		$new_item['postmeta_edit'] = $menu_item_meta;		

		$GLOBALS['rtmegamenu']['posts'][] = $new_item;	
		
	}
	
	return $item;
}
add_filter('wp_import_post_data_raw','rpb_mm_wp_import_hook', 99);





/*
**	Wordpress Importer plugin fires this hook at the end of import. This function
**	adds required meta fields to the main navigation (menu)
**
**	Uses the hook in Wordpress Importer plugin at the wordpress-importer.php file
**
**	Uses global $rtmegamenu variable. This variable holds menu posts in $rtmegamenu['posts']
**
**	Uses $wp_import global variable. This variable holds the main Wordpress Importer plugin
**
**	@param	:	Only uses global variables
**	@return	:	void
**
**	@since	:	1.0
**	@author	:	XanderRock
*/
function rpb_mm_import_end(){
	global $rtmegamenu, $wp_import;

	if(empty($rtmegamenu)) return;

	//Get the imported datas old url
	$old_url = $wp_import->base_url;
	
	//Get current url
	$current_site_url = home_url();

	if(isset($GLOBALS['rpb_export_settings'])){
		/*
		**	This global variable will be set when using One Click Installer.
		**
		**	@since	:	1.0
		*/
		//echo 'GLOBAL ROCKTHEMES';
		$omu_data = $GLOBALS['rpb_export_settings'];
		if(is_array($omu_data) && isset($omu_data['media_url']) && isset($omu_data['media_url']['baseurl'])){
			$omu = $omu_data['media_url']['baseurl'];
		}
	}else{
		//echo 'NO GLOBAL ROCKTHEMES';
		$omu = get_option('rpb_migrate_omu',false);	
	}
	
	
	if(isset($omu) && $omu && $omu !== ''){
		//echo 'ROCKTHEMES EXPORT SETTINGS OMU '.$omu;
		$old_url = $omu;	
		$nmu = wp_upload_dir();
		$current_site_url = $nmu['baseurl'];
	}
		

	//Encode URLs
	$old_url_encoded = str_replace('/', '\\/', $old_url);
	$current_site_url_encoded = str_replace('/', '\\/', $current_site_url);

	$old_main_url = '';
	$new_main_url = '';
	if(isset($GLOBALS['rtm_base_blog_url']) && $GLOBALS['rtm_base_blog_url'] != ''){
		$old_main_url = $GLOBALS['rtm_base_blog_url'];
		$new_main_url = get_site_url();
	}	

	if(!isset($wp_import) || empty($wp_import)) return;

	foreach ($rtmegamenu['posts'] as $item){

		if(isset($old_main_url) && $old_main_url != ''){
			$menu_id = (int) $wp_import->processed_menu_items[$item['post_first_id']];
			$menu_url = get_post_meta($menu_id, '_menu_item_url');

			if(isset($menu_url) && isset($menu_url[0]) ){
				$menu_url = str_replace($old_main_url, $new_main_url, $menu_url[0]);
				update_post_meta( $menu_id, '_menu_item_url', $menu_url );
			}

		}


		foreach($item['postmeta_edit'] as $mk => $mv){

			if($mk === '_rockthemes_mm' || $mk === '_rockthemes_mm_fe'){
				
				/*
				**	Wordpress auto serialize the data in database. And the data is the same for
				**	
				**
				*/
				$encoded_details = json_encode(maybe_unserialize($mv));
								
				//replace all of the old urls 	
				$encoded_details_replaced = str_replace($old_url, $current_site_url, ($encoded_details));
				
				//replace all of the old urls 	
				$encoded_details_replaced = str_replace($old_url_encoded, $current_site_url_encoded, ($encoded_details_replaced));
				
				$decoded_details_replaced = json_decode($encoded_details_replaced, true);
								
				update_post_meta($menu_id, $mk, ($decoded_details_replaced));			
			}else{
				update_post_meta($menu_id, $mk, maybe_unserialize($mv));
			}
		}

	}
}
add_action('import_end', 'rpb_mm_import_end');










// instantiate plugin's class
$GLOBALS['rockthemes_mega_menu'] = new Rockthemes_Mega_menu();
global $pagenow;


if(!function_exists('rockthemes_mm_admin_files')):
function rockthemes_mm_admin_files(){
	global $rockthemes_mm_defaults;
	$rmm = array(
		'ajaxurl'	=>	admin_url('admin-ajax.php'),
		'nonce'		=>	wp_create_nonce("rockthemes_mm_nonce"),
		'debug'		=>	'yes',
		
		'text'		=>	array(
			'trigger_button'	=>	__('Mega Menu', 'azoom')
		),
		
		'default_settings'	=> $rockthemes_mm_defaults
	);
	
	//wp_enqueue_style( 'rockthemes_mm_icomoon', F_WAY.'/css/icomoon.css', '', '', 'all' );
	wp_enqueue_style( 'rockthemes_mm_bootstrap_css', F_WAY.'/rock-widgets/mega-menu/css/admin.css', '', '', 'all' );

	wp_enqueue_script('jquery');
	wp_enqueue_script('json2');
	wp_enqueue_media();

	wp_enqueue_script('rockthemes_mm_bootstrap_modal', F_WAY.'/rock-widgets/mega-menu/js/bootstrap.js', array('jquery'), '');
	wp_enqueue_script('rockthemes_mm_admin_js', F_WAY.'/rock-widgets/mega-menu/js/rockthemes_mm_admin.js', array('jquery'), '');

	wp_localize_script('rockthemes_mm_admin_js', 'rockthemes', $rmm);

}
endif;

include_once( 'custom_walker-mega.php' );

//include_once( 'edit_custom_walker.php' );

if ( (defined( 'WP_ADMIN' ) && WP_ADMIN ) ||  ( defined( 'DOING_AJAX' ) && DOING_AJAX )){

	/*
	**	Rockthemes Mega Menu Functions
	**
	*/
	if(strpos($pagenow, 'nav-menus') > -1 || 
		((isset($_REQUEST['rockthemes_mm']) &&
		!empty($_REQUEST['rockthemes_mm']) && 
		$_REQUEST['rockthemes_mm'] = 'yes'))){
		
		define('RMM_DIR', get_template_directory().'/rock-widgets/mega-menu/');
		define('RMM_URI', get_template_directory_uri().'/rock-widgets/mega-menu/');

		include_once('rockthemes-mm-defaults.php');
		include_once('rockthemes-mm-functions.php');
		include_once('rockthemes-mm-admin-ui.php');
		include_once('rockthemes-mm-modals.php');
		add_action('admin_enqueue_scripts', 'rockthemes_mm_admin_files');
	}
}


function rockthemes_mega_menu( $args = array() ) {
				
	static $menu_id_slugs = array();

	$walker = new Rockthemes_MegaMenu_Walker();

	$defaults = array( 
		'menu' => '', 
		'container' => 'div', 
		'container_class' => '', 
		'container_id' => 'nav', 
		'menu_class' => 'nav-menu rtm-menu', 
		'menu_id' => '', 
		'echo' => true, 
		'fallback_cb' => 'wp_page_menu', 
		'before' => '', 
		'after' => '', 
		'link_before' => '', 
		'link_after' => '', 
		'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 
		'depth' => 0, 
		'walker' => $walker, 
		'theme_location' => 'primary' 
	);

	$args = wp_parse_args( $args, $defaults );
	/**
	 * Filter the arguments used to display a navigation menu.
	 *
	 * @since 3.0.0
	 *
	 * @param array $args Arguments from {@see wp_nav_menu()}.
	 */
	$args = apply_filters( 'wp_nav_menu_args', $args );
	$args = (object) $args;

	// Get the nav menu based on the requested menu
	$menu = wp_get_nav_menu_object( $args->menu );

	// Get the nav menu based on the theme_location
	if ( ! $menu && $args->theme_location && ( $locations = get_nav_menu_locations() ) && isset( $locations[ $args->theme_location ] ) )
		$menu = wp_get_nav_menu_object( $locations[ $args->theme_location ] );

	// get the first menu that has items if we still can't find a menu
	if ( ! $menu && !$args->theme_location ) {
		$menus = wp_get_nav_menus();
		foreach ( $menus as $menu_maybe ) {
			if ( $menu_items = wp_get_nav_menu_items( $menu_maybe->term_id, array( 'update_post_term_cache' => false ) ) ) {
				$menu = $menu_maybe;
				break;
			}
		}
	}

	// If the menu exists, get its items.
	if ( $menu && ! is_wp_error($menu) && !isset($menu_items) )
		$menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'update_post_term_cache' => false ) );


	/*
	 * If no menu was found:
	 *  - Fall back (if one was specified), or bail.
	 *
	 * If no menu items were found:
	 *  - Fall back, but only if no theme location was specified.
	 *  - Otherwise, bail.
	 */
	if ( ( !$menu || is_wp_error($menu) || ( isset($menu_items) && empty($menu_items) && !$args->theme_location ) )
		&& $args->fallback_cb && is_callable( $args->fallback_cb ) )
			return call_user_func( $args->fallback_cb, (array) $args );

	if ( ! $menu || is_wp_error( $menu ) )
		return false;

	$nav_menu = $items = '';

	$nav_menu .= '<nav id="rtm-navigation" class="navigation main-navigation">';
				
	$show_container = false;
	if ( $args->container ) {
		/**
		 * Filter the list of HTML tags that are valid for use as menu containers.
		 *
		 * @since 3.0.0
		 *
		 * @param array The acceptable HTML tags for use as menu containers, defaults as 'div' and 'nav'.
		 */
		$allowed_tags = apply_filters( 'wp_nav_menu_container_allowedtags', array( 'div', 'nav' ) );
		if ( in_array( $args->container, $allowed_tags ) ) {
			$show_container = true;
			$class = $args->container_class ? ' class="' . esc_attr( $args->container_class ) . '"' : ' class="menu-'. $menu->slug .'-container"';
			$id = $args->container_id ? ' id="' . esc_attr( $args->container_id ) . '"' : '';
			$nav_menu .= '<'. $args->container . $id . $class . '>';
		}
	}

	// Set up the $menu_item variables
	_wp_menu_item_classes_by_context( $menu_items );

	$sorted_menu_items = $menu_items_with_children = array();
	foreach ( (array) $menu_items as $menu_item ) {
		$sorted_menu_items[ $menu_item->menu_order ] = $menu_item;
		if ( $menu_item->menu_item_parent )
			$menu_items_with_children[ $menu_item->menu_item_parent ] = true;
	}

	// Add the menu-item-has-children class where applicable
	if ( $menu_items_with_children ) {
		foreach ( $sorted_menu_items as &$menu_item ) {
			if ( isset( $menu_items_with_children[ $menu_item->ID ] ) )
				$menu_item->classes[] = 'menu-item-has-children';
		}
	}

	unset( $menu_items, $menu_item );

	/**
	 * Filter the sorted list of menu item objects before generating the menu's HTML.
	 *
	 * @since 3.1.0
	 *
	 * @param array $sorted_menu_items The menu items, sorted by each menu item's menu order.
	 */
	$sorted_menu_items = apply_filters( 'wp_nav_menu_objects', $sorted_menu_items, $args );

	$items .= walk_nav_menu_tree( $sorted_menu_items, $args->depth, $args );
	unset($sorted_menu_items);

	// Attributes
	if ( ! empty( $args->menu_id ) ) {
		$wrap_id = $args->menu_id;
	} else {
		$wrap_id = 'menu-' . $menu->slug;
		while ( in_array( $wrap_id, $menu_id_slugs ) ) {
			if ( preg_match( '#-(\d+)$#', $wrap_id, $matches ) )
				$wrap_id = preg_replace('#-(\d+)$#', '-' . ++$matches[1], $wrap_id );
			else
				$wrap_id = $wrap_id . '-1';
		}
	}
	$menu_id_slugs[] = $wrap_id;

	$wrap_class = $args->menu_class ? $args->menu_class.' rtm-menu' : '';

	/**
	 * Filter the HTML list content for navigation menus.
	 *
	 * @since 3.0.0
	 *
	 * @param string $items The HTML list content for the menu items.
	 * @param array $args Arguments from {@see wp_nav_menu()}.
	 */
	$items = apply_filters( 'wp_nav_menu_items', $items, $args );
	/**
	 * Filter the HTML list content for a specific navigation menu.
	 *
	 * @since 3.0.0
	 *
	 * @param string $items The HTML list content for the menu items.
	 * @param array $args Arguments from {@see wp_nav_menu()}.
	 */
	$items = apply_filters( "wp_nav_menu_{$menu->slug}_items", $items, $args );

	// Don't print any markup if there are no items at this point.
	if ( empty( $items ) )
		return false;

	$nav_menu .= sprintf( $args->items_wrap, esc_attr( $wrap_id ), esc_attr( $wrap_class ), $items );
	unset( $items );

	if ( $show_container )
		$nav_menu .= '</' . $args->container . '></nav><!-- #site-navigation -->';

	/**
	 * Filter the HTML content for navigation menus.
	 *
	 * @since 3.0.0
	 *
	 * @param string $nav_menu The HTML content for the navigation menu.
	 * @param array $args Arguments from {@see wp_nav_menu()}.
	 */
	$nav_menu = apply_filters( 'wp_nav_menu', $nav_menu, $args );
				
	$woo_cart = function_exists('rockthemes_woocommerce_active') && rockthemes_woocommerce_active() && xr_get_option('add_cart_icon_to_menu', false) ? true : false;
	if(xr_get_option('main_menu_model', 'regular') !== 'regular'){
		$nav_menu .= '<div class="menu-mobile-details'.($woo_cart ? ' rtm-woo-cart-enabled' : '').'">';
	}
				
	/*
	**	Check if the rockthemes mobile active
	*/
	if(1==1){

		$nav_menu .= '
			<div class="mobile-menu-switcher-holder azoom-transition">
				<i class="mobile-menu-switcher icomoon icomoon-icon-list3"></i>
			</div>
		';

		/*
		$nav_menu .= '
		<div class="mobile-menu-switcher-holder azoom-transition">
			<div id="mobile-menu-list-icon" class="mm-slideout">
				<span></span>
			</div>
		</div>';
		*/
	}
	
	/*
	**	TO DO : Bind To an Option
	**	Check if cart is activated in tablets
	*/
	if($woo_cart){
		$cart_url = '';
		if(isset($GLOBALS['woocommerce'])){
			if(version_compare(WOOCOMMERCE_VERSION, "2.5") >= 0){
				$cart_url = wc_get_checkout_url();
			}else{
				$cart_url = $GLOBALS['woocommerce']->cart->get_cart_url();
			}
		}
		$nav_menu .= '
			<a href="'.$cart_url.'" class="mobile-cart-holder azoom-transition">
				<i class="mobile-cart icomoon icomoon-icon-shopping114"></i>
			</a>
		';
	}
	
	if(xr_get_option('main_menu_model', 'regular') !== 'regular'){
		//$nav_menu .= azoom_add_main_nav_mobile_add_search();
		$nav_menu .= '</div>';//.menu-mobile-details	
	}
				

	if ( $args->echo )
		echo rockthemes_escaped_out_render($nav_menu);
	else
		return $nav_menu;
}