<?php

/**
 * @file
 * Contains field_group_label.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function field_group_label_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the field_group_label module.
    case 'help.page.field_group_label':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Field Group Label') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_field_group_pre_render().
 */
function field_group_label_field_group_pre_render(&$element, $group, $rendering_object) {

  // Search inside field group childrens for field group label field types.
  foreach ($group->children as $children_key) {
    if (!empty($element[$children_key]['#field_type']) && $element[$children_key]['#field_type'] == 'field_group_label_field_type') {
      $label = $element[$children_key]['#field_group_label'] ?? NULL;
      // Only override if value is not empty, otherwise preserve original label.
      if (!empty($label)) {
        $element['#title'] = $label;
        $group->label = $label;
      }
      // Clean children field to prevent showing field group when empty.
      unset($element[$children_key]);

      // Just use first one, others will be ignored.
      break;
    }
  }
}
