<?php
/**
 * SettingsPageRenderer class.
 *
 * Renders settings pages in the WordPress admin using the Settings API,
 * including tabbed navigation, module overview, and individual setting group forms.
 *
 * @package Ilabs\Firevert\Core\Settings\UI
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Settings\UI;

use Ilabs\Firevert\Core\ModuleManager;
use Ilabs\Firevert\Core\Services\Builder\PageUrlBuilder;
use Ilabs\Firevert\Core\Settings\Registry\SettingsRegistry;

/**
 * Renders settings pages using the WordPress Settings API.
 */
class SettingsPageRenderer {

	/**
	 * Central settings registry instance.
	 *
	 * @var SettingsRegistry
	 */
	private SettingsRegistry $registry;

	/**
	 * Constructor.
	 *
	 * @param SettingsRegistry $registry Get from DI container.
	 */
	public function __construct( SettingsRegistry $registry ) {
		$this->registry = $registry;
	}

	/**
	 * Registers the "Firevert" menu page in the WordPress admin.
	 *
	 * @return void
	 */
	public function register_menu(): void {
		add_menu_page(
			'Firevert',
			'Firevert',
			'manage_options',
			'firevert',
			array( $this, 'render_page' ),
			'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5LjUiIGhlaWdodD0iMTIiIHZpZXdCb3g9IjAgMCAxNC43MDUgMTguNTQiPjxwYXRoIGQ9Ik0xNC43MDUsMEg3LjM1M0E3LjM4NSw3LjM4NSwwLDAsMCwwLDcuNDE2SDMuNjYxQTcuNDE4LDcuNDE4LDAsMCwwLDAsMTMuODIyVjE4LjU0YzMuNzM4LTQuNzE4LDcuMzUzLTQuNzE4LDcuMzUzLTQuNzE4YTcuMzg1LDcuMzg1LDAsMCwwLDcuMzUzLTcuNDE2SDExLjA0NEE3LjQxOCw3LjQxOCwwLDAsMCwxNC43MDUsMCIgZmlsbD0iIzlkYTNhOCIvPjwvc3ZnPg==',
			30
		);
	}

	/**
	 * Renders the settings page based on the registered setting groups.
	 *
	 * @return void
	 */
	public function render_page(): void {
		$groups       = $this->registry->get_groups();
		$active_tab   = $this->get_active_tab();
		$module_param = $this->get_module_param();

		$content_data = $this->prepare_content_data( $groups, $active_tab, $module_param );

		firevert_view(
			'settings.view.php',
			array(
				'title'        => __( 'Firevert Settings', 'firevert' ),
				'active_tab'   => $active_tab,
				'content_data' => $content_data,
			)
		);
	}


	/**
	 * Gets the active tab from URL parameters.
	 *
	 * @return string
	 */
	private function get_active_tab(): string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$tab_param = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : null;

		return $tab_param ?? 'general';
	}

	/**
	 * Prepares content data based on active tab and parameters.
	 *
	 * @param array       $groups Registered setting groups.
	 * @param string      $active_tab Current active tab.
	 * @param string|null $module_param Module parameter from URL.
	 *
	 * @return array
	 */
	private function prepare_content_data( array $groups, string $active_tab, ?string $module_param ): array {
		$content_data = array();

		if ( 'modules' === $active_tab ) {
			$groups = array_filter(
				$groups,
				static function ( $group ) {
					return isset( $group['is_module'] ) && true === $group['is_module'];
				}
			);

			$content_data = $this->prepare_modules_content( $groups, $module_param );
		} elseif ( isset( $groups[ $active_tab ] ) ) {
			$content_data = $this->prepare_group_content( $active_tab );
		}

		return $content_data;
	}

	/**
	 * Prepares content data for modules tab.
	 *
	 * @param array       $groups Registered setting groups.
	 * @param string|null $module_param Module parameter from URL.
	 *
	 * @return array
	 */
	private function prepare_modules_content( array $groups, ?string $module_param ): array {
		$content_data = array(
			'type'         => 'modules',
			'modules_data' => array(
				'groups' => $groups,
			),
		);

		if ( $module_param && isset( $groups[ $module_param ] ) ) {
			$module_data = $this->process_module_request( $groups, $module_param );
			if ( $module_data ) {
				$content_data['module_settings'] = $module_data;
			}
		}

		return $content_data;
	}

	/**
	 * Processes a module request, handling redirects for disabled modules.
	 *
	 * @param array  $groups Registered setting groups.
	 * @param string $module_param Module parameter from URL.
	 *
	 * @return array|null Module data or null if redirected
	 */
	private function process_module_request( array $groups, string $module_param ): ?array {
		if ( empty( $groups[ $module_param ]['is_enabled'] ) ) {
			$this->handle_disabled_module_redirect();

			return null;
		}

		/**
		 * Get from DI container.
		 *
		 * @var ModuleManager $manager
		 */
		$manager = firevert_container()->get( 'module_manager' );
		$module  = $manager->get_module_by_slug( $module_param );

		return array(
			'groups'      => $groups,
			'module_slug' => $module_param,
			'module'      => $module,
		);
	}

	/**
	 * Handles redirect for disabled module requests.
	 *
	 * @return void
	 */
	private function handle_disabled_module_redirect(): void {
		set_transient( 'firevert_module_disabled', true, 30 );

		$redirect_url = ( new PageUrlBuilder() )->modules();

		wp_safe_redirect( $redirect_url );
		exit;
	}

	/**
	 * Prepares content data for regular group tabs.
	 *
	 * @param string $active_tab Current active tab.
	 *
	 * @return array
	 */
	private function prepare_group_content( string $active_tab ): array {
		$group = $this->registry->get_group( $active_tab );

		if ( ! $group ) {
			return array();
		}

		return array(
			'type'       => 'group',
			'group_data' => array(
				'group_slug' => $active_tab,
				'group'      => $group,
				'has_form'   => $group['has_form'] ?? true,
			),
		);
	}


	/**
	 * Gets the module parameter from URL.
	 *
	 * @return string|null
	 */
	private function get_module_param(): ?string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return isset( $_GET['module'] ) ? sanitize_text_field( wp_unslash( $_GET['module'] ) ) : null;
	}
}
