<?php

declare(strict_types=1);

namespace Drupal\sobki_theme_bootstrap\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
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['items']) || !\is_array($variables['items'])) {
      return;
    }

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

      $attributes = $item['url']->getOption('attributes');
      if (!\is_array($attributes)) {
        continue;
      }

      if (!isset($attributes['data-simple-mega-menu']) || empty($attributes['data-simple-mega-menu'])) {
        continue;
      }

      /** @var string $simple_mega_menu_id */
      $simple_mega_menu_id = $attributes['data-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');
      }
    }
  }

}
