<?php

declare(strict_types=1);

namespace Drupal\sobki_theme_bootstrap\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Template\AttributeValueBase;
use Drupal\simple_megamenu\Entity\SimpleMegaMenuInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Ensure menu structure fits into links prop structure.
 */
class PreprocessMenu implements ContainerInjectionInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
  ) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static($container->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   *
   * @SuppressWarnings(PHPMD.CyclomaticComplexity)
   */
  public function preprocess(array &$variables): void {
    if (!isset($variables['preprocessed_items']) || !\is_array($variables['preprocessed_items'])) {
      return;
    }

    // Only handle first level links.
    foreach ($variables['preprocessed_items'] as &$item) {
      if (!isset($item['link_attributes']) || !($item['link_attributes'] instanceof Attribute)) {
        continue;
      }

      if (!$item['link_attributes']->hasAttribute('data-simple-mega-menu')) {
        continue;
      }

      $attributeValue = $item['link_attributes']->offsetGet('data-simple-mega-menu');
      if (!$attributeValue instanceof AttributeValueBase) {
        continue;
      }

      $simple_mega_menu_id = $attributeValue->value();
      /** @var \Drupal\simple_megamenu\Entity\SimpleMegaMenuInterface $simple_mega_menu */
      $simple_mega_menu = $this->entityTypeManager->getStorage('simple_mega_menu')
        ->load($simple_mega_menu_id);
      if ($simple_mega_menu instanceof SimpleMegaMenuInterface) {
        if (!$simple_mega_menu->access('view')) {
          continue;
        }
        $viewBuilder = $this->entityTypeManager->getViewBuilder('simple_mega_menu');
        $item['megamenu'] = $viewBuilder->view($simple_mega_menu, 'default');
      }
    }
  }

}
