<?php
/**
 * SettingsFormHandler class.
 *
 * Handles registration and sanitization of settings data via the WordPress Settings API.
 * Responsible for delegating saving logic to the CPT-based storage service.
 *
 * @package Ilabs\Firevert\Core\Settings\Form
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Settings\Form;

use Ilabs\Firevert\Core\Settings\Registry\SettingsRegistry;

/**
 * Handles registration and sanitization of settings using WordPress Settings API.
 */
final class SettingsFormHandler {

	/**
	 * Settings registry instance.
	 *
	 * @var SettingsRegistry
	 */
	private SettingsRegistry $registry;

	/**
	 * Settings storage service.
	 *
	 * @var SettingsStorageService
	 */
	private SettingsStorageService $storage;

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

	/**
	 * Registers the firevert_settings group with WordPress.
	 *
	 * @return void
	 */
	public function register(): void {
		register_setting(
			'firevert_settings',
			'firevert_settings',
			array(
				'type'              => 'array',
				'default'           => array(),
				'sanitize_callback' => array( $this, 'handle' ),
			)
		);
	}

	/**
	 * Sanitizes and stores settings data on save.
	 *
	 * @param array|null $input Raw input from settings form.
	 *
	 * @return array Always empty since we store everything manually via CPT.
	 */
	public function handle( ?array $input ): array {
		$input = is_array( $input ) ? $input : array();
		$input = array_map(
			static function ( $value ) {
				return is_array( $value )
					? array_map( 'sanitize_text_field', $value )
					: sanitize_text_field( $value );
			},
			$input
		);

		$modules_input = $input['modules'] ?? array();
		$module_slugs  = array_keys( $this->registry->get_module_groups() );

		foreach ( $module_slugs as $slug ) {
			$enabled = isset( $modules_input[ $slug ] ) ? '1' : '0';

			$this->storage->save_module_settings(
				$slug,
				array( 'enabled' => $enabled )
			);
		}

		$existing = get_option( 'firevert_settings', array() );

		return is_array( $existing ) ? $existing : array();
	}
}
