<?php
if (!defined('ABSPATH')) exit;

class Aegisify_Admin {

    const CAPABILITY = 'manage_options';
    const MENU_SLUG = 'aegisify-dashboard';
	private static $jump_targets = array();
	
	public function hooks(): void {
		add_action('admin_menu', array($this, 'register_menu'), 1);
		add_action('admin_menu', array($this, 'register_module_jump_submenus'), 999);
		add_filter('custom_menu_order', '__return_true');
		add_filter('menu_order', array($this, 'filter_menu_order'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
		add_action('admin_post_aegisify_toggle_module', array($this, 'handle_toggle_module'));
	}

	public function register_menu(): void {
		add_menu_page(
			__('Aegisify', 'aegisify'),
			__('Aegisify', 'aegisify'),
			self::CAPABILITY,
			self::MENU_SLUG,
			array($this, 'render_dashboard'),
			$this->get_menu_icon(),
			3
		);
		add_submenu_page(
			self::MENU_SLUG,
			__('Dashboard', 'aegisify'),
			__('Dashboard', 'aegisify'),
			self::CAPABILITY,
			self::MENU_SLUG,
			array($this, 'render_dashboard')
		);
		if (class_exists('Aegisify_Bundled_Plugins_Page')) {
			Aegisify_Bundled_Plugins_Page::init(array(
				'parent_slug' => self::MENU_SLUG,
				'menu_slug'   => 'aegisify-plugins',
				'page_title'  => 'Aegisify Plugins',
				'menu_title'  => 'Plugins',
				'view_cap'    => self::CAPABILITY,
			));

			Aegisify_Bundled_Plugins_Page::add_submenu();
		}

		add_submenu_page(
			self::MENU_SLUG,
			__('SMTP Settings', 'aegisify'),
			__('SMTP Settings', 'aegisify'),
			self::CAPABILITY,
			'aegisify-email-settings',
			array('Aegisify_Admin_Emails', 'render_page')
		);
	}

    private function get_menu_icon(): string {
        return 'dashicons-shield';
    }

	public function enqueue_assets($hook): void {
		$page = isset($_GET['page']) ? sanitize_key( (string) wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if (empty($page) || !in_array($page, array(self::MENU_SLUG, 'aegisify-plugins'), true)) {
			return;
		}

		$css_file = plugin_dir_path(__FILE__) . '../assets/admin.css';
		$css_ver  = file_exists($css_file) ? (string) filemtime($css_file) : AEGISIFY_CORE_VERSION;

		wp_enqueue_style(
			'aegisify-admin',
			AEGISIFY_CORE_URL . 'assets/admin.css',
			array(),
			$css_ver
		);
    }

    public function handle_toggle_module(): void {
        if (!current_user_can(self::CAPABILITY)) {
	            wp_die( esc_html__( 'Insufficient permissions.', 'aegisify' ) );
        }

        check_admin_referer('aegisify_toggle_module');

        $slug = isset($_POST['module_slug']) ? sanitize_key(wp_unslash($_POST['module_slug'])) : '';
        $action = isset($_POST['toggle_action']) ? sanitize_key(wp_unslash($_POST['toggle_action'])) : '';

        if (!$slug || !in_array($action, array('enable', 'disable'), true)) {
            wp_safe_redirect(admin_url('admin.php?page=' . self::MENU_SLUG . '&aegisify_msg=invalid'));
            exit;
        }

        $ok = false;
        if ($action === 'enable') {
            $ok = Aegisify_Modules::enable($slug);
        } else {
            $ok = Aegisify_Modules::disable($slug);
        }

        $msg = $ok ? 'ok' : 'failed';
        wp_safe_redirect(admin_url('admin.php?page=' . self::MENU_SLUG . '&aegisify_msg=' . $msg));
        exit;
    }
	public function filter_menu_order($menu_order) {
		if (!is_array($menu_order)) {
			return $menu_order;
		}

		$needle = self::MENU_SLUG;
		$menu_order = array_values(array_filter($menu_order, function ($slug) use ($needle) {
			return $slug !== $needle;
		}));

		array_splice($menu_order, 2, 0, array($needle));

		return $menu_order;
	}

	public function register_module_jump_submenus(): void {
		$enabled = get_option(Aegisify_Modules::OPTION_ENABLED, array());
		if (!is_array($enabled) || empty($enabled)) {
			return;
		}

		$label_variants = array(
			'aegisshield'  => array('AegisShield'),
			'aegiswaf'     => array('AegisWAF', 'Aegis WAF'),
			('aegis' . 'seo')     => array('AegisSEO', 'Aegis SEO'),
			'aegisspam'    => array('AegisSpamGuard', 'AegisSPAM', 'AegisSpam'),
			'aegislink'    => array('AegisLink', 'AegisLINK'),
			'aegisbackup'  => array('AegisBackup'),
			'aegissitemap' => array('AegisSiteMap', 'AegisSitemap', 'AegisSiteMAP'),
			'aegisticket'  => array('AegisTickets', 'AegisTicket'),
		);

		foreach ($enabled as $module_slug => $on) {
			if (empty($on)) {
				continue;
			}

			$module_slug = sanitize_key((string) $module_slug);
			$labels = $label_variants[$module_slug] ?? array();
			if (empty($labels)) {
				continue;
			}

			$target_slug = $this->find_existing_top_level_menu_slug($labels);
			if (empty($target_slug)) {
				continue;
			}

			$target_url = $this->build_admin_target_url($target_slug);
			if (empty($target_url)) {
				continue;
			}

			$jump_slug = 'aegisify-jump-' . $module_slug;
			self::$jump_targets[$jump_slug] = $target_url;

			add_submenu_page(
				self::MENU_SLUG,
				$labels[0],
				$labels[0],
				self::CAPABILITY,
				$jump_slug,
				array($this, 'render_jump_page')
			);
		}
	}

	public function render_jump_page(): void {
		$page = isset($_GET['page']) ? sanitize_key( (string) wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ($page && !empty(self::$jump_targets[$page])) {
			wp_safe_redirect(self::$jump_targets[$page]);
			exit;
		}

		wp_safe_redirect(admin_url('admin.php?page=' . self::MENU_SLUG));
		exit;
	}

	private function find_existing_top_level_menu_slug(array $possible_labels): string {
		global $menu;
		if (!is_array($menu) || empty($menu)) {
			return '';
		}

		$possible_labels = array_values(array_filter(array_map('strval', $possible_labels)));
		if (empty($possible_labels)) {
			return '';
		}

		foreach ($menu as $item) {
			if (!is_array($item) || empty($item[0]) || empty($item[2])) {
				continue;
			}

			$label = strtolower(wp_strip_all_tags((string) $item[0]));
			foreach ($possible_labels as $needle) {
				$needle = strtolower(wp_strip_all_tags($needle));
				if ($needle !== '' && strpos($label, $needle) !== false) {
					return (string) $item[2];
				}
			}
		}

		return '';
	}

	private function build_admin_target_url(string $menu_slug): string {
		$menu_slug = trim((string) $menu_slug);
		if ($menu_slug === '') {
			return '';
		}

		if (strpos($menu_slug, '.php') !== false) {
			return admin_url($menu_slug);
		}

		return admin_url('admin.php?page=' . rawurlencode($menu_slug));
	}
	
	private function render_license_panel(): void {

		$license = Aegisify_Core::instance()->license();
		$free_optin  = (int) get_option(\Aegisify\Utils\License::OPTION_FREE_OPTIN, 0);
		$free_status = (string) get_option(\Aegisify\Utils\License::OPTION_FREE_STATUS, 'unregistered');

		$license_action = isset($_POST['aegisify_license_action']) ? sanitize_key( (string) wp_unslash( $_POST['aegisify_license_action'] ) ) : '';

		if ( $license_action !== '' ) {

			check_admin_referer('aegisify_license_action');

			$key   = isset($_POST['license_key']) ? sanitize_text_field( (string) wp_unslash( $_POST['license_key'] ) ) : '';
			$email = isset($_POST['license_email']) ? sanitize_email( (string) wp_unslash( $_POST['license_email'] ) ) : '';

			$license->set_key($key);
			update_option(\Aegisify\Utils\License::OPTION_EMAIL, $email, false);

			$msg = 'saved';

			if (isset($_POST['aegisify_activate_license'])) {
				$resp = $license->activate_now(AEGISIFY_CORE_VERSION);
				$msg = !empty($resp['success']) ? 'activated' : 'activate_failed';

			} elseif (isset($_POST['aegisify_deactivate_license'])) {
				$resp = $license->deactivate_now(AEGISIFY_CORE_VERSION);
				$msg = !empty($resp['success']) ? 'deactivated' : 'deactivate_failed';

			} elseif (isset($_POST['aegisify_check_license'])) {
				$license->check_now(AEGISIFY_CORE_VERSION);
				$msg = 'checked';

			} elseif (isset($_POST['aegisify_start_trial'])) {
				$resp = $license->start_trial_now(AEGISIFY_CORE_VERSION);
				$msg = !empty($resp['success']) ? 'trial_started' : 'trial_failed';

			} elseif (isset($_POST['aegisify_register_free_install'])) {
				$st = $license->get_status();
				$is_pro    = !empty($st['is_pro']);
				$lic_state = isset($st['status']) ? (string) $st['status'] : '';
				$is_active = $is_pro || ($lic_state === 'active');

				$consent_value = isset($_POST['aegisify_free_reg_consent']) ? sanitize_text_field( (string) wp_unslash( $_POST['aegisify_free_reg_consent'] ) ) : '';
				$consent = $is_active
					? true
					: ($consent_value === '1');

				if (!$consent) {
					$msg = 'consent_required';
				} else {
					update_option(\Aegisify\Utils\License::OPTION_FREE_OPTIN, 1, false);
					update_option(\Aegisify\Utils\License::OPTION_FREE_STATUS, 'unregistered', false);
					delete_transient('aegisify_clm_free_reg_sent');
					$license->maybe_send_free_register(AEGISIFY_CORE_VERSION);

					$free_status = (string) get_option(\Aegisify\Utils\License::OPTION_FREE_STATUS, 'unregistered');
					$msg = ($free_status === 'registered') ? 'free_registered' : 'free_register_failed';
				}

			} elseif (isset($_POST['aegisify_unregister_free_install'])) {

				update_option(\Aegisify\Utils\License::OPTION_FREE_OPTIN, 0, false);
				update_option(\Aegisify\Utils\License::OPTION_FREE_STATUS, 'unregistered', false);
				$msg = 'free_unregistered';
			}

			$_GET['aegisify_license_msg'] = $msg;
			$free_optin  = (int) get_option(\Aegisify\Utils\License::OPTION_FREE_OPTIN, 0);
			$free_status = (string) get_option(\Aegisify\Utils\License::OPTION_FREE_STATUS, 'unregistered');
		}

		$status = $license->get_status();
		$is_pro    = !empty($status['is_pro']);
		$plan      = isset($status['plan']) ? (string) $status['plan'] : '';
		$expires   = isset($status['expires']) ? (string) $status['expires'] : '';
		$lic_state = isset($status['status']) ? (string) $status['status'] : '';
		$is_active = $is_pro || ($lic_state === 'active');

		if (isset($_GET['aegisify_license_msg'])) {
			$m = sanitize_key((string) $_GET['aegisify_license_msg']);
			$map = array(
				'saved' => array('success', __('License saved.', 'aegisify')),
				'activated' => array('success', __('License activated.', 'aegisify')),
				'activate_failed' => array('error', __('Activation failed. Check your server error log.', 'aegisify')),
				'deactivated' => array('success', __('License deactivated.', 'aegisify')),
				'deactivate_failed' => array('error', __('Deactivation failed. Check your server error log.', 'aegisify')),
				'checked' => array('success', __('License status refreshed.', 'aegisify')),
				'consent_required' => array('error', __('Please confirm consent before registering this installation.', 'aegisify')),
				'free_registered' => array('success', __('Registered successfully with Aegisify.', 'aegisify')),
				'free_register_failed' => array('error', __('Free registration failed. Please try again.', 'aegisify')),
				'free_unregistered' => array('success', __('Free installation unregistered.', 'aegisify')),
			);

			if (isset($map[$m])) {
				$type = $map[$m][0];
				$txt  = $map[$m][1];
				$cls  = ($type === 'success') ? 'notice-success' : 'notice-error';
				echo '<div class="notice ' . esc_attr($cls) . ' is-dismissible"><p>' . esc_html($txt) . '</p></div>';
			}
		}

		$license_key   = $license->get_key();
		$license_email = (string) get_option(\Aegisify\Utils\License::OPTION_EMAIL, '');

		echo '<div class="postbox aegisify-license-panel" style="padding:16px; margin: 16px 0;">';
		echo '<h2 style="margin:0 0 12px 0;">' . esc_html__('One License for 8 Tools!', 'aegisify') . '</h2>';

		echo '<h3 style="margin:0 0 10px 0;">' . esc_html__('License Status', 'aegisify') . '</h3>';
		echo '<table class="widefat striped" style="max-width:600px;margin-bottom:14px;"><tbody>';

		echo '<tr><th scope="row">' . esc_html__('Status', 'aegisify') . '</th><td>';
		if ( $is_active ) {
			$status_text = $is_pro ? __( 'Active (Pro enabled)', 'aegisify' ) : __( 'Active', 'aegisify' );
			echo '<span style="color:#46b450;font-weight:600;">' . esc_html( $status_text ) . '</span>';
		} else {
			echo '<span style="color:#dc3232;font-weight:600;">' . esc_html__( 'Inactive', 'aegisify' ) . '</span>';
		}
		echo '</td></tr>';

		echo '<tr><th scope="row">' . esc_html__('Plan', 'aegisify') . '</th><td>' . esc_html($plan !== '' ? $plan : '-') . '</td></tr>';
		echo '<tr><th scope="row">' . esc_html__('Expires At', 'aegisify') . '</th><td>' . esc_html($expires !== '' ? $expires : '-') . '</td></tr>';

		echo '</tbody></table>';

		echo '<p class="description" style="margin:0 0 14px 0;">' .
			 esc_html__('Enter your license key and the email used at checkout. Activate to unlock PRO features and updates.', 'aegisify') .
			 '</p>';

		echo '<form method="post" style="width:100%; max-width:none;">';
		wp_nonce_field('aegisify_license_action');
		echo '<input type="hidden" name="aegisify_license_action" value="1" />';

		echo '<table class="form-table" role="presentation" style="max-width:900px;"><tbody>';

		echo '<tr><th scope="row"><label for="license_key">' . esc_html__('License Key', 'aegisify') . '</label></th>';
		echo '<td><input type="text" id="license_key" name="license_key" value="' . esc_attr($license_key) . '" class="regular-text" /></td></tr>';

		echo '<tr><th scope="row"><label for="license_email">' . esc_html__('License Email', 'aegisify') . '</label></th>';
		echo '<td><input type="email" id="license_email" name="license_email" value="' . esc_attr($license_email) . '" class="regular-text" /></td></tr>';

		echo '</tbody></table>';

		echo '<p style="margin-top:10px; display:flex; gap:8px; flex-wrap:wrap;">';
		echo '<button type="submit" name="aegisify_activate_license" class="button button-primary">' . esc_html__('Activate License', 'aegisify') . '</button>';
		echo '<button type="submit" name="aegisify_deactivate_license" class="button">' . esc_html__('Deactivate', 'aegisify') . '</button>';
		echo '<button type="submit" name="aegisify_check_license" class="button">' . esc_html__('Check Status', 'aegisify') . '</button>';
		echo '<button type="submit" name="aegisify_start_trial" class="button" style="background:#46b450;border-color:#46b450;color:#ffffff;">' . esc_html__('Start 30-Day Trial', 'aegisify') . '</button>';
		echo '</p>';

		echo '<hr style="margin:16px 0;" />';

		echo '<h3 style="margin:0 0 8px 0;">' . esc_html__('Optional: Register this free installation', 'aegisify') . '</h3>';
		echo '<p class="description" style="margin:0 0 10px 0;">' .
			 esc_html__('This is optional and only if you want update checks and license-related features through Aegisify. This will send your site domain, site URL, and the WordPress admin email to Aegisify.', 'aegisify') .
			 '</p>';

			// If the site has an active paid license, consent is no longer required.
			$checked  = (bool) $is_active || ( (int) $free_optin === 1 );
			$disabled = (bool) $is_active;

			echo '<label style="display:inline-flex; gap:8px; align-items:center; margin-bottom:8px;">';
			echo '<input type="checkbox" name="aegisify_free_reg_consent" value="1" ' . checked( $checked, true, false ) . ' ' . disabled( $disabled, true, false ) . ' /> ';
		echo esc_html__('I consent to send the data described above to Aegisify.', 'aegisify');
		echo '</label>';

		echo '<p style="margin:6px 0 10px 0;"><strong>' . esc_html__('Registration Status:', 'aegisify') . '</strong> ' .
			 esc_html($free_status === 'registered' ? 'Registered' : 'Unregistered') .
			 '</p>';

		echo '<p style="display:flex; gap:8px; flex-wrap:wrap;">';
		echo '<button type="submit" name="aegisify_register_free_install" class="button">' . esc_html__('Register Free Installation', 'aegisify') . '</button>';
		echo '<button type="submit" name="aegisify_unregister_free_install" class="button">' . esc_html__('Unregister Free Installation', 'aegisify') . '</button>';
		echo '</p>';

		echo '<p class="description" style="margin-top:12px;">' .
			 'Create an account on ' . '<a href="' . esc_url('https://aegisify.com/register/') . '" target="_blank" rel="noopener noreferrer">https://aegisify.com/register/</a>' .
			 ' ' . esc_html__('and help support Aegisify by buying a license today!', 'aegisify') .
			 '</p>';

		echo '</form>';
		echo '</div>';
	}

    public function render_dashboard(): void {
        $catalog = Aegisify_Modules::get_default_catalog();
        $enabled_map = get_option(Aegisify_Modules::OPTION_ENABLED, array());

        ?>
        <div class="wrap aegisify-wrap">
            <div class="aegisify-hero">
                <div class="aegisify-hero-left">
                    <div class="aegisify-brand">
                        <div class="aegisify-logo"><img src="<?php echo esc_url(AEGISIFY_URL . 'assets/aegisify_logo1_small.png'); ?>" alt="Aegisify" /></div>
                        <div class="aegisify-title">
                            <h1>Everything Your WordPress Site Needs One Platform. One Price.</h1>
                            <p>Built for site owners, freelancers, and agencies who want stability.  Get enterprise level Backups & DR, Advanced SEO, latest Security protection, SPAM protection, WAF and the list will continue.</p>
                        </div>
                    </div>

                    <div class="aegisify-cta">
                        <a class="button button-primary" href="admin.php?page=aegisify-plugins">Get Started</a>
                        <a class="button" href="https://aegisify.com/help-center/">Documentation</a>
                    </div>
                </div>

                <div class="aegisify-hero-right">
                    <div class="aegisify-status-card">
                        <h3>Suite Status</h3>
                        <p>
                            Enabled modules:
                            <strong><?php echo intval(count($enabled_map)); ?></strong>
                            / <?php echo intval(count($catalog)); ?>
                        </p>
                        <p class="description">Toggle modules below. Disabled modules remain inert.</p>
                    </div>
                </div>
            </div>

			<?php
			$aegisify_msg = isset($_GET['aegisify_msg']) ? sanitize_key( (string) wp_unslash( $_GET['aegisify_msg'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			?>
			<?php if (!empty($aegisify_msg)): ?>
				<?php $notice_class = ($aegisify_msg === 'ok') ? 'success' : 'warning'; ?>
				<div class="notice notice-<?php echo esc_attr($notice_class); ?> is-dismissible">
					<p>
						<?php
						if ($aegisify_msg === 'ok') {
							echo esc_html__('Updated successfully.', 'aegisify');
						} elseif ($aegisify_msg === 'failed') {
							echo esc_html__('Action failed (license or module not available).', 'aegisify');
						} else {
							echo esc_html__('Invalid request.', 'aegisify');
						}
						?>
					</p>
				</div>
			<?php endif; ?>
			<div class="aegisify-midrow">
				<div class="aegisify-mid-left">
					<?php $this->render_license_panel(); ?>
				</div>

				<div class="aegisify-mid-right">
					<div class="postbox aegisify-plans-panel">
						<div class="aegisify-plans-image">
							<img
								src="<?php echo esc_url(AEGISIFY_URL . 'assets/all.png'); ?>"
								alt="Aegisify Plans"
							/>
						</div>
						<br>
						<div class="aegisify-plans-price">
							14 DAY MONEY BACK GUARANTEED. <span class="aegisify-plans-price-sub"> NO QUESTIONS ASKED.</span>
						</div>

						<p class="description aegisify-plans-desc">
							Get the full Aegisify Suite: Security, WAF, SEO, Backup, Spam, Links, SiteMap, Tickets - ALL INCLUDED
						</p>

						<a class="button button-primary button-hero aegisify-plans-btn"
						   href="https://www.paypal.com/ncp/payment/XPUYRBYTKER3U"
						   target="_blank" rel="noopener noreferrer">
							Buy Now
						</a>
					</div>
				</div>
			</div>
			<div class="aegisify-icons-row">
			<?php
			$icon_size_px = 140;
			$icons = array(
				array(
					'src' => AEGISIFY_URL . 'assets/aegisifyshield.png',
					'alt' => 'AegisShield',
					'url' => 'https://aegisify.com/wordpress-aegis-shield-security-product/',
				),
				array(
					'src' => AEGISIFY_URL . 'assets/aegisifywaf.png',
					'alt' => 'AegisWAF',
					'url' => 'https://aegisify.com/aegiswaf/',
				),
				array(
					'src' => AEGISIFY_URL . ('assets/' . 'aegisify' . 'seo.png'),
					'alt' => 'AegisSEO',
					'url' => ('https://aegisify.com/' . 'aegis' . 'seo/'),
				),
				array(
					'src' => AEGISIFY_URL . 'assets/aegisifyspam.png',
					'alt' => 'AegisSpam',
					'url' => 'https://aegisify.com/aegisspam-guard/',
				),
				array(
					'src' => AEGISIFY_URL . 'assets/aegisifylinks.png',
					'alt' => 'AegisLink',
					'url' => 'https://aegisify.com/aegislink/',
				),
				array(
					'src' => AEGISIFY_URL . 'assets/aegisifybackup.png',
					'alt' => 'AegisBackup',
					'url' => 'https://aegisify.com/aegisbackup/',
				),
				array(
					'src' => AEGISIFY_URL . 'assets/aegisifysitemap.png',
					'alt' => 'AegisSiteMap',
					'url' => 'https://aegisify.com/aegissitemap/',
				),
				array(
					'src' => AEGISIFY_URL . 'assets/aegisifyticket.png',
					'alt' => 'AegisTicket',
					'url' => 'https://aegisify.com/aegisticket/',
				),
			);
			?>

			<div class="aegisify-icons-row" style="--aegisify-icon-size: <?php echo intval($icon_size_px); ?>px;">
				<?php foreach ($icons as $icon): ?>
					<a class="aegisify-icon-link"
					   href="<?php echo esc_url($icon['url']); ?>"
					   target="_blank"
					   rel="noopener noreferrer">
						<img src="<?php echo esc_url($icon['src']); ?>"
							 alt="<?php echo esc_attr($icon['alt']); ?>" />
					</a>
				<?php endforeach; ?>
			</div>

			</div>
        </div>
        <?php
    }
}
