<?php
/**
 * Admin functionality for FoodOrd.
 *
 * @package FoodOrd
 */

defined('ABSPATH') || exit;

/**
 * Class Foodord_Admin
 */
class Foodord_Admin
{

	/**
	 * Option key for diagnostic data sharing consent.
	 */
	private const OPTION_ALLOW_TRACKING = 'foodord_allow_tracking';

	/**
	 * Shortcodes handler instance.
	 *
	 * @var Foodord_Shortcodes
	 */
	private $shortcodes_handler;

	/**
	 * License handler instance.
	 *
	 * @var Foodord_License
	 */
	private $license_handler;

	/**
	 * Product layout handler instance.
	 *
	 * @var Foodord_Product_Layout|null
	 */
	private $product_layout_handler;

	/**
	 * Determine whether the FoodOrd Pro plugin is active.
	 */
	private function is_pro_active(): bool
	{
		if (function_exists('foodord_pro_is_active')) {
			return (bool) foodord_pro_is_active();
		}

		if (defined('FOODORD_PRO_VERSION')) {
			return true;
		}

		return false;
	}

	/**
	 * Retrieve the parent slug used for all FoodOrd admin pages.
	 */
	private function get_settings_parent_slug(): string
	{
		return function_exists('foodord_get_admin_parent_slug')
			? foodord_get_admin_parent_slug()
			: 'foodord-settings';
	}

	/**
	 * Determine whether the current admin hook suffix matches a FoodOrd page.
	 *
	 * @param string $hook     Current admin hook suffix.
	 * @param string $page_key FoodOrd page key.
	 */
	private function is_hook_for_page($hook, $page_key): bool
	{
		if (!is_string($hook) || '' === $page_key) {
			return false;
		}

		$slugs = function_exists('foodord_get_settings_page_slugs')
			? foodord_get_settings_page_slugs($page_key)
			: array($page_key);

		foreach ($slugs as $slug) {
			if ('' !== $slug && false !== strpos($hook, $slug)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Determine whether shared admin assets (like the horizontal nav) should load.
	 *
	 * @param mixed $hook Current admin hook suffix.
	 */
	private function should_enqueue_shared_admin_assets($hook): bool
	{
		if (!is_string($hook) || '' === $hook) {
			return false;
		}

		$needles = array('foodord', 'foodord-theme-settings');
		foreach ($needles as $needle) {
			if ('' !== $needle && false !== strpos($hook, $needle)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Retrieve the current slug for a given page key.
	 *
	 * @param string $page_key FoodOrd page key.
	 */
	private function get_page_slug(string $page_key): string
	{
		return function_exists('foodord_get_settings_page_slug')
			? foodord_get_settings_page_slug($page_key)
			: $page_key;
	}

	/**
	 * Retrieve the Dashboard hero logo URL.
	 */
	private function get_dashboard_logo_url(): string
	{
		return plugins_url('admin/images/logo-dashboard.png', FOODORD_FILE);
	}

	/**
	 * Render the Dashboard hero header.
	 */
	private function render_dashboard_header(): void
	{
		$docs_url = set_url_scheme('//www.foodord.com/documentation/', 'https');
		$pricing_url = set_url_scheme('//www.foodord.com/pricing/', 'https');
		$action_url = $pricing_url;
		$action_label = __('Go Pro', 'foodord');
		$action_external = true;
		$show_pro_action = !function_exists('foodord_is_license_active') || !foodord_is_license_active();
		?>
		<section class="foodord-admin-dashboard-hero" aria-label="<?php esc_attr_e('FoodOrd dashboard header', 'foodord'); ?>">
			<div class="foodord-admin-dashboard-hero__brand">
				<img class="foodord-admin-dashboard-hero__logo" src="<?php echo esc_url($this->get_dashboard_logo_url()); ?>"
					alt="<?php esc_attr_e('FoodOrd logo', 'foodord'); ?>" />
			</div>
			<div class="foodord-admin-dashboard-hero__actions">
				<a class="foodord-admin-dashboard-hero__button foodord-admin-dashboard-hero__button--ghost foodord-admin-dashboard-external"
					href="<?php echo esc_url($docs_url); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e('Documentation', 'foodord'); ?>
					<span class="foodord-admin-dashboard-external__icon" aria-hidden="true">
						<svg viewBox="0 0 16 16" fill="none">
							<path
								d="M6.25 3.75H4.75C4.05964 3.75 3.5 4.30964 3.5 5V11.25C3.5 11.9404 4.05964 12.5 4.75 12.5H11C11.6904 12.5 12.25 11.9404 12.25 11.25V9.75"
								stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
							<path d="M8.25 3.75H12.25V7.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
								stroke-linejoin="round" />
							<path d="M7 9L12.25 3.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
								stroke-linejoin="round" />
						</svg>
					</span>
				</a>
				<?php if ($show_pro_action): ?>
					<a class="foodord-admin-dashboard-hero__button foodord-admin-dashboard-hero__button--primary foodord-admin-dashboard-hero__button--with-icon"
						href="<?php echo esc_url($action_url); ?>" <?php if ($action_external): ?> target="_blank"
							rel="noopener noreferrer" <?php endif; ?>>
						<span class="foodord-admin-dashboard-hero__button-icon" aria-hidden="true">
							<svg viewBox="0 0 16 16" fill="none">
								<path
									d="M8 2.25L9.70703 5.71094L13.5273 6.26562L10.7637 8.96094L11.416 12.7656L8 10.9688L4.58398 12.7656L5.23633 8.96094L2.47266 6.26562L6.29297 5.71094L8 2.25Z"
									fill="currentColor" />
							</svg>
						</span>
						<?php echo esc_html($action_label); ?>
					</a>
				<?php endif; ?>
			</div>
		</section>
		<?php
	}

	/**
	 * Render dashboard theme compatibility support banner.
	 */
	private function render_dashboard_compatibility_banner(): void
	{
		$contact_url = set_url_scheme('//www.foodord.com/contact-us/', 'https');
		?>
		<section class="foodord-admin-dashboard-compat-banner" aria-labelledby="foodord-dashboard-compat-title">
			<span class="foodord-admin-dashboard-compat-banner__icon dashicons dashicons-admin-appearance" aria-hidden="true"></span>
			<div class="foodord-admin-dashboard-compat-banner__content">
				<h2 id="foodord-dashboard-compat-title" class="foodord-admin-dashboard-compat-banner__title">
					<?php esc_html_e('Theme compatibility help', 'foodord'); ?>
				</h2>
				<p class="foodord-admin-dashboard-compat-banner__text">
					<?php esc_html_e('FoodOrd is designed to work with standard WordPress and WooCommerce themes. If you notice any layout or styling issue with your current theme, our team can help you resolve it.', 'foodord'); ?>
				</p>
			</div>
			<a class="foodord-admin-dashboard-compat-banner__button" href="<?php echo esc_url($contact_url); ?>" target="_blank" rel="noopener noreferrer">
				<?php esc_html_e('Get compatibility help', 'foodord'); ?>
			</a>
		</section>
		<?php
	}

	/**
	 * Retrieve dashboard tutorial videos.
	 *
	 * @return array<int,array<string,string>>
	 */
	private function get_dashboard_videos(): array
	{
		return array(
			array(
				'title' => __('Initial setup walkthrough', 'foodord'),
				'description' => __('Start with the essential setup flow and the main admin structure.', 'foodord'),
				'watch_url' => 'https://youtu.be/5cav8Zqgxd8?si=NAocqJ1fyMXcupaf',
				'embed_url' => 'https://www.youtube-nocookie.com/embed/5cav8Zqgxd8?autoplay=1&rel=0',
				'thumbnail_url' => 'https://i.ytimg.com/vi/5cav8Zqgxd8/hqdefault.jpg',
			),
			array(
				'title' => __('Ordering flow configuration', 'foodord'),
				'description' => __('Review the ordering experience and the key settings used on live stores.', 'foodord'),
				'watch_url' => 'https://youtu.be/qHAjESmthF4?si=6dD44lp4h6CGyb58',
				'embed_url' => 'https://www.youtube-nocookie.com/embed/qHAjESmthF4?autoplay=1&rel=0',
				'thumbnail_url' => 'https://i.ytimg.com/vi/qHAjESmthF4/hqdefault.jpg',
			),
			array(
				'title' => __('Product and storefront basics', 'foodord'),
				'description' => __('Learn how the product experience connects with the storefront layout.', 'foodord'),
				'watch_url' => 'https://youtu.be/6idV7_ad2HA?si=7O25G7-nisTOPNd0',
				'embed_url' => 'https://www.youtube-nocookie.com/embed/6idV7_ad2HA?autoplay=1&rel=0',
				'thumbnail_url' => 'https://i.ytimg.com/vi/6idV7_ad2HA/hqdefault.jpg',
			),
		);
	}

	/**
	 * Render dashboard tutorial section.
	 */
	private function render_dashboard_video_section(): void
	{
		$videos = $this->get_dashboard_videos();
		$channel_url = 'https://www.youtube.com/@foodord';
		?>
		<section class="foodord-admin-dashboard-section foodord-admin-dashboard-section--videos"
			aria-labelledby="foodord-dashboard-videos-title">
			<div class="foodord-admin-dashboard-section__head">
				<div class="foodord-admin-dashboard-section__intro">
					<span class="foodord-admin-dashboard-section__icon dashicons dashicons-video-alt3"
						aria-hidden="true"></span>
					<div class="foodord-admin-dashboard-section__copy">
						<h2 id="foodord-dashboard-videos-title" class="foodord-admin-dashboard-section__title">
							<?php esc_html_e('Video tutorials', 'foodord'); ?></h2>
						<p class="foodord-admin-dashboard-section__description">
							<?php esc_html_e('Three quick videos to help you get started with FoodOrd.', 'foodord'); ?></p>
					</div>
				</div>
				<a class="foodord-admin-dashboard-section__action foodord-admin-dashboard-external"
					href="<?php echo esc_url($channel_url); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e('View More', 'foodord'); ?>
					<span class="foodord-admin-dashboard-external__icon" aria-hidden="true">
						<svg viewBox="0 0 16 16" fill="none">
							<path
								d="M6.25 3.75H4.75C4.05964 3.75 3.5 4.30964 3.5 5V11.25C3.5 11.9404 4.05964 12.5 4.75 12.5H11C11.6904 12.5 12.25 11.9404 12.25 11.25V9.75"
								stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
							<path d="M8.25 3.75H12.25V7.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
								stroke-linejoin="round" />
							<path d="M7 9L12.25 3.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
								stroke-linejoin="round" />
						</svg>
					</span>
				</a>
			</div>
			<div class="foodord-admin-dashboard-videos" data-foodord-dashboard-videos>
				<?php foreach ($videos as $index => $video): ?>
					<article class="foodord-admin-dashboard-video-card">
						<div class="foodord-admin-dashboard-video-card__media">
							<img class="foodord-admin-dashboard-video-card__image"
								src="<?php echo esc_url($video['thumbnail_url']); ?>"
								alt="<?php echo esc_attr($video['title']); ?>" />
							<button type="button" class="foodord-admin-dashboard-video-card__play" data-foodord-video-trigger
								data-foodord-video-embed="<?php echo esc_url($video['embed_url']); ?>"
								data-foodord-video-title="<?php echo esc_attr($video['title']); ?>" <?php /* translators: %d: sequential video number in the dashboard tutorials list. */ ?>
								aria-label="<?php echo esc_attr(sprintf(__('Play video %d', 'foodord'), (int) $index + 1)); ?>">
								<span class="foodord-admin-dashboard-video-card__play-icon" aria-hidden="true"></span>
							</button>
						</div>
						<div class="foodord-admin-dashboard-video-card__body">
							<h3 class="foodord-admin-dashboard-video-card__title"><?php echo esc_html($video['title']); ?></h3>
							<p class="foodord-admin-dashboard-video-card__text"><?php echo esc_html($video['description']); ?></p>
						</div>
					</article>
				<?php endforeach; ?>
			</div>
		</section>

		<div class="foodord-admin-video-modal" data-foodord-video-modal hidden>
			<div class="foodord-admin-video-modal__backdrop" data-foodord-video-close></div>
			<div class="foodord-admin-video-modal__dialog" role="dialog" aria-modal="true"
				aria-labelledby="foodord-admin-video-modal-title">
				<div class="foodord-admin-video-modal__bar">
					<h3 id="foodord-admin-video-modal-title" class="foodord-admin-video-modal__title"></h3>
					<button type="button" class="foodord-admin-video-modal__close" data-foodord-video-close
						aria-label="<?php esc_attr_e('Close video', 'foodord'); ?>">
						<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
					</button>
				</div>
				<div class="foodord-admin-video-modal__frame-wrap">
					<iframe class="foodord-admin-video-modal__frame"
						title="<?php esc_attr_e('FoodOrd tutorial video', 'foodord'); ?>" src="" loading="lazy"
						allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
						referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render dashboard review card.
	 */
	private function render_dashboard_review_section(): void
	{
		$review_url = 'https://wordpress.org/plugins/foodord/#reviews';
		?>
		<section class="foodord-admin-dashboard-section foodord-admin-dashboard-section--review"
			aria-labelledby="foodord-dashboard-review-title">
			<div class="foodord-admin-dashboard-section__head">
				<div class="foodord-admin-dashboard-section__intro">
					<span class="foodord-admin-dashboard-section__icon dashicons dashicons-star-filled"
						aria-hidden="true"></span>
					<div class="foodord-admin-dashboard-section__copy">
						<h2 id="foodord-dashboard-review-title" class="foodord-admin-dashboard-section__title">
							<?php esc_html_e('Enjoying FoodOrd?', 'foodord'); ?></h2>
						<p class="foodord-admin-dashboard-section__description">
							<?php esc_html_e('Your review helps more restaurant owners discover FoodOrd and helps us keep improving the plugin.', 'foodord'); ?>
						</p>
					</div>
				</div>
				<a class="foodord-admin-dashboard-section__action foodord-admin-dashboard-external"
					href="<?php echo esc_url($review_url); ?>" target="_blank" rel="noopener noreferrer">
					<?php esc_html_e('Leave a Review', 'foodord'); ?>
					<span class="foodord-admin-dashboard-external__icon" aria-hidden="true">
						<svg viewBox="0 0 16 16" fill="none">
							<path
								d="M6.25 3.75H4.75C4.05964 3.75 3.5 4.30964 3.5 5V11.25C3.5 11.9404 4.05964 12.5 4.75 12.5H11C11.6904 12.5 12.25 11.9404 12.25 11.25V9.75"
								stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
							<path d="M8.25 3.75H12.25V7.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
								stroke-linejoin="round" />
							<path d="M7 9L12.25 3.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
								stroke-linejoin="round" />
						</svg>
					</span>
				</a>
			</div>
		</section>
		<?php
	}

	/**
	 * Render dashboard support resource cards.
	 */
	private function render_dashboard_resource_cards(): void
	{
		$theme_status = function_exists('foodord_get_theme_admin_status') ? foodord_get_theme_admin_status() : ((defined('FOODORD_THEME_ACTIVE') && FOODORD_THEME_ACTIVE) ? 'active' : 'missing');
		if ('active' === $theme_status) {
			$promo_url = admin_url('admin.php?page=' . $this->get_page_slug('styling'));
			$promo_label = __('Open Styling', 'foodord');
			$promo_badge = __('For Free', 'foodord');
			$promo_external = false;
		} elseif ('installed' === $theme_status) {
			$promo_url = function_exists('foodord_get_theme_activation_url') ? foodord_get_theme_activation_url() : admin_url('themes.php');
			$promo_label = __('Activate Theme', 'foodord');
			$promo_badge = __('Theme Installed', 'foodord');
			$promo_external = false;
		} else {
			$promo_url = function_exists('foodord_get_theme_download_url') ? foodord_get_theme_download_url() : admin_url('themes.php');
			$promo_label = __('Download Free Theme', 'foodord');
			$promo_badge = __('Free Theme', 'foodord');
			$promo_external = true;
		}
		$promo_art_url = plugins_url('admin/images/theme-promo-art.png', FOODORD_FILE);
		$promo_features = array(
			__('Dark mode support', 'foodord'),
			__('Ordering-first mobile layout', 'foodord'),
			__('Matching FoodOrd design ecosystem', 'foodord'),
			__('Fast storefront launch setup', 'foodord'),
		);
		$promo_title = sprintf(
			/* translators: %s is the highlighted "FoodOrd Theme" text. */
			__('Download %s', 'foodord'),
			'<span class="foodord-admin-dashboard-promo__title-accent">' . esc_html__('FoodOrd Theme', 'foodord') . '</span>'
		);
		$resources = array(
			array(
				'icon' => 'dashicons-sos',
				'title' => __('Customer Support', 'foodord'),
				'description' => __('Reach our team for setup help, account questions, and day-to-day store support.', 'foodord'),
				'label' => __('Contact Support', 'foodord'),
				'url' => 'https://www.foodord.com/support/',
			),
			array(
				'icon' => 'dashicons-book-alt',
				'title' => __('Knowledge Base', 'foodord'),
				'description' => __('Use practical guides for setup steps, core features, and day-to-day store work.', 'foodord'),
				'label' => __('Open Docs', 'foodord'),
				'url' => 'https://www.foodord.com/documentation/',
			),
		);
		?>
		<div class="foodord-admin-dashboard-panels" aria-label="<?php esc_attr_e('FoodOrd support resources', 'foodord'); ?>">
			<?php foreach ($resources as $resource): ?>
				<article class="foodord-admin-dashboard-panel">
					<span class="foodord-admin-dashboard-panel__icon dashicons <?php echo esc_attr($resource['icon']); ?>"
						aria-hidden="true"></span>
					<h3 class="foodord-admin-dashboard-panel__title"><?php echo esc_html($resource['title']); ?></h3>
					<p class="foodord-admin-dashboard-panel__text"><?php echo esc_html($resource['description']); ?></p>
					<a class="foodord-admin-dashboard-panel__button foodord-admin-dashboard-external"
						href="<?php echo esc_url($resource['url']); ?>" target="_blank" rel="noopener noreferrer">
						<?php echo esc_html($resource['label']); ?>
						<span class="foodord-admin-dashboard-external__icon" aria-hidden="true">
							<svg viewBox="0 0 16 16" fill="none">
								<path
									d="M6.25 3.75H4.75C4.05964 3.75 3.5 4.30964 3.5 5V11.25C3.5 11.9404 4.05964 12.5 4.75 12.5H11C11.6904 12.5 12.25 11.9404 12.25 11.25V9.75"
									stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
								<path d="M8.25 3.75H12.25V7.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
									stroke-linejoin="round" />
								<path d="M7 9L12.25 3.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
									stroke-linejoin="round" />
							</svg>
						</span>
					</a>
				</article>
			<?php endforeach; ?>
		</div>
		<aside class="foodord-admin-dashboard-promo">
			<span class="foodord-admin-dashboard-promo__badge"><?php echo esc_html($promo_badge); ?></span>
			<span class="foodord-admin-dashboard-promo__icon dashicons dashicons-art" aria-hidden="true"></span>
			<h3 class="foodord-admin-dashboard-promo__title"><?php
				echo wp_kses(
					$promo_title,
					array(
						'span' => array(
							'class' => array(),
						),
					)
				);
				?></h3>
			<p class="foodord-admin-dashboard-promo__text">
				<?php esc_html_e('Use the free storefront theme for built-in dark mode, faster launch setup, and a cleaner ordering experience across every screen.', 'foodord'); ?>
			</p>
			<a class="foodord-admin-dashboard-promo__button" href="<?php echo esc_url($promo_url); ?>" <?php if ($promo_external): ?> target="_blank" rel="noopener noreferrer" <?php endif; ?>>
				<?php echo esc_html($promo_label); ?>
			</a>
			<ul class="foodord-admin-dashboard-promo__list">
				<?php foreach ($promo_features as $feature): ?>
					<li class="foodord-admin-dashboard-promo__item">
						<span class="foodord-admin-dashboard-promo__check dashicons dashicons-yes-alt" aria-hidden="true"></span>
						<span><?php echo esc_html($feature); ?></span>
					</li>
				<?php endforeach; ?>
			</ul>
			<div class="foodord-admin-dashboard-promo__art-wrap" aria-hidden="true">
				<img class="foodord-admin-dashboard-promo__art" src="<?php echo esc_url($promo_art_url); ?>" alt=""
					loading="lazy" />
			</div>
		</aside>
		<?php
	}

	/**
	 * Determine whether we are on a WooCommerce order edit screen.
	 */
	private function is_order_edit_screen(): bool
	{
		if (!is_admin()) {
			return false;
		}

		$screen = function_exists('get_current_screen') ? get_current_screen() : null;
		if ($screen instanceof WP_Screen) {
			if (in_array($screen->id, array('shop_order', 'woocommerce_page_wc-orders'), true)) {
				return true;
			}

			if ('shop_order' === $screen->post_type) {
				return true;
			}
		}

		global $typenow;
		return ('shop_order' === $typenow);
	}

	/**
	 * Bootstrap admin hooks.
	 */
	public function init()
	{
		// Initialize shortcodes handler early so enqueue_scripts can work.
		$this->shortcodes_handler = new Foodord_Shortcodes();


		// Initialize license handler early for admin_post hooks.
		$this->license_handler = new Foodord_License();
		$this->product_layout_handler = new Foodord_Product_Layout();
		if (defined('FOODORD_THEME_ACTIVE') && !FOODORD_THEME_ACTIVE) {
			add_action('admin_menu', array($this, 'register_standalone_menu'), 9);
			add_action('admin_menu', array($this, 'cleanup_standalone_menu'), 99);
		}
		// Run after the theme registers the FoodOrd top-level menu (theme default priority: 10).
		add_action('admin_menu', array($this, 'register_dashboard_submenu'), 11);
		add_action('admin_menu', array($this, 'register_settings_hub_submenu'), 22);
		add_action('admin_menu', array($this, 'register_styling_submenu'), 12);
		add_action('admin_menu', array($this, 'register_license_submenu'), 11);
		add_action('admin_menu', array($this, 'register_delivery_submenu'), 13);
		add_action('admin_menu', array($this, 'register_pickup_submenu'), 14);
		add_action('admin_menu', array($this, 'register_toppings_submenu'), 16);
		add_action('admin_menu', array($this, 'register_integrations_submenu'), 21);
		add_action('admin_menu', array($this, 'register_shortcodes_submenu'), 20);
		add_action('admin_menu', array($this, 'register_layout_submenu'), 15);
		add_action('admin_menu', array($this, 'register_pro_teaser_submenus'), 30);
		add_action('admin_menu', array($this, 'prioritize_dashboard_submenu'), 999);
		add_action('admin_menu', array($this, 'register_upgrade_menu_cta'), 1000);
		add_action('admin_menu', array($this, 'organize_foodord_submenu'), 1001);
		add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
		add_filter('admin_body_class', array($this, 'filter_admin_body_class'));
		add_filter('submenu_file', array($this, 'filter_foodord_submenu_file'), 10, 2);
		add_filter('woocommerce_hidden_order_itemmeta', array($this, 'hide_order_item_internal_meta'));
		add_action('admin_head', array($this, 'hide_admin_order_item_details'));
		add_action('current_screen', array($this, 'maybe_register_help_tab'), 10, 1);
		add_action('admin_post_foodord_save_diagnostics_preferences', array($this, 'handle_diagnostics_preferences_save'));
		add_filter('plugin_action_links_' . plugin_basename(FOODORD_FILE), array($this, 'add_plugin_action_links'));
		add_filter('plugin_row_meta', array($this, 'add_plugin_row_meta'), 10, 2);
		add_action('admin_footer', array($this, 'render_plugins_page_optin_modal'));
	}

	/**
	 * Add custom links to the plugin meta row.
	 *
	 * @param array  $links Array of plugin meta links.
	 * @param string $file  Plugin file.
	 * @return array
	 */
	public function add_plugin_row_meta($links, $file)
	{
		if (plugin_basename(FOODORD_FILE) === $file) {
			$video_link = sprintf(
				'<a href="%s" target="_blank">%s</a>',
				esc_url('https://www.youtube.com/@foodord'),
				esc_html__('Video Tutorials', 'foodord')
			);
			$links['video_tutorials'] = $video_link;
		}

		return $links;
	}

	/**
	 * Add custom links to the plugin action links.
	 *
	 * @param array $links Array of action links.
	 * @return array
	 */
	public function add_plugin_action_links($links)
	{
		$settings_url = admin_url('admin.php?page=' . $this->get_page_slug('settings_hub'));
		$settings_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url($settings_url),
			esc_html__('Settings', 'foodord')
		);

		$go_pro_url = 'https://www.foodord.com/pricing/';
		$go_pro_link = sprintf(
			'<a href="%s" class="foodord-plugin-action-link foodord-plugin-action-link--pro" target="_blank" rel="noopener noreferrer">%s</a>',
			esc_url($go_pro_url),
			esc_html__('Go Pro', 'foodord')
		);

		$is_tracking_allowed = false;
		if (class_exists('Foodord_Diagnostics')) {
			$is_tracking_allowed = Foodord_Diagnostics::is_enabled();
		} else {
			$is_tracking_allowed = 'yes' === get_option(self::OPTION_ALLOW_TRACKING, 'no');
		}

		$optin_text = $is_tracking_allowed ? __('Opt-out', 'foodord') : __('Opt-in', 'foodord');

		$privacy_link = sprintf(
			'<a href="#" class="foodord-optin-modal-trigger">%s</a>',
			esc_html($optin_text)
		);

		array_unshift($links, $settings_link);
		$links['foodord_privacy'] = $privacy_link;
		
		$is_license_active = 'active' === get_option('foodord_license_status', 'inactive');
		if (! $is_license_active) {
			$links['go_pro'] = $go_pro_link;
		}

		return $links;
	}

	/**
	 * Render the opt-in modal on the plugins page.
	 */
	public function render_plugins_page_optin_modal()
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		global $pagenow;
		if ('plugins.php' !== $pagenow) {
			return;
		}

		$is_tracking_allowed = false;
		if (class_exists('Foodord_Diagnostics')) {
			$is_tracking_allowed = Foodord_Diagnostics::is_enabled();
		} else {
			$is_tracking_allowed = 'yes' === get_option(self::OPTION_ALLOW_TRACKING, 'no');
		}

		$form_action = admin_url('admin-post.php');
		$new_status = $is_tracking_allowed ? 'no' : 'yes';

		?>
		<dialog id="foodord-optin-modal" class="foodord-optin-modal">
			<div class="foodord-optin-modal__content">
				<h3 class="foodord-optin-modal__title">
					<?php esc_html_e('Help us!', 'foodord'); ?></h3>
				<p class="foodord-optin-modal__description">
					<?php esc_html_e('Help us improve FoodOrd by sharing anonymous diagnostic data. We only collect technical environment details (like PHP/WP versions).', 'foodord'); ?>
				</p>
				<p class="foodord-optin-modal__notice">
					<?php esc_html_e('We never collect customer, order, payment or personal data.', 'foodord'); ?>
				</p>

				<div class="foodord-optin-modal__status">
					<span class="foodord-optin-modal__status-label"><?php esc_html_e('Current Status:', 'foodord'); ?></span>
					<?php if ($is_tracking_allowed): ?>
						<span class="foodord-optin-modal__status-value foodord-optin-modal__status-value--enabled"><?php esc_html_e('Sharing Enabled', 'foodord'); ?></span>
					<?php else: ?>
						<span class="foodord-optin-modal__status-value foodord-optin-modal__status-value--disabled"><?php esc_html_e('Sharing Disabled', 'foodord'); ?></span>
					<?php endif; ?>
				</div>

				<form class="foodord-optin-modal__form" method="post" action="<?php echo esc_url($form_action); ?>">
					<?php wp_nonce_field('foodord_save_diagnostics_preferences'); ?>
					<input class="foodord-optin-modal__input foodord-optin-modal__input--action" type="hidden" name="action" value="foodord_save_diagnostics_preferences">
					<input class="foodord-optin-modal__input foodord-optin-modal__input--status" type="hidden" name="foodord_allow_tracking" value="<?php echo esc_attr($new_status); ?>">

					<button type="button" class="button" data-foodord-optin-modal-close><?php esc_html_e('Cancel', 'foodord'); ?></button>
					<?php if ($is_tracking_allowed): ?>
						<button type="submit" class="button"><?php esc_html_e('Stop Sharing', 'foodord'); ?></button>
					<?php else: ?>
						<button type="submit" class="button button-primary foodord-optin-modal__allow-button"><?php esc_html_e('Allow Sharing', 'foodord'); ?></button>
					<?php endif; ?>
				</form>
			</div>
			</dialog>
			<?php
		}

	/**
	 * Add dashboard-specific admin body classes.
	 *
	 * @param string $classes Existing body classes.
	 */
	public function filter_admin_body_class($classes): string
	{
		$page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		if (!is_string($page)) {
			return is_string($classes) ? $classes : '';
		}

		$dashboard_slugs = function_exists('foodord_get_settings_page_slugs')
			? foodord_get_settings_page_slugs('dashboard')
			: array($this->get_page_slug('dashboard'), 'foodord-theme-settings-dashboard', 'foodord-dashboard');

		$dashboard_slugs[] = $this->get_settings_parent_slug();
		$dashboard_slugs = array_filter(array_unique($dashboard_slugs));

		if (in_array($page, $dashboard_slugs, true)) {
			$classes = is_string($classes) ? trim($classes) : '';
			$classes .= ' foodord-admin-dashboard-screen';
		}

		return is_string($classes) ? $classes : '';
	}

	/**
	 * Save diagnostics preferences from the Help tab.
	 */
	public function handle_diagnostics_preferences_save(): void
	{
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('You do not have permission to update FoodOrd diagnostics preferences.', 'foodord'));
		}

		check_admin_referer('foodord_save_diagnostics_preferences');

		$allow_tracking = filter_input(INPUT_POST, 'foodord_allow_tracking', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		if (class_exists('Foodord_Diagnostics')) {
			Foodord_Diagnostics::update_preference('yes' === $allow_tracking);
		} else {
			update_option(self::OPTION_ALLOW_TRACKING, 'yes' === $allow_tracking ? 'yes' : 'no');
		}

		$redirect_url = wp_get_referer();
		if (!is_string($redirect_url) || '' === $redirect_url) {
			$redirect_url = admin_url('admin.php?page=' . $this->get_settings_parent_slug());
		}

		$redirect_url = remove_query_arg('foodord_diagnostics_updated', $redirect_url);
		wp_safe_redirect(add_query_arg('foodord_diagnostics_updated', '1', $redirect_url));
		exit;
	}

	/**
	 * Retrieve mapping of FoodOrd Pro admin pages used for teaser menus.
	 *
	 * @return array<string,string>
	 */
	private function get_pro_teaser_pages(): array
	{
		return array(
			'foodord-pro-tipping' => __('Tipping', 'foodord'),
			'foodord-pro-loyalty' => __('Loyalty', 'foodord'),
			'foodord-pro-pricing' => __('Pricing Rules', 'foodord'),
			'foodord-pro-reviews' => __('Reviews', 'foodord'),
		);
	}

	/**
	 * Retrieve the grouped pages shown in the Settings hub.
	 *
	 * @return array<int,array{
	 *     id: string,
	 *     title: string,
	 *     items: array<int,array{
	 *         slug: string,
	 *         label: string
	 *     }>
	 * }>
	 */
	private function get_settings_hub_groups(): array
	{
		return array(
			array(
				'id' => 'ordering',
				'title' => __('Ordering', 'foodord'),
				'items' => array(
					array(
						'slug' => $this->get_page_slug('delivery'),
						'label' => __('Delivery', 'foodord'),
					),
					array(
						'slug' => $this->get_page_slug('pickup'),
						'label' => __('Pickup', 'foodord'),
					),
				),
			),
			array(
				'id' => 'menu',
				'title' => __('Menu', 'foodord'),
				'items' => array(
					array(
						'slug' => $this->get_page_slug('toppings'),
						'label' => __('Toppings', 'foodord'),
					),
					array(
						'slug' => $this->get_page_slug('topping_sets'),
						'label' => __('Topping Sets', 'foodord'),
					),
					array(
						'slug' => 'edit.php?post_type=foodord_timed',
						'label' => __('Timed Products', 'foodord'),
					),
				),
			),
			array(
				'id' => 'appearance',
				'title' => __('Appearance', 'foodord'),
				'items' => array(
					array(
						'slug' => $this->get_page_slug('styling'),
						'label' => __('Styling', 'foodord'),
					),
					array(
						'slug' => $this->get_page_slug('layout'),
						'label' => __('Layout', 'foodord'),
					),
					array(
						'slug' => $this->get_page_slug('home_banner'),
						'label' => __('Home Banner', 'foodord'),
					),
					array(
						'slug' => $this->get_page_slug('cookie_law'),
						'label' => __('Cookie Law', 'foodord'),
					),
				),
			),
			array(
				'id' => 'advanced',
				'title' => __('Advanced', 'foodord'),
				'items' => array(
					array(
						'slug' => $this->get_page_slug('tweaks'),
						'label' => __('Tweaks', 'foodord'),
					),
					array(
						'slug' => $this->get_page_slug('shortcodes'),
						'label' => __('Shortcodes', 'foodord'),
					),
					array(
						'slug' => $this->get_page_slug('integrations'),
						'label' => __('Integrations', 'foodord'),
					),
				),
			),
			array(
				'id' => 'pro-features',
				'title' => __('Pro Features', 'foodord'),
				'items' => array(
					array(
						'slug' => 'foodord-pro-tipping',
						'label' => __('Tipping', 'foodord'),
					),
					array(
						'slug' => 'foodord-pro-loyalty',
						'label' => __('Loyalty', 'foodord'),
					),
					array(
						'slug' => 'foodord-pro-pricing',
						'label' => __('Pricing Rules', 'foodord'),
					),
					array(
						'slug' => 'foodord-pro-reviews',
						'label' => __('Reviews', 'foodord'),
					),
				),
			),
		);
	}

	/**
	 * Retrieve the registered submenu entries under FoodOrd.
	 *
	 * @return array<string,array<int,mixed>>
	 */
	private function get_registered_foodord_submenu_entries(): array
	{
		$parent_slug = $this->get_settings_parent_slug();

		global $submenu;
		if (!isset($submenu[$parent_slug]) || !is_array($submenu[$parent_slug])) {
			return array();
		}

		$entries = array();
		foreach ($submenu[$parent_slug] as $entry) {
			if (!is_array($entry) || !isset($entry[2])) {
				continue;
			}

			$slug = (string) $entry[2];
			if ('' !== $slug) {
				$entries[$slug] = $entry;
			}
		}

		return $entries;
	}

	/**
	 * Build an admin URL for a registered FoodOrd submenu entry.
	 *
	 * @param string $slug Registered submenu slug.
	 */
	private function get_foodord_submenu_url(string $slug): string
	{
		if (0 === strpos($slug, 'edit.php')) {
			return admin_url($slug);
		}

		return admin_url('admin.php?page=' . rawurlencode($slug));
	}

	/**
	 * Register teaser submenu items for FoodOrd Pro features when Pro is not active.
	 */
	public function register_pro_teaser_submenus()
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		if ($this->is_pro_active()) {
			return;
		}

		$parent_slug = $this->get_settings_parent_slug();
		$pages = $this->get_pro_teaser_pages();

		foreach ($pages as $slug => $label) {
			$menu_title = sprintf(
				'%1$s <span class="foodord-admin-badge foodord-admin-badge--pro">%2$s</span>',
				esc_html($label),
				esc_html__('PRO', 'foodord')
			);

			add_submenu_page(
				$parent_slug,
				$label,
				$menu_title,
				'manage_options',
				$slug,
				array($this, 'render_pro_teaser_page')
			);
		}
	}

	/**
	 * Add the FoodOrd Upgrade CTA to the bottom of the left admin submenu.
	 */
	public function register_upgrade_menu_cta(): void
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		if (function_exists('foodord_is_license_active') && foodord_is_license_active()) {
			return;
		}

		$parent_slug = $this->get_settings_parent_slug();
		$pricing_url = 'https://www.foodord.com/pricing/';

		global $submenu;
		if (!isset($submenu[$parent_slug]) || !is_array($submenu[$parent_slug])) {
			return;
		}

		$submenu[$parent_slug] = array_values(
			array_filter(
				$submenu[$parent_slug],
				static function ($entry) use ($pricing_url): bool {
					return !is_array($entry) || !isset($entry[2]) || $pricing_url !== (string) $entry[2];
				}
			)
		);

		$submenu[$parent_slug][] = array(
			__('Upgrade', 'foodord'),
			'manage_options',
			$pricing_url,
			__('Upgrade', 'foodord'),
			'foodord-admin-menu-upgrade',
		);
	}

	/**
	 * Register contextual help tab on FoodOrd related screens.
	 *
	 * @param WP_Screen $screen Current screen.
	 */
	public function maybe_register_help_tab($screen): void
	{
		if (!current_user_can('manage_options')) {
			return;
		}
		if (!$screen instanceof WP_Screen) {
			return;
		}

		if ($this->is_setup_wizard_screen($screen)) {
			return;
		}

		if (!$this->is_foodord_help_screen($screen)) {
			return;
		}

		$this->add_help_tabs($screen);
	}

	/**
	 * Register help tabs for current screen (used by load- hooks).
	 */
	public function add_help_tabs_on_load(): void
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		if (!function_exists('get_current_screen')) {
			return;
		}

		$screen = get_current_screen();
		if (!$screen instanceof WP_Screen) {
			return;
		}

		if ($this->is_setup_wizard_screen($screen)) {
			return;
		}

		$this->add_help_tabs($screen);
	}

	/**
	 * Add FoodOrd help tabs to a screen.
	 *
	 * @param WP_Screen $screen Current screen.
	 */
	private function add_help_tabs(WP_Screen $screen): void
	{
		if (method_exists($screen, 'get_help_tab') && $screen->get_help_tab('foodord_help_setup')) {
			return;
		}

		$screen->add_help_tab(
			array(
				'id' => 'foodord_help_setup',
				'title' => __('Setup Wizard', 'foodord'),
				'priority' => 10,
				'content' => $this->get_help_tab_setup_content(),
			)
		);

		$screen->add_help_tab(
			array(
				'id' => 'foodord_help_documentation',
				'title' => __('Documentation', 'foodord'),
				'priority' => 20,
				'content' => $this->get_help_tab_documentation_content(),
			)
		);

		$screen->add_help_tab(
			array(
				'id' => 'foodord_help_support',
				'title' => __('Support', 'foodord'),
				'priority' => 30,
				'content' => $this->get_help_tab_support_content(),
			)
		);

		$screen->add_help_tab(
			array(
				'id' => 'foodord_help_diagnostics',
				'title' => __('Diagnostics', 'foodord'),
				'priority' => 40,
				'content' => $this->get_help_tab_diagnostics_content(),
			)
		);

		$screen->set_help_sidebar($this->get_help_sidebar_content());
	}

	/**
	 * Determine whether this is a FoodOrd related admin screen.
	 *
	 * @param WP_Screen $screen Current screen.
	 */
	private function is_foodord_help_screen($screen): bool
	{
		if (!$screen instanceof WP_Screen) {
			return false;
		}

		$screen_id = isset($screen->id) ? (string) $screen->id : '';
		if ('' === $screen_id) {
			return false;
		}

		$screen_post_type = isset($screen->post_type) ? (string) $screen->post_type : '';
		if ('' !== $screen_post_type && class_exists('Foodord_Timed_Products')) {
			if (Foodord_Timed_Products::POST_TYPE === $screen_post_type) {
				return true;
			}
		}

		if (false !== strpos($screen_id, 'foodord-settings')) {
			return true;
		}

		if (false !== strpos($screen_id, 'foodord-theme-settings')) {
			return true;
		}

		if (false !== strpos($screen_id, 'foodord-pro-')) {
			return true;
		}

		if (false !== strpos($screen_id, 'foodord_page_')) {
			return true;
		}

		if (false !== strpos($screen_id, 'toplevel_page_foodord')) {
			return true;
		}

		return false;
	}

	/**
	 * Determine whether the current screen is the FoodOrd setup wizard.
	 *
	 * @param WP_Screen $screen Current screen.
	 */
	private function is_setup_wizard_screen($screen): bool
	{
		if (!$screen instanceof WP_Screen) {
			return false;
		}

		$screen_id = isset($screen->id) ? (string) $screen->id : '';
		$base = isset($screen->base) ? (string) $screen->base : '';

		if (false !== strpos($screen_id, 'foodord-setup')) {
			return true;
		}

		if (false !== strpos($base, 'foodord-setup')) {
			return true;
		}

		return false;
	}

	/**
	 * Build help tab content.
	 */
	private function get_help_tab_setup_content(): string
	{
		$theme_download_url = function_exists('foodord_get_theme_download_url')
			? foodord_get_theme_download_url()
			: 'https://www.foodord.com/downloads/';
		$show_theme_cta = !(defined('FOODORD_THEME_ACTIVE') && FOODORD_THEME_ACTIVE);

		ob_start();
		?>
		<p class="foodord-help__text">
			<?php esc_html_e('Run the setup wizard to import demo content and create an Order Page.', 'foodord'); ?>
		</p>
		<form class="foodord-help__form" method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>">
			<input class="foodord-help__input" type="hidden" name="page" value="foodord-setup" />
			<button type="submit" class="button button-primary"><?php esc_html_e('Run Setup Wizard', 'foodord'); ?></button>
		</form>
		<?php if ($show_theme_cta): ?>
			<hr />
			<p class="foodord-help__text">
				<?php esc_html_e('Want the full storefront layout? Download the optional FoodOrd Theme and install it from Appearance > Themes > Add New > Upload Theme.', 'foodord'); ?>
			</p>
			<form class="foodord-help__form" method="get" action="<?php echo esc_url($theme_download_url); ?>" target="_blank">
				<button type="submit" class="button"><?php esc_html_e('Download Theme', 'foodord'); ?></button>
			</form>
		<?php endif; ?>
		<?php
		$content = ob_get_clean();
		return is_string($content) ? $content : '';
	}

	/**
	 * Build documentation tab content.
	 */
	private function get_help_tab_documentation_content(): string
	{
		$docs_url = set_url_scheme('//www.foodord.com/documentation/', 'https');
		ob_start();
		?>
		<p class="foodord-help__text">
			<?php esc_html_e('Browse the documentation for setup, configuration, and usage guides.', 'foodord'); ?>
		</p>
		<form class="foodord-help__form" method="get" action="<?php echo esc_url($docs_url); ?>" target="_blank">
			<button type="submit" class="button button-primary"><?php esc_html_e('Open Documentation', 'foodord'); ?></button>
		</form>
		<p class="foodord-help__text"><a class="foodord-help__link" href="<?php echo esc_url($docs_url); ?>" target="_blank"
				rel="noopener noreferrer"><?php esc_html_e('Documentation link', 'foodord'); ?></a></p>
		<?php
		$content = ob_get_clean();
		return is_string($content) ? $content : '';
	}

	/**
	 * Build support tab content.
	 */
	private function get_help_tab_support_content(): string
	{
		$support_url = set_url_scheme('//www.foodord.com/support/', 'https');
		ob_start();
		?>
		<p class="foodord-help__text"><?php esc_html_e('Need assistance? Contact FoodOrd support.', 'foodord'); ?></p>
		<form class="foodord-help__form" method="get" action="<?php echo esc_url($support_url); ?>" target="_blank">
			<button type="submit" class="button button-primary"><?php esc_html_e('Open Support', 'foodord'); ?></button>
		</form>
		<p class="foodord-help__text"><a class="foodord-help__link" href="<?php echo esc_url($support_url); ?>" target="_blank"
				rel="noopener noreferrer"><?php esc_html_e('Support link', 'foodord'); ?></a></p>
		<?php
		$content = ob_get_clean();
		return is_string($content) ? $content : '';
	}

	/**
	 * Build diagnostics tab content.
	 */
	private function get_help_tab_diagnostics_content(): string
	{
		$allow_tracking = class_exists('Foodord_Diagnostics')
			? Foodord_Diagnostics::has_explicit_consent()
			: 'yes' === (string) get_option(self::OPTION_ALLOW_TRACKING, '');
		$updated = '1' === filter_input(INPUT_GET, 'foodord_diagnostics_updated', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

		ob_start();
		?>
		<?php if ($updated): ?>
			<p class="foodord-help__text"><strong><?php esc_html_e('Diagnostics settings saved.', 'foodord'); ?></strong></p>
		<?php endif; ?>
		<p class="foodord-help__text">
			<?php esc_html_e('Help us improve FoodOrd by sharing technical environment and compatibility data.', 'foodord'); ?>
		</p>
		<p class="foodord-help__text">
			<?php esc_html_e('No customer, order, payment, product, or personal customer data is collected.', 'foodord'); ?>
		</p>
		<form class="foodord-help__form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
			<?php wp_nonce_field('foodord_save_diagnostics_preferences'); ?>
			<input class="foodord-help__input" type="hidden" name="action" value="foodord_save_diagnostics_preferences" />
			<label class="foodord-help__label" for="foodord-help-diagnostics-tracking">
				<input id="foodord-help-diagnostics-tracking" class="foodord-help__checkbox" type="checkbox"
					name="foodord_allow_tracking" value="yes" <?php checked($allow_tracking); ?> />
				<span><?php esc_html_e('Share diagnostic data', 'foodord'); ?></span>
			</label>
			<button type="submit" class="button button-primary"><?php esc_html_e('Save changes', 'foodord'); ?></button>
		</form>
		<?php
		$content = ob_get_clean();
		return is_string($content) ? $content : '';
	}

	/**
	 * Build help sidebar content.
	 */
	private function get_help_sidebar_content(): string
	{
		$docs_url = set_url_scheme('//www.foodord.com/documentation/', 'https');
		$support_url = set_url_scheme('//www.foodord.com/support/', 'https');

		return '<p class="foodord-help__sidebar-title"><strong class="foodord-help__sidebar-title-text">' . esc_html__('FoodOrd', 'foodord') . '</strong></p>'
			. '<p class="foodord-help__sidebar-item"><a class="foodord-help__sidebar_link" href="' . esc_url($docs_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Documentation', 'foodord') . '</a></p>'
			. '<p class="foodord-help__sidebar-item"><a class="foodord-help__sidebar_link" href="' . esc_url($support_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Support', 'foodord') . '</a></p>';
	}

	/**
	 * Register Dashboard submenu to existing Theme Settings menu.
	 */
	public function register_dashboard_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Dashboard', 'foodord'),
				__('Dashboard', 'foodord'),
				'manage_options',
				$this->get_page_slug('dashboard'),
				array($this, 'render_dashboard_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register the central Settings hub.
	 */
	public function register_settings_hub_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Settings', 'foodord'),
				__('Settings', 'foodord'),
				'manage_options',
				$this->get_page_slug('settings_hub'),
				array($this, 'render_settings_hub_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register Styling submenu to existing Theme Settings menu.
	 */
	public function register_styling_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Styling', 'foodord'),
				__('Styling', 'foodord'),
				'manage_options',
				$this->get_page_slug('styling'),
				array($this, 'render_styling_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register License submenu to existing Theme Settings menu.
	 */
	public function register_license_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('License', 'foodord'),
				__('License', 'foodord'),
				'manage_options',
				$this->get_page_slug('license'),
				array($this, 'render_license_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register Delivery submenu to existing Theme Settings menu.
	 */
	public function register_delivery_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Delivery', 'foodord'),
				__('Delivery', 'foodord'),
				'manage_options',
				$this->get_page_slug('delivery'),
				array($this, 'render_delivery_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register Pickup submenu to existing Theme Settings menu.
	 */
	public function register_pickup_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Pickup', 'foodord'),
				__('Pickup', 'foodord'),
				'manage_options',
				$this->get_page_slug('pickup'),
				array($this, 'render_pickup_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register Toppings submenu to existing Theme Settings menu.
	 */
	public function register_toppings_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Toppings', 'foodord'),
				__('Toppings', 'foodord'),
				'manage_options',
				$this->get_page_slug('toppings'),
				array($this, 'render_toppings_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register Layout submenu for selecting product card layouts.
	 */
	public function register_layout_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Layout', 'foodord'),
				__('Layout', 'foodord'),
				'manage_options',
				$this->get_page_slug('layout'),
				array($this, 'render_layout_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Register only the Shortcodes submenu to existing Theme Settings menu.
	 */
	public function register_shortcodes_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Shortcodes', 'foodord'),
				__('Shortcodes', 'foodord'),
				'manage_options',
				$this->get_page_slug('shortcodes'),
				array($this, 'render_shortcodes_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}


	/**
	 * Register Integrations submenu to existing Theme Settings menu.
	 */
	public function register_integrations_submenu()
	{
		if (current_user_can('manage_options')) {
			$hook_suffix = add_submenu_page(
				$this->get_settings_parent_slug(),
				__('Integrations', 'foodord'),
				__('Integrations', 'foodord'),
				'manage_options',
				$this->get_page_slug('integrations'),
				array($this, 'render_integrations_page')
			);
			if (is_string($hook_suffix) && '' !== $hook_suffix) {
				add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
			}
		}
	}

	/**
	 * Render the Dashboard page.
	 */
	public function render_dashboard_page()
	{
		if (!current_user_can('manage_options')) {
			return;
		}
		?>
		<div class="wrap">
			<?php $this->render_dashboard_header(); ?>
			<h1 class="screen-reader-text"><?php esc_html_e('Dashboard', 'foodord'); ?></h1>
			<?php
			if (function_exists('foodord_admin_render_horizontal_menu')) {
				foodord_admin_render_horizontal_menu();
			}
			?>
			<div class="foodord-admin-dashboard-overview">
				<?php $this->render_dashboard_compatibility_banner(); ?>
				<?php $this->render_dashboard_resource_cards(); ?>
				<?php $this->render_dashboard_video_section(); ?>
				<?php $this->render_dashboard_review_section(); ?>
			</div>
			<?php
			if (function_exists('foodord_admin_render_faq_section')) {
				foodord_admin_render_faq_section('dashboard');
			}
			?>
		</div>
		<?php
	}

	/**
	 * Render the central Settings hub.
	 */
	public function render_settings_hub_page()
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		$registered_entries = $this->get_registered_foodord_submenu_entries();
		$groups = $this->get_settings_hub_groups();
		?>
		<div class="wrap foodord-settings-hub">
			<h1 class="foodord-settings-hub__title"><?php esc_html_e('Settings', 'foodord'); ?></h1>
			<div class="foodord-settings-hub__content">
				<?php foreach ($groups as $group): ?>
					<?php
					$available_items = array();
					foreach ($group['items'] as $item) {
						if (!isset($registered_entries[$item['slug']])) {
							continue;
						}

						$entry = $registered_entries[$item['slug']];
						$capability = isset($entry[1]) ? (string) $entry[1] : '';
						if ('' !== $capability && !current_user_can($capability)) {
							continue;
						}

						$available_items[] = $item;
					}

					if (empty($available_items)) {
						continue;
					}
					?>
					<section class="foodord-settings-hub__group"
						aria-labelledby="<?php echo esc_attr('foodord-settings-group-' . $group['id']); ?>">
						<header class="foodord-settings-hub__group-header">
							<h2 id="<?php echo esc_attr('foodord-settings-group-' . $group['id']); ?>"
								class="foodord-settings-hub__group-title">
								<?php echo esc_html($group['title']); ?>
							</h2>
						</header>
						<div class="foodord-settings-hub__items">
							<?php foreach ($available_items as $item): ?>
								<a class="foodord-settings-hub__item"
									href="<?php echo esc_url($this->get_foodord_submenu_url($item['slug'])); ?>">
									<span class="foodord-settings-hub__item-title"><?php echo esc_html($item['label']); ?></span>
									<span class="foodord-settings-hub__item-arrow dashicons dashicons-arrow-right-alt2"
										aria-hidden="true"></span>
								</a>
							<?php endforeach; ?>
						</div>
					</section>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the Shortcodes settings page.
	 */
	public function render_shortcodes_page()
	{
		$this->shortcodes_handler->render_shortcodes_page();
	}

	/**
	 * Render the Layout settings page.
	 */
	public function render_layout_page()
	{
		if ($this->product_layout_handler instanceof Foodord_Product_Layout) {
			$this->product_layout_handler->render_page();
		}
	}

	/**
	 * Render the Styling settings page.
	 */
	public function render_styling_page()
	{
		$styling_handler = new Foodord_Styling();
		$styling_handler->render_page();
	}

	/**
	 * Render a simple placeholder page for FoodOrd Pro teaser menus.
	 */
	public function render_pro_teaser_page()
	{
		if (!current_user_can('manage_options')) {
			return;
		}

		$page_slug = '';
		$page_raw = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		if (is_string($page_raw)) {
			$page_slug = sanitize_text_field($page_raw);
		}

		// Map page slugs to template files
		$template_map = array(
			'foodord-pro-tipping' => 'tipping.php',
			'foodord-pro-loyalty' => 'loyalty.php',
			'foodord-pro-pricing' => 'pricing.php',
			'foodord-pro-reviews' => 'reviews.php',
		);

		$teaser_images_url = plugin_dir_url(__FILE__) . 'images/teaser/';

		if (isset($template_map[$page_slug])) {
			$template_file = plugin_dir_path(__FILE__) . 'templates/teasers/' . $template_map[$page_slug];
			if (file_exists($template_file)) {
				include $template_file;
				return;
			}
		}

		$pages = $this->get_pro_teaser_pages();
		$title = isset($pages[$page_slug]) ? $pages[$page_slug] : __('FoodOrd Pro', 'foodord');
		?>
		<div class="wrap foodord-pro-teaser-page">
			<h1 class="wp-heading-inline"><?php echo esc_html($title); ?></h1>
			<?php
			if (function_exists('foodord_admin_render_horizontal_menu')) {
				foodord_admin_render_horizontal_menu();
			}
			?>
		</div>
		<?php
	}

	/**
	 * Enqueue admin scripts and styles.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_admin_scripts($hook)
	{
		if (current_user_can('manage_options')) {
			wp_enqueue_style(
				'foodord-admin-menu',
				plugin_dir_url(__FILE__) . 'css/foodord-admin-menu.css',
				array(),
				FOODORD_VERSION
			);
			wp_enqueue_script(
				'foodord-admin-menu',
				plugin_dir_url(__FILE__) . 'js/foodord-admin-menu.js',
				array(),
				FOODORD_VERSION,
				true
			);
		}

		if ('plugins.php' === $hook) {
			wp_enqueue_style(
				'wrc-admin',
				plugin_dir_url(__FILE__) . 'css/wrc-admin.css',
				array(),
				FOODORD_VERSION
			);
			wp_enqueue_script(
				'foodord-optin-modal',
				plugin_dir_url(__FILE__) . 'js/foodord-optin-modal.js',
				array(),
				FOODORD_VERSION,
				true
			);
		}

		if ($this->should_enqueue_shared_admin_assets($hook)) {
			wp_enqueue_style(
				'foodord-admin-nav',
				plugin_dir_url(__FILE__) . 'css/foodord-admin-nav.css',
				array(),
				FOODORD_VERSION
			);
			wp_enqueue_script(
				'foodord-admin-nav',
				plugin_dir_url(__FILE__) . 'js/foodord-admin-nav.js',
				array(),
				FOODORD_VERSION,
				true
			);
		}

		if ($this->is_hook_for_page($hook, 'dashboard')) {
			wp_enqueue_style(
				'foodord-admin-faq',
				plugin_dir_url(__FILE__) . 'css/foodord-admin-faq.css',
				array(),
				FOODORD_VERSION
			);
			wp_enqueue_script(
				'foodord-dashboard',
				plugin_dir_url(__FILE__) . 'js/foodord-dashboard.js',
				array(),
				FOODORD_VERSION,
				true
			);
		}

		if ($this->is_hook_for_page($hook, 'settings_hub')) {
			wp_enqueue_style(
				'foodord-settings-hub',
				plugin_dir_url(__FILE__) . 'css/foodord-settings-hub.css',
				array('foodord-admin-nav'),
				FOODORD_VERSION
			);
		}

		// Only load on styling page.
		if ($this->is_hook_for_page($hook, 'styling')) {
			wp_enqueue_style('wp-color-picker');
			wp_enqueue_script(
				'foodord-styling',
				plugin_dir_url(__FILE__) . 'js/foodord-styling.js',
				array('wp-color-picker'),
				FOODORD_VERSION,
				true
			);
		}

		// Only load on toppings page.
		if ($this->is_hook_for_page($hook, 'toppings')) {
			// Enqueue jQuery UI Sortable.
			wp_enqueue_script('jquery-ui-sortable');

			// Enqueue custom sortable script.
			wp_enqueue_script(
				'foodord-topping-items-sortable',
				plugin_dir_url(__FILE__) . 'js/foodord-topping-items-sortable.js',
				array('jquery', 'jquery-ui-sortable'),
				FOODORD_VERSION,
				true
			);
		}

		// Only load on delivery page.
		if ($this->is_hook_for_page($hook, 'delivery')) {
			// Enqueue delivery script.
			wp_enqueue_script(
				'foodord-delivery',
				plugin_dir_url(__FILE__) . 'js/foodord-delivery.js',
				array('jquery'),
				FOODORD_VERSION,
				true
			);
			$language = class_exists('Foodord_Location_Service') ? Foodord_Location_Service::get_google_maps_language('admin') : '';
			wp_localize_script(
				'foodord-delivery',
				'foodordDeliveryVars',
				array(
					'google_maps_language' => $language,
				)
			);
		}

		// Only load on pickup page.
		if ($this->is_hook_for_page($hook, 'pickup')) {
			// Enqueue pickup script.
			wp_enqueue_script(
				'foodord-pickup',
				plugin_dir_url(__FILE__) . 'js/foodord-pickup.js',
				array('jquery'),
				FOODORD_VERSION,
				true
			);
		}

		// Load teaser specific styles.
		$teaser_pages = $this->get_pro_teaser_pages();
		$current_page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		if ($current_page && isset($teaser_pages[$current_page])) {
			wp_enqueue_style(
				'foodord-pro-teaser',
				plugin_dir_url(__FILE__) . 'css/foodord-pro-teaser.css',
				array(),
				FOODORD_VERSION
			);
		}

		// Only load on integrations page.
		if ($this->is_hook_for_page($hook, 'integrations')) {
			wp_enqueue_style(
				'foodord-integrations',
				plugin_dir_url(__FILE__) . 'css/foodord-integrations.css',
				array(),
				FOODORD_VERSION
			);
		}
	}

	/**
	 * Render the Delivery settings page.
	 */
	public function render_delivery_page()
	{
		static $delivery_handler = null;
		if (null === $delivery_handler) {
			$delivery_handler = new Foodord_Delivery();
		}
		$delivery_handler->render_delivery_page();
	}

	/**
	 * Render the Pickup settings page.
	 */
	public function render_pickup_page()
	{
		$pickup_handler = new Foodord_Pickup();
		$pickup_handler->render_pickup_page();
	}

	/**
	 * Render the Toppings settings page.
	 */
	public function render_toppings_page()
	{
		$toppings_handler = new Foodord_Toppings();
		$toppings_handler->render_toppings_page();
	}

	/**
	 * Render the Integrations settings page.
	 */
	public function render_integrations_page()
	{
		Foodord_Integrations::render_page();
	}

	/**
	 * Register a Theme Settings parent menu when FoodOrd theme is inactive.
	 */
	public function register_standalone_menu()
	{
		if (defined('FOODORD_THEME_ACTIVE') && FOODORD_THEME_ACTIVE) {
			return;
		}

		if (!current_user_can('manage_options')) {
			return;
		}

		$hook_suffix = add_menu_page(
			__('FoodOrd', 'foodord'),
			__('FoodOrd', 'foodord'),
			'manage_options',
			$this->get_settings_parent_slug(),
			array($this, 'render_dashboard_page'),
			'dashicons-food',
			59
		);
		if (is_string($hook_suffix) && '' !== $hook_suffix) {
			add_action('load-' . $hook_suffix, array($this, 'add_help_tabs_on_load'));
		}
	}

	/**
	 * Remove duplicate submenu entry when FoodOrd theme is inactive.
	 */
	public function cleanup_standalone_menu()
	{
		if (defined('FOODORD_THEME_ACTIVE') && FOODORD_THEME_ACTIVE) {
			return;
		}

		remove_submenu_page($this->get_settings_parent_slug(), $this->get_settings_parent_slug());
	}

	/**
	 * Move Dashboard submenu to the first position.
	 */
	public function prioritize_dashboard_submenu()
	{
		$parent_slug = $this->get_settings_parent_slug();
		$dashboard_slug = $this->get_page_slug('dashboard');

		global $submenu;
		if (!isset($submenu[$parent_slug]) || !is_array($submenu[$parent_slug])) {
			return;
		}

		$dashboard_item = null;
		$remaining_items = array();

		foreach ($submenu[$parent_slug] as $entry) {
			if (is_array($entry) && isset($entry[2]) && $dashboard_slug === (string) $entry[2]) {
				$dashboard_item = $entry;
				continue;
			}

			$remaining_items[] = $entry;
		}

		if (null === $dashboard_item) {
			return;
		}

		array_unshift($remaining_items, $dashboard_item);
		$submenu[$parent_slug] = $remaining_items;
	}

	/**
	 * Keep operational pages visible and move configuration pages into Settings.
	 */
	public function organize_foodord_submenu(): void
	{
		$parent_slug = $this->get_settings_parent_slug();
		$visible_slugs = array(
			$this->get_page_slug('dashboard'),
			$this->get_page_slug('live_orders'),
			$this->get_page_slug('reservations'),
			$this->get_page_slug('license'),
		);
		$settings_hub_slug = $this->get_page_slug('settings_hub');

		global $submenu;
		if (!isset($submenu[$parent_slug]) || !is_array($submenu[$parent_slug])) {
			return;
		}

		$visible_items = array();
		$secondary_items = array();
		$upgrade_items = array();
		$settings_items = array();

		foreach ($submenu[$parent_slug] as $entry) {
			if (!is_array($entry) || !isset($entry[2])) {
				$secondary_items[] = $entry;
				continue;
			}

			$slug = (string) $entry[2];
			$item_class = isset($entry[4]) ? (string) $entry[4] : '';

			if ($settings_hub_slug === $slug) {
				$settings_items[] = $entry;
				continue;
			}

			if (false !== strpos($item_class, 'foodord-admin-menu-upgrade')) {
				$upgrade_items[] = $entry;
				continue;
			}

			$visible_position = array_search($slug, $visible_slugs, true);
			if (false !== $visible_position) {
				$visible_items[(int) $visible_position][] = $entry;
				continue;
			}

			$item_classes = preg_split('/\s+/', trim($item_class));
			$item_classes = is_array($item_classes) ? array_filter($item_classes) : array();
			if (!in_array('foodord-admin-menu-secondary', $item_classes, true)) {
				$item_classes[] = 'foodord-admin-menu-secondary';
			}
			$entry[4] = implode(' ', $item_classes);
			$secondary_items[] = $entry;
		}

		ksort($visible_items);
		$ordered_visible_items = array();
		foreach ($visible_items as $items) {
			foreach ($items as $item) {
				$ordered_visible_items[] = $item;
			}
		}

		$submenu[$parent_slug] = array_merge($ordered_visible_items, $secondary_items, $settings_items, $upgrade_items);
	}

	/**
	 * Keep Settings selected while viewing a page managed by the Settings hub.
	 *
	 * @param mixed $submenu_file Current submenu file.
	 * @param mixed $parent_file  Current parent menu file.
	 * @return mixed
	 */
	public function filter_foodord_submenu_file($submenu_file, $parent_file)
	{
		if (is_string($parent_file) && '' !== $parent_file && $this->get_settings_parent_slug() !== $parent_file) {
			return $submenu_file;
		}

		$page_raw = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
		$current_slug = is_string($page_raw) ? sanitize_key($page_raw) : '';

		if ('' === $current_slug) {
			$post_type_raw = filter_input(INPUT_GET, 'post_type', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
			$post_type = is_string($post_type_raw) ? sanitize_key($post_type_raw) : '';
			if ('foodord_timed' === $post_type) {
				$current_slug = 'edit.php?post_type=foodord_timed';
			}
		}

		if ('' === $current_slug) {
			return $submenu_file;
		}

		foreach ($this->get_registered_foodord_submenu_entries() as $slug => $entry) {
			if ($slug !== $current_slug) {
				continue;
			}

			$item_class = isset($entry[4]) ? (string) $entry[4] : '';
			if (false !== strpos($item_class, 'foodord-admin-menu-secondary')) {
				return $this->get_page_slug('settings_hub');
			}
		}

		return $submenu_file;
	}

	/**
	 * Render the License settings page.
	 */
	public function render_license_page()
	{
		$this->license_handler->render_license_page();
	}

	/**
	 * Hide WooCommerce order item meta rows we don't need in admin.
	 *
	 * @param array<int,string> $hidden_meta Meta keys hidden by WooCommerce.
	 */
	public function hide_order_item_internal_meta($hidden_meta): array
	{
		if (!is_array($hidden_meta)) {
			$hidden_meta = array();
		}

		$hidden_meta[] = '_variation_id';

		return array_values(array_unique($hidden_meta));
	}

	/**
	 * Remove SKU and Variation ID visuals from order edit line items.
	 */
	public function hide_admin_order_item_details(): void
	{
		if (!$this->is_order_edit_screen()) {
			return;
		}
		?>
		<style id="foodord-order-item-cleanup">
			.woocommerce_order_items .wc-order-item-sku,
			.woocommerce_order_items .wc-order-item-variation {
				display: none !important;
			}
		</style>
		<?php
	}
}
