<?php

namespace ModernFields\WordPress\Services;

defined('ABSPATH') || exit;

/**
 * Manages the global modernFields JS data object.
 *
 * Call ScriptDataService::enqueue() from any Hook that needs the global.
 * The base object is output once; subsequent calls only merge their context.
 * Use the `modern-fields/admin/script_data` filter to inject additional data
 * (e.g. licence status from the premium plugin, or add-on namespaces).
 *
 * @since 1.0.1
 */
class ScriptDataService
{
  /**
   * Enqueues the modern-fields-global handle and outputs window.modernFields.
   *
   * Safe to call from multiple Hook classes on the same page: the base object
   * is written once (guarded by wp_script_is), additional context is merged
   * via Object.assign on every subsequent call.
   *
   * @since 1.0.1
   * @param array $contextData Page-specific data to merge into the global.
   * @return void
   */
  public static function enqueue(array $contextData = []): void
  {
    $isFirst = !wp_script_is('modern-fields-global', 'registered');

    wp_register_script('modern-fields-global', '', [], false, ['in_footer' => false]);
    wp_enqueue_script('modern-fields-global');

    if ($isFirst) {
      # Merge rather than assign: the admin bundle may have already attached
      # window.modernFields.router before this inline data runs.
      wp_add_inline_script(
        'modern-fields-global',
        'window.modernFields = Object.assign(window.modernFields || {}, ' . wp_json_encode(static::getData()) . ');',
        'before'
      );
    }

    if (!empty($contextData)) {
      wp_add_inline_script(
        'modern-fields-global',
        'Object.assign(window.modernFields, ' . wp_json_encode($contextData) . ');'
      );
    }
  }

  /**
   * Builds the full data array for window.modernFields.
   *
   * @since 1.0.1
   * @param array $contextData Optional data to merge on top of the base.
   * @return array
   */
  public static function getData(array $contextData = []): array
  {
    $base = [
      'version'   => MODERN_FIELDS_VERSION,
      'pluginUrl' => MODERN_FIELDS_PLUGIN_URL,
      'adminUrl'  => admin_url(),
      'isPremium' => (bool) apply_filters('modern-fields/license/is_premium', false),
      'rest'      => [
        'url'   => rest_url(MODERN_FIELDS_REST_NAMESPACE),
        'nonce' => wp_create_nonce('wp_rest'),
      ],
      'licence'   => [],
    ];

    $merged = array_replace_recursive($base, $contextData);

    return apply_filters('modern-fields/admin/script_data', $merged);
  }
}
