<?php
/**
 * Stores admin-configurable unit price meta key mappings.
 *
 * @package PhoenixWP\PriceLabels
 */

declare(strict_types=1);

namespace PhoenixWP\PriceLabels\Compliance;

defined( 'ABSPATH' ) || exit;

/**
 * Option wrapper for manual Grundpreis field mapping.
 */
final class Unit_Price_Settings {

	public const OPTION_KEY = 'phoenix_wp_price_labels_unit_price_settings';

	/**
	 * @return array{
	 *     mode: string,
	 *     formatted_meta: string,
	 *     unit_price_meta: string,
	 *     base_amount_meta: string,
	 *     product_amount_meta: string,
	 *     unit_meta: string
	 * }
	 */
	public static function get(): array {
		$defaults = self::defaults();
		$stored   = get_option( self::OPTION_KEY, array() );

		if ( ! is_array( $stored ) ) {
			return $defaults;
		}

		return array_merge( $defaults, array_intersect_key( $stored, $defaults ) );
	}

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

		$mode = isset( $input['mode'] ) ? sanitize_key( (string) $input['mode'] ) : 'auto';
		$clean['mode'] = in_array( $mode, array( 'auto', 'manual_only' ), true ) ? $mode : 'auto';

		foreach ( array( 'formatted_meta', 'unit_price_meta', 'base_amount_meta', 'product_amount_meta', 'unit_meta' ) as $field ) {
			$clean[ $field ] = isset( $input[ $field ] ) ? sanitize_key( (string) $input[ $field ] ) : '';
		}

		return $clean;
	}

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

	/**
	 * Whether manual-only mode is active.
	 */
	public static function is_manual_only(): bool {
		return 'manual_only' === self::get()['mode'];
	}

	/**
	 * Whether at least one custom meta mapping is configured.
	 */
	public static function has_manual_mapping(): bool {
		$settings = self::get();

		foreach ( array( 'formatted_meta', 'unit_price_meta', 'base_amount_meta', 'product_amount_meta', 'unit_meta' ) as $field ) {
			if ( '' !== $settings[ $field ] ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * @return array<string, string>
	 */
	private static function defaults(): array {
		return array(
			'mode'                => 'auto',
			'formatted_meta'      => '',
			'unit_price_meta'     => '',
			'base_amount_meta'    => '',
			'product_amount_meta' => '',
			'unit_meta'           => '',
		);
	}
}
