<?php
namespace WPDRMS\ASP\Core;

if ( !defined('ABSPATH') ) {
	die('-1');
}

class Menu {

	/**
	 * Holds the main menu item
	 *
	 * @var array the main menu
	 */
	private static $main_menu = array();

	/**
	 * @var array
	 */
	private static $hooks = array();

	/**
	 * Submenu titles and slugs
	 *
	 * @var array
	 */
	private static $submenu_items = array();

	/**
	 * Bypass method to support translations, because static array varialbes cannot have a value defined as a result
	 * of a function, like 'key' => __('text', ..)
	 */
	private static function preInit() {
		if ( count(self::$submenu_items) == 0 ) {
			$main_menu     = array(
				'title'    => __('Ajax Search Pro', 'ajax-search-pro'),
				'slug'     => 'asp_main_settings',
				'file'     => '/backend/settings.php',
				'position' => '59.435',
				'icon_url' => 'img/svg/asp-menu-icon.svg',
			);
			$submenu_items = array(
				array(
					'title' => __('Search AI', 'ajax-search-pro'),
					'file'  => '/backend/ai-features.php',
					'slug'  => 'asp_ai_features',
				),
				array(
					'title' => __('Index Table', 'ajax-search-pro'),
					'file'  => '/backend/index_table.php',
					'slug'  => 'asp_index_table',
				),
				array(
					'title' => __('Synonyms', 'ajax-search-pro'),
					'file'  => '/backend/synonyms.php',
					'slug'  => 'asp_synonyms',
				),
				array(
					'title' => __('Priorities', 'ajax-search-pro'),
					'file'  => '/backend/priorities.php',
					'slug'  => 'asp_priorities',
				),
				array(
					'title' => __('Search Statistics', 'ajax-search-pro'),
					'file'  => '/backend/statistics.php',
					'slug'  => 'asp_statistics',
				),
				array(
					'title' => __('Analytics Integration', 'ajax-search-pro'),
					'file'  => '/backend/analytics.php',
					'slug'  => 'asp_analytics',
				),
				array(
					'title' => __('Cache', 'ajax-search-pro'),
					'file'  => '/backend/cache.php',
					'slug'  => 'asp_cache',
				),
				array(
					'title' => __('Compatibility & Other Settings', 'ajax-search-pro'),
					'file'  => '/backend/compatibility_settings.php',
					'slug'  => 'asp_compatibility_settings',
				),
				array(
					'title' => __('Maintenance', 'ajax-search-pro'),
					'file'  => '/backend/maintenance.php',
					'slug'  => 'asp_maintenance',
				),
				array(
					'title' => __('Help & Updates', 'ajax-search-pro'),
					'file'  => '/backend/updates_help.php',
					'slug'  => 'asp_updates_help',
				),
				array(
					'title' => 'Dev',
					'file'  => '/backend/dev.php',
					'slug'  => 'asp_dev',
				),
			);

			self::$main_menu     = $main_menu;
			self::$submenu_items = $submenu_items;
		}
	}

	/**
	 * Resolves a menu icon path to a value usable by add_menu_page().
	 *
	 * SVG files are inlined as a base64 data URI so the WordPress sidebar renders a
	 * crisp vector (and adapts to the admin colour scheme via opacity). Anything else
	 * — or an unreadable SVG — falls back to a plain plugin URL.
	 *
	 * @param string $rel Plugin-relative icon path (e.g. 'img/svg/asp-menu-icon.svg').
	 * @return string A data URI or a plugin URL.
	 */
	public static function menuIcon( string $rel ): string {
		if ( substr( $rel, -4 ) === '.svg' ) {
			$file = ASP_PATH . ltrim( $rel, '/' );
			if ( is_readable( $file ) ) {
				// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading a small SVG bundled with the plugin; wp_remote_get() is for remote URLs.
				$svg = file_get_contents( $file );
				if ( $svg !== false ) {
					// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Building a standard data:image/svg+xml;base64 URI for the admin menu icon.
					return 'data:image/svg+xml;base64,' . base64_encode( $svg );
				}
			}
		}

		return ASP_URL . $rel;
	}

	/**
	 * Runs the menu registration process
	 */
	public static function register() {

		$capability = ASP_DEMO == 1 ? 'read' : 'manage_options';

		self::preInit();

		$h                 = add_menu_page(
			self::$main_menu['title'],
			self::$main_menu['title'],
			$capability,
			self::$main_menu['slug'],
			array( '\\WPDRMS\\ASP\\Core\\Menu', 'route' ),
			self::menuIcon( self::$main_menu['icon_url'] ),
			self::$main_menu['position']
		);
		self::$hooks[ $h ] = self::$main_menu['slug'];

		foreach ( self::$submenu_items as $submenu ) {
			if ( $submenu['slug'] === 'asp_dev' && !defined('WP_ASP_TEST_ENV') ) {
				continue;
			}
			$h                 = add_submenu_page(
				self::$main_menu['slug'],
				self::$main_menu['title'],
				$submenu['title'],
				$capability,
				$submenu['slug'],
				array( '\\WPDRMS\\ASP\\Core\\Menu', 'route' )
			);
			self::$hooks[ $h ] = $submenu['slug'];
		}
	}

	/**
	 *  Includes the correct back-end file based on the page string
	 */
	public static function route() {
		$current_view = self::$hooks[ current_filter() ];
		include ASP_PATH . 'backend/' . str_replace('asp_', '', $current_view) . '.php';
	}

	/**
	 * Method to obtain the menu pages for context checking
	 *
	 * @return array
	 */
	public static function getMenuPages(): array {
		self::preInit();
		$ret = array();

		$ret[] = self::$main_menu['slug'];

		foreach ( self::$submenu_items as $menu ) {
			$ret[] = $menu['slug'];
		}

		return $ret;
	}
}
