<?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-metal-rate-charts'),
				__('Preciousuite', 'preciousuite-metal-rate-charts'),
				'manage_options',
				'preciousuite',
				array(__CLASS__, 'render_dashboard'),
				'dashicons-chart-line',
				80
			);

			add_submenu_page(
				'preciousuite',
				__('General', 'preciousuite-metal-rate-charts'),
				__('General', 'preciousuite-metal-rate-charts'),
				'manage_options',
				'preciousuite',
				array(__CLASS__, 'render_dashboard')
			);
		}

		public static function register_static_pages()
		{
			add_submenu_page(
				'preciousuite',
				__('Task List', 'preciousuite-metal-rate-charts'),
				__('Task List', 'preciousuite-metal-rate-charts'),
				'manage_options',
				'preciousuite-tasks',
				array(__CLASS__, 'render_task_list')
			);

			add_submenu_page(
				'preciousuite',
				__('Alert Center', 'preciousuite-metal-rate-charts'),
				__('Alert Center', 'preciousuite-metal-rate-charts'),
				'manage_options',
				'preciousuite-alerts',
				array(__CLASS__, 'render_alert_center')
			);

			add_submenu_page(
				'preciousuite',
				__('Support', 'preciousuite-metal-rate-charts'),
				__('Support', 'preciousuite-metal-rate-charts'),
				'manage_options',
				'preciousuite-support',
				array(__CLASS__, 'render_support')
			);

			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-metal-rate-charts') . '</span>',
				'manage_options',
				'https://preciousuite.com/products'
			);

			add_submenu_page(
				'preciousuite',
				__('First-time configuration', 'preciousuite-metal-rate-charts'),
				__('First-time configuration', 'preciousuite-metal-rate-charts'),
				'manage_options',
				'preciousuite-configuration',
				array(__CLASS__, 'render_configuration')
			);
		}

		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 -- Reading admin list table filter value.
			if (!isset($_GET['page'])) {
				return;
			}

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin list table filter value.
			$page = sanitize_key(wp_unslash($_GET['page']));
			$map = array(
				'precioussuite' => 'preciousuite',
				'precioussuite-tasks' => 'preciousuite-tasks',
				'precioussuite-alerts' => 'preciousuite-alerts',
				'precioussuite-support' => 'preciousuite-support',
				'preciousuite-upgrade' => 'preciousuite-upgrade',
				'preciousuite-configuration' => 'preciousuite-configuration',
			);

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

			$target_page = $map[$page];
			if ($target_page === $page) {
				return;
			}

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin list table filter value.
			$args = wp_unslash($_GET);
			$args['page'] = $target_page;

			// phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect -- Safe redirect, args are sanitized.
			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 -- Reading admin list table filter value.
			$page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading admin list table filter value.
			$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(
				'precioussuite-admin',
				self::$config['base_url'] . 'assets/admin.css',
				array(),
				self::$config['version']
			);
		}

		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_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;
			}
		}
	}
}
