<?php
/**
 * Buttons module settings.
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Buttons_Settings
 */
class Rsmspark_Buttons_Settings {

	const OPTION_KEY = 'rsmspark_buttons_settings';

	/**
	 * @return array<string, mixed>
	 */
	public static function defaults() {
		return array(
			'show_list_preview'    => true,
			'use_theme_defaults'   => true,
			'new_button_defaults'  => array(),
		);
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function get() {
		$stored = get_option( self::OPTION_KEY, array() );
		if ( ! is_array( $stored ) ) {
			$stored = array();
		}

		return wp_parse_args( $stored, self::defaults() );
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function get_effective_new_button_defaults() {
		$base  = Rsmspark_Buttons_Config::base_defaults();
		$out   = $base;
		$settings = self::get();

		if ( ! empty( $settings['use_theme_defaults'] ) && class_exists( 'Rsmspark_Buttons_Theme_Defaults', false ) ) {
			$out = wp_parse_args( Rsmspark_Buttons_Theme_Defaults::get(), $out );
		}

		$partial = is_array( $settings['new_button_defaults'] ?? null ) ? $settings['new_button_defaults'] : array();
		if ( ! empty( $partial ) ) {
			$out = wp_parse_args( Rsmspark_Buttons_Config::sanitize( $partial ), $out );
		}

		return $out;
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function get_new_button_defaults() {
		return self::get_effective_new_button_defaults();
	}

	/**
	 * @return bool
	 */
	public static function show_list_preview() {
		$settings = self::get();
		return ! empty( $settings['show_list_preview'] );
	}

	/**
	 * @param array<string, mixed> $input Raw input.
	 * @return array<string, mixed>
	 */
	public static function sanitize( array $input ) {
		$out = wp_parse_args( $input, self::defaults() );

		$out['show_list_preview'] = ! empty( $out['show_list_preview'] );
		$out['use_theme_defaults'] = ! empty( $out['use_theme_defaults'] );

		$partial = is_array( $out['new_button_defaults'] ?? null ) ? $out['new_button_defaults'] : array();
		$out['new_button_defaults'] = Rsmspark_Buttons_Config::sanitize( $partial );

		return $out;
	}

	/**
	 * @param array<string, mixed> $settings Settings.
	 * @return void
	 */
	public static function save( array $settings ) {
		update_option( self::OPTION_KEY, self::sanitize( $settings ), false );
	}

	/**
	 * @return void
	 */
	public static function init() {
	}
}
