<?php

/**
 * @file
 * Theme and preprocess functions for commerce-related entities.
 */

/**
 * Implements hook_preprocess_commerce_product().
 */
function saklimarket_preprocess_commerce_product(&$variables) {
  // Manual region rendering.
  $region = 'product_info';
  $variables['product_info_region'] = [];
  $blocks = \Drupal::service('block.repository')->getVisibleBlocksPerRegion();
  if (isset($blocks[$region])) {
    foreach ($blocks[$region] as $block_id => $block) {
      $variables['product_info_region'][$block_id] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
    }
  }

  // Gather Specs (Dynamic Taxonomy fields on product).
  $product = $variables['product_entity'];
  $specs = [];

  foreach ($product->getFieldDefinitions() as $field_name => $field_definition) {
    // Only field_ fields that are entity references.
    if (strpos($field_name, 'field_') === 0 && $field_definition->getType() === 'entity_reference') {
      // Check if target type is taxonomy_term.
      if ($field_definition->getSetting('target_type') === 'taxonomy_term') {
        // Get the vocabulary (target_bundles).
        $handler_settings = $field_definition->getSetting('handler_settings');
        $target_bundles = $handler_settings['target_bundles'] ?? [];
        
        $is_attribute = false;
        foreach ($target_bundles as $vid) {
          $vocabulary = \Drupal\taxonomy\Entity\Vocabulary::load($vid);
          if ($vocabulary && $vocabulary->getThirdPartySetting('commerce_product_hub', 'is_product_attribute_vocabulary')) {
            $is_attribute = true;
            break;
          }
        }

        if ($is_attribute && !$product->get($field_name)->isEmpty()) {
          $label = $field_definition->getLabel();
          $values = [];
          foreach ($product->get($field_name)->referencedEntities() as $entity) {
            $values[] = $entity->label();
          }
          if (!empty($values)) {
            // Get weight from the display if possible.
            $display = \Drupal::service('entity_display.repository')
              ->getViewDisplay('commerce_product', $product->bundle(), $variables['elements']['#view_mode'] ?? 'default');
            $component = $display->getComponent($field_name);
            $weight = $component['weight'] ?? 0;

            $specs[] = [
              'label' => $label,
              'value' => implode(', ', $values),
              'weight' => $weight,
            ];
          }
        }
      }
    }
  }

  // Sort specs by weight.
  usort($specs, function($a, $b) {
    return $a['weight'] <=> $b['weight'];
  });

  $variables['product_specs'] = $specs;
}
