<?php
/**
 * Shared Preciousuite admin shell.
 *
 * @package Preciousuite
 */

if (!defined('ABSPATH')) {
	exit;
}

if (!class_exists('PreciousSuite_Admin', false)) {
	final class PreciousSuite_Admin
	{
		private static $config = array();
		private static $module_redirects = array();

		public static function init(array $config)
		{
			if (!empty(self::$config)) {
				return;
			}

			self::$config = wp_parse_args(
				$config,
				array(
					'version' => '1.0.0',
					'base_path' => '',
					'base_url' => '',
				)
			);

			add_action('admin_menu', array(__CLASS__, 'register_menu'), 30);
			add_action('admin_menu', array(__CLASS__, 'register_static_pages'), 120);
			add_action('admin_init', array(__CLASS__, 'redirect_legacy_pages'));
			add_action('admin_head', array(__CLASS__, 'hide_internal_submenus'));
			add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_assets'), 99);
		}

		public static function register_menu()
		{
			add_menu_page(
				__('Preciousuite', 'preciousuite-gold-buyback-quote-calculator'),
				__('Preciousuite', 'preciousuite-gold-buyback-quote-calculator'),
				'manage_options',
				'preciousuite',
				array(__CLASS__, 'render_dashboard'),
				'dashicons-chart-line',
				80
			);

			add_submenu_page(
				'preciousuite',
				__('General', 'preciousuite-gold-buyback-quote-calculator'),
				__('General', 'preciousuite-gold-buyback-quote-calculator'),
				'manage_options',
				'preciousuite',
				array(__CLASS__, 'render_dashboard')
			);
		}

		public static function register_static_pages()
		{
			add_submenu_page(
				'preciousuite',
				__('Task List', 'preciousuite-gold-buyback-quote-calculator'),
				__('Task List', 'preciousuite-gold-buyback-quote-calculator'),
				'manage_options',
				'preciousuite-tasks',
				array(__CLASS__, 'render_task_list')
			);

			add_submenu_page(
				'preciousuite',
				__('Alert Center', 'preciousuite-gold-buyback-quote-calculator'),
				__('Alert Center', 'preciousuite-gold-buyback-quote-calculator'),
				'manage_options',
				'preciousuite-alerts',
				array(__CLASS__, 'render_alert_center')
			);

			add_submenu_page(
				'preciousuite',
				__('Support', 'preciousuite-gold-buyback-quote-calculator'),
				__('Support', 'preciousuite-gold-buyback-quote-calculator'),
				'manage_options',
				'preciousuite-support',
				array(__CLASS__, 'render_support')
			);

			add_submenu_page(
				'preciousuite',
				__('First-time Configuration', 'preciousuite-gold-buyback-quote-calculator'),
				__('First-time Configuration', 'preciousuite-gold-buyback-quote-calculator'),
				'manage_options',
				'preciousuite-configuration',
				array(__CLASS__, 'render_first_time_configuration')
			);

			global $submenu;
			$submenu['preciousuite'][] = array(
				'<span style="color: #000; background-color: #fcd34d; padding: 2px 6px; border-radius: 4px; display: flex; justify-content:center;">' . __('Upgrade Pro', 'preciousuite-gold-buyback-quote-calculator') . '</span>',
				'manage_options',
				'https://preciousuite.com/products'
			);
		}

		public static function hide_internal_submenus()
		{
			?>
			<script>
				document.addEventListener('DOMContentLoaded', function () {
					document.querySelectorAll('#adminmenu a[href$="page=preciousuite-tasks"], #adminmenu a[href$="page=preciousuite-alerts"], #adminmenu a[href$="page=preciousuite-configuration"], #adminmenu a[href$="page=ps-gs-schemes"], #adminmenu a[href$="page=ps-gs-customers"], #adminmenu a[href$="page=ps-gs-settings"]').forEach(function (link) {
						var item = link.closest('li');

						if (item) {
							item.remove();
						}
					});
				});
			</script>
			<?php
		}

		public static function redirect_legacy_pages()
		{
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter check for legacy redirect mapping.
			if (!isset($_GET['page'])) {
				return;
			}

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter check for legacy redirect mapping.
			$page = sanitize_key(wp_unslash($_GET['page']));
			$map = array(
				'precioussuite' => 'preciousuite',
				'precioussuite-tasks' => 'preciousuite-tasks',
				'precioussuite-alerts' => 'preciousuite-alerts',
				'precioussuite-support' => 'preciousuite-support',
				'precioussuite-upgrade' => 'preciousuite-upgrade',
				'precioussuite-configuration' => 'preciousuite-configuration',
			);

			if (!isset($map[$page])) {
				return;
			}

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter check for legacy redirect mapping.
			$args = wp_unslash($_GET);
			$args['page'] = $map[$page];

			wp_safe_redirect(esc_url_raw(add_query_arg($args, admin_url('admin.php'))));
			exit;
		}

		public static function enqueue_assets($hook)
		{
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter check only for assets enqueueing.
			$page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter check only for assets enqueueing.
			$post_type = isset($_GET['post_type']) ? sanitize_key(wp_unslash($_GET['post_type'])) : '';
			$pages = array(
				'preciousuite',
				'gold-price',
				'gold-price-widgets',
				'gold-price-api-settings',
				'gold-price-logs',
				'preciousuite-settings',
				'jicg-settings',
				'preciousuite-tasks',
				'preciousuite-alerts',
				'preciousuite-support',
				'preciousuite-upgrade',
				'preciousuite-configuration',
			);

			if (false === strpos($hook, 'precioussuite') && false === strpos($hook, 'preciousuite') && !in_array($page, $pages, true) && 'preciousuite_quote' !== $post_type) {
				return;
			}

			wp_enqueue_style(
				'preciousuite-gold-buyback-admin',
				self::$config['base_url'] . 'assets/admin.css',
				array(),
				time()
			);

			wp_enqueue_style(
				'preciousuite-responsive',
				PRECIOUSUITE_URL . 'assets/css/responsive.css',
				array(),
				time()
			);
		}

		public static function render_dashboard()
		{
			require self::$config['base_path'] . 'views/dashboard.php';
		}

		public static function render_support()
		{
			require self::$config['base_path'] . 'views/support.php';
		}

		public static function render_alert_center()
		{
			require self::$config['base_path'] . 'views/alert-center.php';
		}

		public static function render_task_list()
		{
			require self::$config['base_path'] . 'views/task-list.php';
		}

		public static function render_first_time_configuration()
		{
			require self::$config['base_path'] . 'views/first-time-configuration.php';
		}

		public static function render_upgrade()
		{
			require self::$config['base_path'] . 'views/upgrade.php';
		}

		public static function render_module_redirect()
		{
			self::render_dashboard();
		}

		public static function redirect_module_page()
		{
			$screen = get_current_screen();

			if ($screen && isset(self::$module_redirects[$screen->id])) {
				wp_safe_redirect(esc_url_raw(self::$module_redirects[$screen->id]));
				exit;
			}
		}
	}
}
