<?php
/**
 * Class MenuOrderer
 *
 * @package DhlPolska\Admin\Menu
 */

namespace DhlPolska\Admin\Menu;

use DhlPolska\Admin\DhlPolskaMenu;
use DhlPolska\ShipmentTemplates\ShipmentTemplatePostType;
use DhlPolskaVendor\WPDesk\PluginBuilder\Plugin\Hookable;

/**
 * Ensure expected submenu order under DHL Polska.
 */
class MenuOrderer implements Hookable {

	/**
	 * Hooks.
	 */
	public function hooks() {
		add_action( 'admin_menu', [ $this, 'reorder_menu' ], 99 );
	}

	/**
	 * @return void
	 */
	public function reorder_menu() {
		global $submenu;

		if ( ! isset( $submenu[ DhlPolskaMenu::MENU_SLUG ] ) ) {
			return;
		}

		$items          = $submenu[ DhlPolskaMenu::MENU_SLUG ];
		$templates_slug = 'edit.php?post_type=' . ShipmentTemplatePostType::POST_TYPE;
		$desired_slugs  = [
			DhlPolskaMenu::MENU_SLUG,
			PnpSubmenu::PAGE_SLUG,
			$templates_slug,
			SettingsSubmenu::MENU_SLUG,
		];

		$ordered = [];
		foreach ( $desired_slugs as $slug ) {
			foreach ( $items as $item ) {
				if ( $item[2] === $slug ) {
					$ordered[] = $item;
					break;
				}
			}
		}

		foreach ( $items as $item ) {
			if ( in_array( $item[2], $desired_slugs, true ) ) {
				continue;
			}
			$ordered[] = $item;
		}

		// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Need to reorder admin submenu items.
		$submenu[ DhlPolskaMenu::MENU_SLUG ] = $ordered;
	}
}
