<?php

namespace ModernFields\FieldGroups\Services;

defined('ABSPATH') || exit;

/**
 * Reads the site options registered by Modern Fields field groups.
 *
 * Fields whose group targets an options-backed location (options page,
 * dashboard) are registered through register_setting() in the
 * 'modern_fields_options' group. This service returns their current values,
 * used as the initial state of the React apps rendering those groups.
 *
 * @since 1.3.0
 */
class OptionsService
{
  /**
   * Get all registered Modern Fields options with their current values.
   *
   * @since 1.3.0
   * @return array<string, mixed> Option values keyed by option name.
   */
  public static function getRegisteredOptions(): array
  {
    global $wp_registered_settings;

    $modern_fields_options = [];

    if (!is_array($wp_registered_settings)) {
      return $modern_fields_options;
    }

    foreach ($wp_registered_settings as $option_name => $settings) {
      if (!isset($settings['group']) || $settings['group'] !== 'modern_fields_options') {
        continue;
      }

      # No explicit default here: passing one to get_option() short-circuits
      # the default registered through register_setting() (see WordPress core
      # filter_default_option), which would hide the field's configured default.
      $value = get_option($option_name);

      # Never-saved option without a registered default: get_option() returns
      # false, fall back to the registered type's empty value so array and
      # object fields (checkboxes, repeater…) receive the shape they expect.
      if ($value === false && !isset($settings['default'])) {
        $value = match ($settings['type'] ?? 'string') {
          'array'   => [],
          'object'  => (object) [],
          'boolean' => false,
          default   => "",
        };
      }

      $modern_fields_options[$option_name] = $value;
    }

    return $modern_fields_options;
  }
}
