<?php
// MENU ITEMS RESTRICTION


// SINGLE MENU ITEM CHECK
function pc_single_menu_check($items, $item_id) {
	foreach($items as $item) {
		if($item->ID == $item_id) {

			// polylang language switche -skip to avoid server crash
			if(function_exists('pll__') && strpos($item->post_name, 'language-switcher') !== false) {
				continue;	
			}

			if($item->menu_item_parent) {
				$parent_check = pc_single_menu_check($items, $item->menu_item_parent);	
				if(!$parent_check) {return false;}
			}

			// if allowed users array exist 
			if(isset($item->pc_hide_item) && is_array($item->pc_hide_item)) {
				$allowed = implode(',', $item->pc_hide_item);
				return (pc_user_check($allowed, '', true) === 1) ? true : false;
			}	
		}		
	}
	
	return true;
}


// HIDE MENU ITEMS IF USER HAS NO PERMISSIONS
function pc_menu_filter($items) {	
	$new_items = array();
	
	// full website lock 
	if((get_option('pg_complete_lock') && !get_option('pg_complete_lock_exclude_menu')) && pc_user_check('all', '', true) !== 1) {
		return $new_items;	
	}
	
	foreach($items as $item) {
		if(isset($item->menu_item_parent) && $item->menu_item_parent) {
			$parent_check = pc_single_menu_check($items, $item->menu_item_parent);	
		}
		else {$parent_check = true;}
		
		if($parent_check) {

			// if allowed users array exist 
			if(isset($item->pc_hide_item) && is_array($item->pc_hide_item)) {
				$allowed = implode(',', $item->pc_hide_item);
				if(pc_user_check($allowed, '', true) === 1) {$new_items[] = $item;}	
			}
			else {$new_items[] = $item;}
		}
	}
	
	return $new_items;
}
add_action( 'wp_nav_menu_objects', 'pc_menu_filter', 9999);

