<?php

/**
 * @file
 * Theme functions to support Vartheme BS5 theme.
 */

use Drupal\Core\Language\LanguageInterface;

/**
 * Implements hook_theme().
 */
function vartheme_bs5_theme($existing, $type, $theme, $path) {
  return [
    'media_oembed_iframe__remote_video__varbase_heroslider' => [
      'template' => 'media/media-oembed-iframe--remote-video--varbase-heroslider',
      'variables' => [
        'provider' => NULL,
        'media' => NULL,
        'base_path' => base_path(),
        'vartheme_bs5' => \Drupal::service('extension.list.theme')->getPath('vartheme_bs5'),
      ],
    ],
  ];
}

/**
 * Implements hook_preprocess_HOOK().
 */
function vartheme_bs5_preprocess_media_oembed_iframe__remote_video__varbase_heroslider(&$variables) {
  // Send variables for the remote_video varbase heroslier oembed iframe.
  $query = \Drupal::request()->query;
  $variables['type'] = $query->get('type');
  $variables['provider'] = $query->get('provider');
  $variables['view_mode'] = $query->get('view_mode');
  $variables['base_path'] = base_path();
  $variables['vartheme_bs5'] = \Drupal::service('extension.list.theme')->getPath('vartheme_bs5');
}

/**
 * Implements hook_library_info_alter().
 */
function vartheme_bs5_library_info_alter(array &$libraries, $module) {
  if ($module === 'sitewide_alert' && isset($libraries['init'])) {
    // Add the dependency only if it's not already present.
    if (!in_array('core/components.vartheme_bs5--alert', $libraries['init']['dependencies'])) {
      $libraries['init']['dependencies'][] = 'core/components.vartheme_bs5--alert';
    }
    unset($libraries['init']['css']);
  }

  // Load components root and styles for CKEditor5 styles.
  if ($module === 'ckeditor5' && isset($libraries['internal.drupal.ckeditor5.stylesheets'])) {
    $libraries['internal.drupal.ckeditor5.stylesheets']['dependencies'][] = 'vartheme_bs5/ckeditor5-root';
    $libraries['internal.drupal.ckeditor5.stylesheets']['dependencies'][] = 'vartheme_bs5/ckeditor5-styles';
  }

  // Replace the Popper.js library file from the Responsive Theme preview module.
  // Vartheme BS5 need a different version which still
  // works for the Responsive Theme preview module.
  if ($module === 'responsive_preview'
    && isset($libraries['drupal.responsive-preview'])
    && isset($libraries['drupal.responsive-preview']['js'])
    && isset($libraries['drupal.responsive-preview']['js']['js/popperjs/popper.min.js'])) {

    unset($libraries['drupal.responsive-preview']['js']['js/popperjs/popper.min.js']);
    $libraries['drupal.responsive-preview']['dependencies'][] = 'vartheme_bs5/popper-script';
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function vartheme_bs5_preprocess_field(&$variables) {
  $ckeditor5_fields = [
    'text_with_summary',
    'text_long',
  ];

  // Check if the field type is in the list of CKEditor5 fields.
  if (in_array($variables['field_type'], $ckeditor5_fields)) {
    // Attach the library to the field.
    $variables['#attached']['library'][] = 'vartheme_bs5/ckeditor5-styles';
  }
}

/**
 * Implements hook_preprocess().
 */
function vartheme_bs5_preprocess_menu(&$variables, $hook, $info) {
  // Checks the nested level of a menu.
  vartheme_bs5_process_menu_level($variables['items']);
}

/**
 * Add menu_link_level to menus.
 */
function vartheme_bs5_process_menu_level(&$menu_items, $menu_level = 1) {
  foreach ($menu_items as &$menu_item) {
    // Set the menu level for the current item.
    $menu_item['menu_link_level'] = $menu_level;

    // If there are child items, process them recursively.
    if (!empty($menu_item['below'])) {
      vartheme_bs5_process_menu_level($menu_item['below'], $menu_level + 1);
    }
  }
}

/**
 * Implements hook_preprocess_page().
 */
function vartheme_bs5_preprocess_page(&$variables) {
  // Add the print logo.
  $variables['logo_print'] = \Drupal::request()->getBaseUrl() . '/' . \Drupal::service('extension.list.theme')->getPath('vartheme_bs5') . '/logo-print.png';

  // Add the white logo.
  $variables['logo_white'] = \Drupal::request()->getBaseUrl() . '/' . \Drupal::service('extension.list.theme')->getPath('vartheme_bs5') . '/logo-white.svg';

  // Add the site name and slogan.
  $variables['site_name'] = \Drupal::config('system.site')->get('name');
  $variables['site_slogan'] = \Drupal::config('system.site')->get('slogan');

  $vartheme_bs5_contained_regions = [
    'container_top_bar',
    // 'container_navbar_branding',
    // 'container_navigation',
    // 'container_highlighted',
    'container_content_above',
    // 'container_primary_sidebar',
    'container_content',
    // 'container_secondary_sidebar',
    'container_content_below',
    'container_footer_top',
    'container_footer_bottom',
  ];

  foreach ($vartheme_bs5_contained_regions as $contained_region) {
    $theme_settings_for_contained_region = theme_get_setting($contained_region);
    if (isset($theme_settings_for_contained_region)
      && $theme_settings_for_contained_region !== '') {
      $variables[$contained_region] = $theme_settings_for_contained_region;
    }
  }

}

/**
 * Implements hook_preprocess_page_title().
 */
function vartheme_bs5_preprocess_page_title(&$variables) {

  // Hide page title for the front page and let screen readers only see it.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['title_attributes']['class'][] = 'visually-hidden';
  }
}

/**
 * Implements hook_preprocess_html().
 */
function vartheme_bs5_preprocess_html(&$variables) {

  // The path for Vartheme BS5 theme in variables.
  $variables['vartheme_bs5_path'] = \Drupal::request()->getSchemeAndHttpHost() . \Drupal::request()->getBaseUrl() . '/' . \Drupal::service('extension.list.theme')->getPath('vartheme_bs5');

}

/**
 * Implements hook_form_alter().
 */
function vartheme_bs5_form_alter(&$form, $form_state, $form_id) {

  // Have a default style for moderation entity form.
  if ($form_id == 'content_moderation_entity_moderation_form') {
    $form['#attributes']['class'][] = 'card card-body bg-light mb-3';
  }

  // Have a default style for the moderation status in the layout editing node pages.
  if ((preg_match('/^node_.*._layout_builder_form$/', $form_id)
    && isset($form['moderation_state']))) {
    $form['moderation_state']['#attributes']['class'][] = 'card card-body bg-light mb-3';
    $form['#attached']['library'][] = 'vartheme_bs5/content_moderation';
  }
}

/**
 * Implements hook_preprocess_login_with().
 */
function vartheme_bs5_preprocess_login_with(&$variables) {

  // Check if the Social Auth module exists and social networks are set.
  if (!\Drupal::moduleHandler()->moduleExists('social_auth') || empty($variables['networks'])) {
    return;
  }

  if (is_array($variables['networks']) && $variables['networks'] > 0) {
    foreach ($variables['networks'] as $id => $network) {
      $network_definition = $network->getPluginDefinition();
      if (isset($network_definition['img_path'])) {
        $theme_path = \Drupal::service('extension.list.theme')->getPath('vartheme_bs5');
        $network_img_path_in_vartheme = $theme_path . '/images/social_auth/' . $network_definition['provider'] . '/' . $network_definition['img_path'];

        if (file_exists(DRUPAL_ROOT . '/' . $network_img_path_in_vartheme)) {
          $variables['custom_networks'][$id] = [
            'img_path' => $network_img_path_in_vartheme,
          ];
        }
      }
    }
  }
}

/**
 * Implements hook_preprocess_region().
 */
function vartheme_bs5_preprocess_region(&$variables) {
  $isFront = \Drupal::service('path.matcher')->isFrontPage();
  if ($isFront && $variables["region"] === "header") {
    $variables["is_front"] = $isFront;
  }
}

/**
 * Implements hook_preprocess().
 */
function vartheme_bs5_preprocess(&$variables, $hook, $info) {
  $language = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
  $language_direction = $language->getDirection();
  $variables['lang_dir'] = $language_direction;
}
