<?php
/**
 * SettingsRenderer class.
 *
 * Renders the settings view for PromoTimeWidget module.
 *
 * @package Ilabs\Firevert\Modules\PromoTimeWidget\Services\Render
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Modules\PromoTimeWidget\Services\Render;

use Ilabs\Firevert\Core\Form\FormHandler;
use Ilabs\Firevert\Core\Services\Builder\PageUrlBuilder;
use Ilabs\Firevert\Modules\PromoTimeWidget\Services\Repository\PromoTimeWidgetRepository;
use Ilabs\Firevert\Modules\PromoTimeWidget\Services\Type\ModuleType;
use Ilabs\Firevert\Modules\PromoTimeWidget\Services\Type\SectionType;
use WP_Post;

use function firevert_container;
use function firevert_module_view;

/**
 * Class SettingsRenderer.
 */
final class SettingsRenderer {

	/**
	 * Renders the full settings view.
	 *
	 * @return void
	 */
	public function render(): void {
		$post    = $this->get_or_create_post();
		$section = $this->get_current_section();
		$data    = $this->get_section_data( $post, $section );

		$page_url_builder = new PageUrlBuilder();
		$base_url         = $page_url_builder->module( ModuleType::MODULE_SLUG );

		$data['post'] = $post;

		firevert_module_view(
			'PromoTimeWidget',
			'settings.view.php',
			array(
				'data'     => $data,
				'section'  => $section,
				'base_url' => $base_url,
			)
		);
	}

	/**
	 * Retrieves the main PromoTimeWidget post or creates one if not found.
	 *
	 * @return WP_Post
	 */
	public function get_or_create_post(): WP_Post {
		/**
		 * Get from container DI.
		 *
		 * @var PromoTimeWidgetRepository $repository
		 */
		$repository = firevert_container()->get( 'repository', ModuleType::MODULE_SLUG );

		return $repository->get_or_create_main();
	}

	/**
	 * Retrieves the current section from the query string.
	 *
	 * @return string
	 */
	private function get_current_section(): string {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return isset( $_GET['section'] ) ? sanitize_key( wp_unslash( $_GET['section'] ) ) : SectionType::SETTINGS;
	}

	/**
	 * Retrieves the form data array for the given section and post.
	 *
	 * @param WP_Post $post PromoTimeWidget post.
	 * @param string  $section Section slug.
	 *
	 * @return array<string, mixed> Form data.
	 */
	private function get_section_data( WP_Post $post, string $section ): array {
		$data          = array();
		$handler_class = SectionType::get_handler( $section );

		if ( $handler_class && class_exists( $handler_class ) ) {
			/**
			 * Create new FormHandler class
			 *
			 * @var FormHandler $handler
			 */
			$handler = new $handler_class( $post );
			$data    = $handler->get_data();
		}

		return $data;
	}
}
