<?php
/**
 * Settings screen service for building admin settings UI data.
 *
 * @package RewardsWP
 */

namespace Awesomemotive\Rewardswp\Services;

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

use Awesomemotive\Rewardswp\Factories\OptionsFactory;

class SettingsScreenService {
	/**
	 * Options factory instance.
	 *
	 * @since 1.0.0
	 *
	 * @var OptionsFactory
	 */
	private OptionsFactory $options_factory;

	/**
	 * Settings allowed.
	 *
	 * Separated by group.
	 *
	 * @since 1.0.0
	 *
	 * @var array|array[]
	 */
	protected array $settings = [
		'general'        => [
			'license',
			'currency',
			'brand_color',
		],
		'points'         => [
			'enabled',
			'currency_singular',
			'currency_plural',
			'points_expiration',
			'earn_actions',
			'spend_actions',
		],
		'referrals'      => [
			'enabled',
			'referral_slug',
			'cookie_expiration',
			'rewards',
			'sharing',
		],
		'rewards_widget' => [
			'launcher_display',
			'launcher_text',
			'launcher_position',
			'brand_foreground_color',
			'welcome_heading',
			'program_name',
		],
		'emails'         => [
			'from_email',
			'from_name',
			'email_logo',
		],
	];

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param OptionsFactory $options_factory The options factory instance.
	 */
	public function __construct( OptionsFactory $options_factory ) {
		$this->options_factory = $options_factory;
	}

	/**
	 * Get default options for the plugin.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	public function get_default_options(): array {
		$defaults = [];

		foreach ( $this->settings as $group => $options ) {
			foreach ( $options as $option_name ) {
				$option_obj = $this->options_factory->get_option( $option_name, $group );

				if ( is_null( $option_obj ) ) {
					continue;
				}

				$defaults[ $group ][ $option_name ] = $option_obj->get_default_value();
			}
		}

		return $defaults;
	}

	/**
	 * Sanitize settings before saving.
	 *
	 * @since 1.0.0
	 *
	 * @param array $settings The raw settings array.
	 *
	 * @return array The sanitized settings array.
	 */
	public function sanitize_settings( array $settings ): array {
		foreach ( $settings as $group => $options ) {
			if ( ! is_array( $options ) ) {
				continue;
			}

			foreach ( $options as $option_name => $option_value ) {
				$option_obj = $this->options_factory->get_option( $option_name, $group );

				if ( is_null( $option_obj ) ) {
					continue;
				}

				$settings[ $group ][ $option_name ] = $option_obj->sanitize( $option_value );
			}
		}

		return $settings;
	}
}
