<?php
/**
 * Settings Manager
 *
 * @package AmbassadorHub\Admin\Settings
 */

namespace AmbassadorHub\Admin\Settings;

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

use AmbassadorHub\Admin\AdminPage;

/**
 * Manages the tabbed settings page.
 *
 * Handles rendering, tab switching, and form submission.
 */
final class Manager {
	/**
	 * Current active tab.
	 *
	 * @var string
	 */
	private static string $current_tab = 'fundraisers';

	/**
	 * Initialize the Settings manager.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'ambh_admin_menu_registered', array( self::class, 'register_menu' ), 90 );
		add_action( 'admin_notices', array( self::class, 'render_header' ), 1 );
		add_action( 'admin_init', array( self::class, 'handle_tab_form_submissions' ) );
	}

	/**
	 * Dispatch POST form submissions to the active settings tab.
	 *
	 * Runs on admin_init (before any output) so tabs can redirect after saving.
	 * Each tab's handle_submission() is responsible for its own nonce check.
	 *
	 * @return void
	 */
	public static function handle_tab_form_submissions(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- routing only; each tab verifies its own nonce.
		if ( 'ambassadorhub-settings' !== sanitize_key( wp_unslash( $_GET['page'] ?? '' ) ) ) {
			return;
		}

		foreach ( Registry::get_tabs() as $tab ) {
			if ( method_exists( $tab, 'handle_submission' ) ) {
				$tab->handle_submission();
			}
		}
	}

	/**
	 * Register the Settings submenu page.
	 *
	 * @return void
	 */ public static function register_menu(): void {

		// Add Settings submenu.
		// Do this after the action so other modules can add theirs first.
		add_submenu_page(
			'ambassadorhub',
			__( 'Settings', 'ambassadorhub' ),
			__( 'Settings', 'ambassadorhub' ),
			'manage_options',
			'ambassadorhub-settings',
			array( self::class, 'render_settings_page' )
		);
}

	/**
	 * Render the header.
	 *
	 * @return void
	 */
public static function render_header(): void {

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

	if ( ! AdminPage::is_page( 'ambassadorhub-settings' ) ) {
		return;
	}

	AdminPage::header(
		esc_html__( 'AmbassadorHub', 'ambassadorhub' ),
		esc_html__( 'Configure AmbassadorHub settings, integrations, and pages.', 'ambassadorhub' )
	);
}

	/**
	 * Get the current active tab.
	 *
	 * @return string Tab ID.
	 */
public static function get_current_tab(): string {
	if ( isset( $_GET['tab'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only GET parameter for tab navigation only.
		$tab  = sanitize_key( $_GET['tab'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$tabs = Registry::get_tabs();
		if ( isset( $tabs[ $tab ] ) ) {
			self::$current_tab = $tab;
		}
	}

	return self::$current_tab;
}

	/**
	 * Render the settings page.
	 *
	 * @return void
	 */
public static function render_settings_page(): void {

	$tabs        = Registry::get_tabs();
	$current_tab = self::get_current_tab();

	// Sort tabs by priority.
	uasort(
		$tabs,
		static function ( Tab $a, Tab $b ) {
			return $a->get_priority() <=> $b->get_priority();
		}
	);
	?>

		<div class="wrap">

			<h2></h2> <!-- Prevent admin notices being moved to the hidden h2 position -->

			<div class="ambh-settings-layout">

				<nav class="ambh-settings-nav" role="tablist" aria-label="<?php esc_attr_e( 'Settings sections', 'ambassadorhub' ); ?>">
				<?php foreach ( $tabs as $tab_id => $tab ) : ?>
						<?php $is_active = $tab_id === $current_tab; ?>
						<a
							href="<?php echo esc_url( add_query_arg( 'tab', $tab_id ) ); ?>"
							class="ambh-settings-nav__item<?php echo $is_active ? ' is-active' : ''; ?>"
							role="tab"
							aria-selected="<?php echo esc_attr( $is_active ? 'true' : 'false' ); ?>"
						>
							<?php echo esc_html( $tab->get_label() ); ?>
						</a>
					<?php endforeach; ?>
				</nav>

				<div class="ambassadorhub-settings-content">
				<?php
				if ( isset( $tabs[ $current_tab ] ) ) {
					$tabs[ $current_tab ]->render();
				}
				?>
				</div>

			</div>

		</div> 
		<?php
}
}
