<?php

namespace Drupal\nodehive_core\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'variant_selector_widget' widget.
 *
 * @FieldWidget(
 *   id = "nodehive_variant_selector_widget",
 *   label = @Translation("Variant selector widget"),
 *   field_types = {
 *     "nodehive_variant_selector"
 *   }
 * )
 */
class NodeHiveVariantSelectorWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $field_settings = $this->getFieldSettings();
    $structured_variants = isset($field_settings['variants']) && is_array($field_settings['variants'])
      ? $field_settings['variants']
      : [];

    // Build the options array for the select list with optgroups.
    $options = [];
    if (!empty($structured_variants)) {
      foreach ($structured_variants as $variant) {
        $category = $variant['category'];
        $key = $variant['key'];
        $title = $variant['title'];
        $options[$category][$key] = $title;
      }
    }

    // Add the select list to the form.
    $element['variant'] = [
      '#type' => 'select',
      '#title' => $this->t('Variant'),
      '#options' => $options,
      '#default_value' => $items[$delta]->key ?? NULL,
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    foreach ($values as $delta => $value) {
      // Set the correct value structure for saving.
      $values[$delta]['key'] = $value['variant'];
    }
    return $values;
  }

}
