<?php
/**
 * Seventhqueen\Typer\Nav_Menus\Component class
 *
 * @package typer
 */

namespace Seventhqueen\Typer\Nav_Menus;

use Seventhqueen\Typer\Component_Interface;
use Seventhqueen\Typer\Templating_Component_Interface;
use WP_Post;
use function add_action;
use function register_nav_menus;
use function has_nav_menu;
use function wp_nav_menu;

/**
 * Class for managing navigation menus.
 *
 * Exposes template tags:
 * * `typer()->is_primary_nav_menu_active()`
 * * `typer()->display_primary_nav_menu( array $args = [] )`
 */
class Component implements Component_Interface, Templating_Component_Interface {

	const PRIMARY_NAV_MENU_SLUG = 'primary';

	/**
	 * Gets the unique identifier for the theme component.
	 *
	 * @return string Component slug.
	 */
	public function get_slug() {
		return 'nav_menus';
	}

	/**
	 * Adds the action and filter hooks to integrate with WordPress.
	 */
	public function initialize() {
		add_action( 'after_setup_theme', [ $this, 'action_register_nav_menus' ] );
	}

	/**
	 * Gets template tags to expose as methods on the Template_Tags class instance, accessible through `typer()`.
	 *
	 * @return array Associative array of $method_name => $callback_info pairs. Each $callback_info must either be
	 *               a callable or an array with key 'callable'. This approach is used to reserve the possibility of
	 *               adding support for further arguments in the future.
	 */
	public function template_tags() {
		return [
			'is_primary_nav_menu_active' => [ $this, 'is_primary_nav_menu_active' ],
			'display_primary_nav_menu'   => [ $this, 'display_primary_nav_menu' ],
		];
	}

	/**
	 * Registers the navigation menus.
	 */
	public function action_register_nav_menus() {
		register_nav_menus(
			[
				static::PRIMARY_NAV_MENU_SLUG => esc_html__( 'Primary', 'typer' ),
			]
		);
	}


	/**
	 * Checks whether the primary navigation menu is active.
	 *
	 * @return bool True if the primary navigation menu is active, false otherwise.
	 */
	public function is_primary_nav_menu_active() {
		return (bool) has_nav_menu( static::PRIMARY_NAV_MENU_SLUG );
	}

	/**
	 * Displays the primary navigation menu.
	 *
	 * @param array $args Optional. Array of arguments. See `wp_nav_menu()` documentation for a list of supported
	 *                    arguments.
	 */
	public function display_primary_nav_menu( array $args = [] ) {
		if ( ! isset( $args['container'] ) ) {
			$args['container'] = 'ul';
		}
		$args['depth']      = 4;
		$args['menu_class'] = 'navbar-nav mr-auto';
		$args['walker']     = new Walker();

		$args['theme_location'] = static::PRIMARY_NAV_MENU_SLUG;

		wp_nav_menu( $args );
	}
}
