<?php
/**
 * Shared behaviour for modules that present a stored menu.
 *
 * @package MenuVerse
 */

namespace WPXero\MenuVerse\Modules;

use WPXero\MenuVerse\Menus\Menu_Tree;
use WPXero\MenuVerse\Plugin;

defined( 'ABSPATH' ) || exit;

/**
 * Resolves the `menu` setting to a tree.
 *
 * Every module except the bottom bar renders a menu WordPress already stores,
 * and each one resolved the same setting the same way. The bottom bar keeps
 * its own item list, so it does not use this.
 */
trait Menu_Backed {

	/**
	 * A menu backed module has content exactly when its menu has items.
	 *
	 * @param array $settings Resolved settings.
	 * @return bool
	 */
	public function has_content( array $settings ) {
		$tree = $this->resolve_menu( $settings );

		return $tree instanceof Menu_Tree && (bool) $tree->items();
	}

	/**
	 * Resolves the configured menu to a normalized tree.
	 *
	 * The stored value is `source:id`. Falling back to the first available
	 * menu is what makes a freshly enabled module show something before
	 * anybody has chosen a menu for it.
	 *
	 * @param array $settings Resolved settings.
	 * @return Menu_Tree|null Null when no menu could be resolved.
	 */
	protected function resolve_menu( array $settings ) {
		$sources = Plugin::instance()->menu_sources();
		$value   = isset( $settings['menu'] ) ? (string) $settings['menu'] : '';

		if ( '' !== $value && false !== strpos( $value, ':' ) ) {
			list( $source_id, $menu_id ) = explode( ':', $value, 2 );

			return $sources->get_tree( $source_id, (int) $menu_id );
		}

		$menus = $sources->list_menus();

		return empty( $menus ) ? null : $sources->get_tree( $menus[0]['source'], $menus[0]['id'] );
	}
}
