<?php

/**
 * @file
 * Custom theme hooks.
 */

declare(strict_types=1);

use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;

/**
 * Implements hook_library_info_alter().
 *
 *  Automatically creates components libraries (Not visible in theme's
 *  libraries.yml file). You can directly use the component name as a library,
 *  e.g.: {{ attach_library('droopler_theme/block') }}.
 */
function droopler_theme_library_info_alter(&$libraries, $extension) {
  if ($extension == 'droopler_theme') {
    $theme_handler = \Drupal::service('theme_handler');
    $theme_path = $theme_handler->getTheme('droopler_theme')->getPath();

    $extensions = ['css', 'js'];
    $directory = $theme_path . '/components';
    $extensions = array_map('preg_quote', $extensions);
    $extensions = implode('|', $extensions);

    \Drupal::logger('sandbox')->info('droopler_theme_library_info_build');
    if (!is_dir($directory)) {
      return [];
    }

    $file_scan = \Drupal::service('file_system')->scanDirectory(
      $directory,
      "#^(?!.*\/src\/).*\.(?:{$extensions})$#"
    );
    foreach ($file_scan as $file) {
      $parts = explode('.', $file->filename);
      $extension = end($parts);
      switch ($extension) {
        case 'css':
          $libraries[$file->name][$extension] = [
            'component' => [
              '/' . $file->uri => [],
            ],
          ];
          break;

        case 'js':
          $libraries[$file->name][$extension] = [
            '/' . $file->uri => [],
          ];
          break;
      }
    }
  }

  return $libraries;
}

/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function droopler_theme_preprocess_page(&$variables) {
  $variables['footer_primary_regions'] = [];

  foreach ($variables['page'] as $name => $data) {
    if (str_contains($name, 'footer_primary_') && !empty($data)) {
      $variables['footer_primary_regions'][] = $data;
    }
  }

  $variables['footer_primary_regions_count'] = count($variables['footer_primary_regions']);

  $route_name = \Drupal::routeMatch()->getRouteName();
  if (stripos($route_name, 'view.products_list') !== FALSE) {
    $pager_manager = \Drupal::service('pager.manager');
    if ($pager = $pager_manager->getPager(0)) {
      $variables['pager_total_items'] = $pager->getTotalItems();
    }
    $variables['#attached']['library'][] = 'd_product/d_product_searches';
  }

  // Remove title block from product listing and product page.
  $no_title_routes = [
    'entity.node.canonical',
    'entity.node.revision',
    'view.products_list.products_list',
  ];
  if (in_array($route_name, $no_title_routes)) {
    $node = $variables['node'] ?? NULL;
    if ($node && !($node instanceof NodeInterface)) {
      $node = Node::load($node);
    }
    if (!$node || $node->getType() == 'd_product') {
      foreach ($variables['page']['content'] as &$element) {
        if (isset($element['#plugin_id']) && $element['#plugin_id'] == 'page_title_block') {
          $element['#access'] = FALSE;
        }
      }
    }
  }

  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $variables['page']['content']['pagetitle']['#attributes']['class'] = ['blog-listing-main-header'];
  }
}
