<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Site\Settings;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\kamihaya_digitalagency\KamihayaSettingsManager;
use Drupal\menu_link_content\MenuLinkContentInterface;
use Drupal\user\Entity\User;

/**
 * @file
 * Kamihaya デジタル庁デザインシステム準拠テーマ theme file.
 */

 /**
 * Implements hook_form_FORM_ID_alter().
 */
function kamihaya_digitalagency_form_system_theme_settings_alter(&$form, FormStateInterface $form_state, $form_id = NULL) {
  $settings_manager = new KamihayaSettingsManager(\Drupal::service('theme.manager'));
  return $settings_manager->themeSettingsAlter($form, $form_state, $form_id);
}

/**
 * Implements hook_preprocess_pager().
 */
function kamihaya_digitalagency_preprocess_pager(&$variables) {
  $element = $variables['pager']['#element'];
  /** @var \Drupal\Core\Pager\PagerManagerInterface $pager_manager */
  $pager_manager = \Drupal::service('pager.manager');
  $pager = $pager_manager->getPager($element);
  if (!$pager) {
    return;
  }
  $variables['pager_max'] = $pager->getTotalPages();
 }

/**
 * Implements hook_preprocess_views_mini_pager().
 */
function kamihaya_digitalagency_preprocess_views_mini_pager(&$variables) {
  /** @var \Drupal\Core\Pager\PagerManagerInterface $pager_manager */
  $pager_manager = \Drupal::service('pager.manager');

  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $pager = $pager_manager->getPager($element);
  if (!$pager) {
    return;
  }

  $items = &$variables['items'];
  $current = $pager->getCurrentPage();
  $total = $pager->getTotalPages();

  $route_name = '<current>';
  $route_parameters = $variables['pager']['#route_parameters'] ?? [];

  $variables['pager_max'] = $total;

  // Create the "first" and "previous" links if we are not on the first page.
  if ($current > 0) {
    $items['first'] = [];
    $items['first']['attributes'] = new Attribute();
    $options = [
      'query' => $pager_manager->getUpdatedParameters($parameters, $element, 0),
    ];
    $items['first']['href'] = Url::fromRoute($route_name, $route_parameters, $options)->toString();
  }

  // Create the "next" and "last" links if we are not on the last page.
  if ($current < ($total - 1)) {
    $items['last'] = [];
    $items['last']['attributes'] = new Attribute();
    $options = [
      'query' => $pager_manager->getUpdatedParameters($parameters, $element, $total - 1),
    ];
    $items['last']['href'] = Url::fromRoute($route_name, $route_parameters, $options)->toString();
  }
 }

 /**
 * Implements hook_theme_suggestions_alter().
 */
function kamihaya_digitalagency_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook === 'views_view_grid') {
    $suggestions[] = $hook . '__' . $variables['view']->id() . '_' . $variables['view']->current_display;
  }
  if ($hook === 'views_view') {
    $suggestions[] = $hook . '__' . $variables['view']->id();
  }
  if ($hook === 'user') {
    $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
    $suggestions[] = 'user__' . $sanitized_view_mode;
  }
  if ($hook === 'node'
    && !empty($variables['elements']['#node'])
    && strpos($variables['elements']['#node']->getType(), 'kamihaya') === 0) {
    $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
    $suggestions[] = 'node__kamihaya';
    $suggestions[] = "node__{$variables['elements']['#node']->getType()}";
    $suggestions[] = "node__$sanitized_view_mode";
    $suggestions[] = "node__kamihaya__$sanitized_view_mode";
    $suggestions[] = "node__{$variables['elements']['#node']->getType()}__$sanitized_view_mode";
  }
  if ($hook === 'taxonomy_term') {
    $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
    $suggestions[] = "taxonomy_term__$sanitized_view_mode";
    $suggestions[] = "taxonomy_term__{$variables['elements']['#taxonomy_term']->bundle()}__$sanitized_view_mode";
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function kamihaya_digitalagency_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Content type specific twig suggestion.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if (is_object($node)) {
      $content_type = $node->bundle();
      $suggestions[] = 'page__' . $content_type;
      $paths = explode('/', $node->toUrl()->toString());
      $suggest = '';
      foreach($paths as $path) {
        if (empty($path)) {
          continue;
        }
        $suggest .= "_$path";
        $suggestions[] = 'page__' . $content_type . '_' . $suggest;
      }
    }
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function kamihaya_digitalagency_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if (isset($variables['attributes']['data-block']['region'])) {
    $region = $variables['attributes']['data-block']['region'];
    foreach ($suggestions as $key => $suggestion) {
      if ($suggestion === "menu__$region") {
        unset($suggestions[$key]);
        $suggestions = array_merge(["menu__$region"], $suggestions);
        break;
      }
    }
  }
}


 /**
 * Implements hook_preprocess_node().
 */
function kamihaya_digitalagency_preprocess_node(array &$variables) {
  $variables['#attached']['library'][] = 'kamihaya_digitalagency/node';
  if ($variables['elements']['#node']->bundle() === 'recruitment' && $variables['view_mode'] === 'apply_form') {
    $user = User::load(Drupal::currentUser()->id());
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('user');

    $variables['profile'] = $view_builder->view($user, 'profile');
    $variables['resume'] =  $view_builder->view($user, 'resume');
  }

  if ($variables['elements']['#node']->bundle() === 'kamihaya_article') {
    $variables['#attached']['library'][] = 'kamihaya_digitalagency/node-kamihaya-article';
    $variables['show_post_date'] = theme_get_setting('teaser_show_post_date');
    $variables['show_author_info'] = theme_get_setting('teaser_show_author_info');
  }
}

/**
 * Implements hook_preprocess_layout().
 */
function kamihaya_digitalagency_preprocess_layout(array &$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if (empty($node)) {
    return;
  }
  $variables['#attached']['library'][] = 'kamihaya_digitalagency/node';
}

 /**
 * Implements hook_preprocess_user().
 */
function kamihaya_digitalagency_preprocess_user(array &$variables) {
  $variables['#attached']['library'][] = 'kamihaya_digitalagency/user';
  $variables['view_mode'] = $variables['elements']['#view_mode'];
}

 /**
 * Implements hook_preprocess_view().
 */
function kamihaya_digitalagency_preprocess_views_view(array &$variables) {
  $variables['#attached']['library'][] = 'kamihaya_digitalagency/view';
  if (\Drupal::moduleHandler()->moduleExists('kamihaya_cms_paragraph_type')) {
    $variables['#attached']['library'][] = 'kamihaya_cms_paragraph_type/heading-css';
  }
  $view = $variables['view'];
  if (!empty($view->getStyle()->getPluginId())) {
    $variables['format'] = str_replace('_', '-', $view->getStyle()->getPluginId());
  }
  $display_links = [];
  foreach ($variables['header'] as $key => $header) {
    if (strpos($key, 'display_link') === 0) {
      $display_links[] = $header;
      unset($variables['header'][$key]);
    }
  }
  if (!empty($display_links)) {
    $variables['header']['display_links'] = [
      '#theme' => 'item_list',
      '#items' => $display_links,
      '#attributes' => [
        'class' => ['display-links'],
      ],
    ];
  }
}

/**
 * Implements hook_preprocess_breadcrumb().
 */
function kamihaya_digitalagency_preprocess_breadcrumb(&$variables){
  $breadcrumb = [];
  foreach($variables['breadcrumb'] as $item) {
    if ($idx = array_search($item['text'], $breadcrumb)) {
      unset($variables['breadcrumb'][$idx]);
      continue;
    }
    $breadcrumb[] = is_array($item['text']) && !empty($item['text']['#markup']) ? $item['text']['#markup'] : $item['text'];
  }
  if(($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    $variables['#cache']['contexts'][] = 'url.path';
    $variables['#cache']['tags'][] = 'node:' . $node->id();
  }
}

 /**
 * Implements hook_preprocess_tb_megamenu_item().
 */
function kamihaya_digitalagency_preprocess_tb_megamenu_item(array &$variables) {
  if (empty($variables['item']->link->getOptions()['container_attributes'])) {
    return;
  }

  $custom_attributes = [
    'font_awesome_class',
    'hide_label',
    'menu_icon_image',
    'menu_icon_image_alt',
    'menu_icon_image_height',
  ];
  foreach($variables['item']->link->getOptions()['container_attributes'] as $key => $value) {
    if (in_array($key, $custom_attributes)) {
      if ($key === 'menu_icon_image' && is_array($value)) {
        $fid = reset($value);
        $file = File::load($fid);
        if (empty($file)) {
          continue;
        }
        $file_url = $file->createFileUrl();
        $value = $file_url;
      }
      $variables[$key] = $value;
      continue;
    }
    $variables['attributes']->setAttribute($key, $value);
  }
}

/**
 * Implements template_preprocess_menu().
 */
function kamihaya_digitalagency_preprocess_menu(array &$variables) {
   _kamihaya_digitalagency_preprocess_menu_items($variables['items']);
}

/**
 * Implements hook_preprocess_paragraph().
 */
function kamihaya_digitalagency_preprocess_paragraph(array &$variables) {
  $paragraph = $variables['paragraph'];
  if ($paragraph->bundle() === 'embed_tag') {
    $variables['raw_text'] = $variables['content']['field_embed_tag']['0']['#markup'];
  }
}

 /**
 * Implements hook_preprocess_commerce_product().
 */
function kamihaya_digitalagency_preprocess_commerce_product(array &$variables) {
  $variables['#attached']['library'][] = 'kamihaya_digitalagency/product';
}

/**
 * Helper function to recursively set the font awesome information.
 */
function _kamihaya_digitalagency_preprocess_menu_items(array &$items) {
  foreach ($items as &$item) {
    /** @var \Drupal\Core\Menu\MenuLinkInterface $menu_link */
    $menu_link = $item['original_link'] ?? NULL;
    if (!empty($menu_link)) {
      $options = ($menu_link instanceof MenuLinkContentInterface)
        ? $menu_link->link->first()->options
        : $menu_link->getOptions();
      if (empty($item['attributes'])) {
        continue;
      }
      if ($item['attributes']->hasAttribute('font_awesome_class') || $item['attributes']->hasAttribute('menu_icon_image')) {
        if (!empty($item['attributes']->offsetGet('hide_label')) && !empty($item['attributes']->offsetGet('hide_label')->value())) {
          $item['hide_label'] = $item['attributes']->offsetGet('hide_label')->value();
        }
        if ($item['attributes']->offsetGet('font_awesome_class')) {
          $item['font_awesome_class'] = $item['attributes']->offsetGet('font_awesome_class');
        }
        if (!empty($item['attributes']->offsetGet('menu_icon_image')) && $item['attributes']->offsetGet('menu_icon_image')->value()) {
          $fid = $item['attributes']->offsetGet('menu_icon_image')->value();
          $fid = is_array($fid) ? reset($fid) : $fid;
          $file = File::load($fid);
          if (!empty($file)) {
            $file_url = $file->createFileUrl();
            $item['menu_icon_image'] = $file_url;
            if ($item['attributes']->hasAttribute('menu_icon_image_alt') && !empty($item['attributes']->offsetGet('menu_icon_image_alt'))) {
              $item['menu_icon_image_alt'] = $item['attributes']->offsetGet('menu_icon_image_alt');
            }
            if ($item['attributes']->hasAttribute('menu_icon_image_height') && !empty($item['attributes']->offsetGet('menu_icon_image_height')->value())) {
              $item['menu_icon_image_height'] = $item['attributes']->offsetGet('menu_icon_image_height')->value();
            }
          }
        }
      }
      $item['attributes']->removeAttribute('font_awesome_class');
      $item['attributes']->removeAttribute('hide_label');
      $item['attributes']->removeAttribute('menu_icon_image');
      $item['attributes']->removeAttribute('menu_icon_image_alt');
      $item['attributes']->removeAttribute('menu_icon_image_height');
    }
    if (!empty($item['below'])) {
      _kamihaya_digitalagency_preprocess_menu_items($item['below']);
    }
  }
}

 /**
 * Implements hook_preprocess_html().
 */
function kamihaya_digitalagency_preprocess_html(array &$variables) {
  if (theme_get_setting('b5_navbar_schema') === 'custom') {
    $variables['attributes']['class'][] = 'navbar-custom';
  }
  // Navbar colour theme.
  $variables['b5_navbar_schema'] = theme_get_setting('b5_navbar_schema');
  $variables['b5_navbar_bg_schema'] = theme_get_setting('b5_navbar_bg_schema');
  // Footer colour theme.
  $variables['b5_footer_schema'] = theme_get_setting('b5_footer_schema');
  $variables['b5_footer_bg_schema'] = theme_get_setting('b5_footer_bg_schema');
  $back_to_top_type = \Drupal::config('back_to_top.settings')->get('back_to_top_button_type');
  if (!empty(theme_get_setting('b5_back_to_top_shape')) && $back_to_top_type === 'text') {
    $variables['back_to_top_shape'] = theme_get_setting('b5_back_to_top_shape');
  }
  if (!empty($back_to_top_type)) {
    $variables['back_to_top_type'] = $back_to_top_type;
  }
}

 /**
 * Implements hook_preprocess_page().
 */
function kamihaya_digitalagency_preprocess_page(array &$variables) {
  if (!empty(theme_get_setting('b5_navbar_sp_position'))) {
    $variables['menu_sp_position'] = theme_get_setting('b5_navbar_sp_position');
  }
  if (!empty(theme_get_setting('b5_footer_width_ratio'))) {
    $variables['footer_width_ratio'] = theme_get_setting('b5_footer_width_ratio');
  }
  if (!empty(theme_get_setting('b5_navbar_sp_revert'))) {
    $variables['navbar_sp_revert'] = theme_get_setting('b5_navbar_sp_revert');
  }
  if (!empty(theme_get_setting('b5_footer_sp_rightt_top'))) {
    $variables['footer_sp_rightt_top'] = theme_get_setting('b5_footer_sp_rightt_top');
  }
  if (!empty($variables['page']['header_left'])) {
    foreach ($variables['page']['header_left'] as $key => $value) {
      if (strpos($key, '#') === 0) {
        continue;
      }
      if (strpos($key, 'branding') === FALSE) {
        break;
      }
      $variables['header_left_logo_only'] = TRUE;
      break;
    }
  }
}

/**
 * Implements hook_preprocess_field().
 */
function kamihaya_digitalagency_preprocess_field(&$variables, $hook) {
  if (!empty($variables['field_type']
    && $variables['field_type'] === 'color_field_type')
    && !empty($variables['element']['#formatter'])
    && $variables['element']['#formatter'] === 'color_field_formatter_swatch'
    && !empty($variables['element'][0]['#attributes'])) {
    $entity = $variables['element']['#object'];
    $variables['element'][0]['#attributes']->setAttribute('title', $entity->label());
    $variables['element'][0]['#attributes']->setAttribute('data-bs-toggle', 'tooltip');
    $variables['element'][0]['#attributes']->setAttribute('data-bs-placement', 'top');
    $variables['#attached']['library'][] = 'kamihaya_digitalagency/color_swatch';
  }

  if (!empty($variables['field_type'])
    && $variables['field_type'] === 'link'
    && !empty($variables['items'])) {
    foreach ($variables['items'] as &$item) {
      if (!empty($item['content']['#url']) && $item['content']['#url'] instanceof Url) {
        $url = $item['content']['#url'];
        // Add target and rel attributes to external links.
        if ($url->isExternal() && $url->getOption('attributes') === NULL) {
          $url->setOptions([
            'attributes' => [
              'target' => '_blank',
              'rel' => 'noopener noreferrer',
            ],
          ]);
        }
      }
    }
  }
}


 /**
 * Implements hook_preprocess_block().
 */
function kamihaya_digitalagency_preprocess_block(array &$variables) {
  if (!empty($variables['plugin_id']) && $variables['plugin_id'] === 'page_title_block') {
    /** @var \Drupal\Entity\FieldableEntityInterface $entity */
    $entity = !empty(\Drupal::routeMatch()->getParameter('node'))
      ? \Drupal::routeMatch()->getParameter('node')
      : \Drupal::routeMatch()->getParameter('taxonomy_term');

    if (empty($entity)) {
      return;
    }
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $fields = $display_repository->getViewDisplay($entity->getEntityTypeId(), $entity->bundle())->getThirdPartySetting('ds', 'fields');
    if (!empty($fields) && !empty($title = $fields['node_title']) && !empty($title['settings']['class']) && strpos($title['settings']['class'], 'sp-hidden') !== FALSE) {
      // Hide title if title fiels is displayed in the layout.
      if (empty($variables['attributes']['class'])) {
        $variables['attributes']['class'] = [];
      }
      $variables['attributes']['class'][] = 'pc-hidden';
      return;
    }

    if (empty($fields['node_title']) && (!$entity->hasField('field_not_display_title') || empty($entity->get('field_not_display_title')->value))) {
      return;
    }
    $variables['content']['#access'] = FALSE;
  }
  if (!empty($variables['plugin_id']) && $variables['plugin_id'] === 'system_branding_block' && !empty(theme_get_setting('logo_url'))) {
    $variables['logo_url'] = theme_get_setting('logo_url');
    $url = Url::fromUri(theme_get_setting('logo_url'));
    if ($url->isExternal()) {
      $variables['logo_url_external'] = TRUE;
    }
  }
}

 /**
 * Implements hook_preprocess_file_link().
 */
function kamihaya_digitalagency_preprocess_file_link(array &$variables) {
  if (!empty($variables['file_size']) && !empty($variables['link']['#title'])) {
    $file_size = $variables['file_size'];
    $link_title = $variables['link']['#title'];
    $variables['link']['#title'] = Markup::create("{$link_title} [{$file_size}]");
    $variables['file_size'] = '';
  }
  $url = $variables['link']['#url'];
  $ext = pathinfo($variables['file']->getFilename(), PATHINFO_EXTENSION);
  $ext = strtolower($ext);

  if ($url instanceof Url && $ext === 'pdf') {
    // Add target and rel attributes to the URL if the file is a PDF.
    $url->setOptions([
      'attributes' => [
        'target' => '_blank',
        'rel' => 'noopener',
      ],
    ]);
    $variables['link']['#url'] = $url;
  }
}

/**
 * Implements hook_preprocess_views_view_table().
 */
function kamihaya_digitalagency_preprocess_views_view_table(&$variables) {
  $rows = $variables['rows'];

  if (empty($rows)) {
    return;
  }
  $row = $rows[0];
  if (empty($row['attributes']['class'])) {
    return;
  }
  $variables['header_attributes'] = new Attribute();
  $variables['header_attributes']->addClass($row['attributes']->getClass()->value());
}

/**
 * Implements hook_page_attachments_alter().
 */
function kamihaya_digitalagency_page_attachments_alter(array &$page) {
  $css_vars = [
    ':root' => [],
    '.navbar' => [],
    '.navbar .dropdown-menu' => [],
    'footer' => [],
  ];
  if (theme_get_setting('b5_body_schema') === 'custom') {
    if (!empty(theme_get_setting('b5_body_text_color'))) {
      $css_vars[':root']['--bs-body-color'] = theme_get_setting('b5_body_text_color');
    }
    if (!empty(theme_get_setting('b5_body_link_color'))) {
      $css_vars[':root']['--bs-link-color'] = theme_get_setting('b5_body_link_color');
    }
    if (!empty(theme_get_setting('b5_body_link_hover_color'))) {
      $css_vars[':root']['--bs-link-hover-color'] = theme_get_setting('b5_body_link_hover_color');
      if (empty(theme_get_setting('b5_body_link_active_color'))) {
        $css_vars[':root']['--bs-link-active-color'] = theme_get_setting('b5_body_link_hover_color');
      }
    }
  }
  if (theme_get_setting('b5_body_bg_schema') === 'custom') {
    if (!empty(theme_get_setting('b5_body_bg_schema_custom'))) {
      $css_vars[':root']['--bs-body-bg'] = theme_get_setting('b5_body_bg_schema_custom');
    }
    if (!empty(theme_get_setting('b5_body_light_bg_schema_custom'))) {
      $css_vars[':root']['--bs-light'] = theme_get_setting('b5_body_light_bg_schema_custom');
    }
    if (!empty(theme_get_setting('b5_body_secondary_bg_schema_custom'))) {
      $css_vars[':root']['--bs-secondary-bg'] = theme_get_setting('b5_body_secondary_bg_schema_custom');
    }
  }

  if (!empty(theme_get_setting('site_max_width'))) {
    $css_vars[':root']['--bs-site-max-width'] = theme_get_setting('site_max_width') . 'px';
  }

  if (theme_get_setting('b5_navbar_schema') === 'custom') {
    if (!empty(theme_get_setting('b5_navbar_text_color'))) {
      $css_vars['.navbar']['--bs-navbar-color'] = theme_get_setting('b5_navbar_text_color');
    }
    if (!empty(theme_get_setting('b5_navbar_link_color'))) {
      $css_vars['.navbar']['--bs-navbar-link-color'] = theme_get_setting('b5_navbar_link_color');
      $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-color'] = theme_get_setting('b5_navbar_link_color');
    }
    if (!empty(theme_get_setting('b5_navbar_link_hover_color'))) {
      $css_vars['.navbar']['--bs-navbar-hover-color'] = theme_get_setting('b5_navbar_link_hover_color');
      $css_vars['.navbar']['--bs-navbar-link-hover-color'] = theme_get_setting('b5_navbar_link_hover_color');
      if (empty(theme_get_setting('b5_navbar_link_active_color'))) {
        $css_vars['.navbar']['--bs-navbar-link-active-color'] = theme_get_setting('b5_navbar_dropdown_hover_color');
      }
      if (empty(theme_get_setting('b5_navbar_dropdown_hover_color'))) {
        $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-hover-color'] = theme_get_setting('b5_navbar_dropdown_hover_color');
      }
      if (empty(theme_get_setting('b5_navbar_dropdown_active_color'))) {
        $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-active-color'] = theme_get_setting('b5_navbar_dropdown_hover_color');
      }
    }
    if (!empty(theme_get_setting('b5_navbar_link_active_color'))) {
      $css_vars['.navbar']['--bs-navbar-active-color'] = theme_get_setting('b5_navbar_link_active_color');
      $css_vars['.navbar']['--bs-navbar-link-active-color'] = theme_get_setting('b5_navbar_link_active_color');
      if (empty(theme_get_setting('b5_navbar_dropdown_active_color'))) {
        $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-active-color'] = theme_get_setting('b5_navbar_dropdown_hover_color');
      }
    }
    if (!empty(theme_get_setting('b5_navbar_dropdown_hover_color'))) {
      $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-hover-color'] = theme_get_setting('b5_navbar_dropdown_hover_color');
      if (empty(theme_get_setting('b5_navbar_dropdown_active_color'))) {
        $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-active-color'] = theme_get_setting('b5_navbar_dropdown_hover_color');
      }
    }
    if (!empty(theme_get_setting('b5_navbar_dropdown_hover_bk_color'))) {
      $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-hover-bg'] = theme_get_setting('b5_navbar_dropdown_hover_bk_color');
      if (!empty(theme_get_setting('b5_navbar_dropdown_active_bg_color'))) {
        $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-active-bg'] = theme_get_setting('b5_navbar_dropdown_hover_bk_color');
      }
    }
    if (!empty(theme_get_setting('b5_navbar_dropdown_active_color'))) {
      $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-active-color'] = theme_get_setting('b5_navbar_dropdown_active_color');
    }
    if (!empty(theme_get_setting('b5_navbar_dropdown_active_bg_color'))) {
      $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-active-bg'] = theme_get_setting('b5_navbar_dropdown_active_bg_color');
    }
  }

  if (theme_get_setting('b5_navbar_bg_schema') === 'custom') {
    if (!empty(theme_get_setting('b5_navbar_bg_schema_custom'))) {
      $css_vars['.navbar']['--bs-navbar-bg'] = theme_get_setting('b5_navbar_bg_schema_custom');
      $css_vars['.navbar .dropdown-menu']['--bs-dropdown-bg'] = theme_get_setting('b5_navbar_bg_schema_custom');
      if (empty(theme_get_setting('b5_navbar_dropdown_hover_bk_color'))) {
        $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-hover-bg'] = theme_get_setting('b5_navbar_dropdown_hover_bk_color');
      }
      if (empty(theme_get_setting('b5_navbar_dropdown_active_bg_color'))) {
        $css_vars['.navbar .dropdown-menu']['--bs-dropdown-link-active-bg'] = theme_get_setting('b5_navbar_dropdown_hover_bk_color');
      }
    }
    if (!empty(theme_get_setting('b5_navbar_secondary_bg_schema_custom'))) {
      $css_vars['.navbar']['--bs-navbar-secondary-bg'] = theme_get_setting('b5_navbar_secondary_bg_schema_custom');
    }
  }
  if (theme_get_setting('b5_footer_schema') === 'custom') {
    if (!empty(theme_get_setting('b5_footer_text_color'))) {
      $css_vars['footer']['--bs-footer-color'] = theme_get_setting('b5_footer_text_color');
    }
    if (!empty(theme_get_setting('b5_footer_link_color'))) {
      $css_vars['footer']['--bs-footer-link-color'] = theme_get_setting('b5_footer_link_color');
    }
    if (!empty(theme_get_setting('b5_footer_link_hover_color'))) {
      $css_vars['footer']['--bs-footer-link-hover-color'] = theme_get_setting('b5_footer_link_hover_color');
      if (empty(theme_get_setting('b5_footer_link_active_color'))) {
        $css_vars['footer']['--bs-footer-link-active-color'] = theme_get_setting('b5_footer_link_hover_color');;
      }
    }
    if (!empty(theme_get_setting('b5_footer_link_active_color'))) {
      $css_vars['footer']['--bs-footer-link-active-color'] = theme_get_setting('b5_footer_link_active_color');
    }
  }
  if (theme_get_setting('b5_footer_bg_schema') === 'custom') {
    if(!empty(theme_get_setting('b5_footer_bg_schema_custom'))) {
      $css_vars['footer']['--bs-footer-bg'] = theme_get_setting('b5_footer_bg_schema_custom');
    }
    if(!empty(theme_get_setting('b5_footer_secondary_bg_schema_custom'))) {
      $css_vars['footer']['--bs-footer-secondary-bg'] = theme_get_setting('b5_footer_secondary_bg_schema_custom');
    }
  }

  if (theme_get_setting('button_radius') !== NULL) {
    $css_vars['.btn']['--bs-btn-border-radius'] = theme_get_setting('button_radius') . 'px';
  }

  $buttons = [
    'primary' => '.btn-primary, .button--small, #backtotop, details summary[role="button"]',
    'secondary' => '.btn-secondary',
  ];

  foreach($buttons as $button => $selector) {
    foreach(['text', 'bg', 'bd'] as $type) {
      $field = "{$button}_button_{$type}_color";
      $hover_field = "{$button}_button_hover_{$type}_color";
      $active_field = "{$button}_button_active_{$type}_color";
      if (!empty(theme_get_setting($field))) {
        $color = theme_get_setting($field);
        if ($type === 'text') {
          $css_vars[$selector]['--bs-btn-color'] = $color;
        }
        if ($type === 'bg') {
          $css_vars[$selector]['--bs-btn-bg'] = $color;
          if ($button === 'primary') {
            $css_vars['.form-checkbox']=
            [
              '--bs-form-check-border-color' => $color,
              '--bs-form-check-checked-bg' => $color,
              '--bs-form-check-checked-border-color' => $color
            ];
          }
        }
        if ($type === 'bd') {
          $css_vars[$selector]['--bs-btn-border-color'] = $color;
        }
      }
      if (!empty(theme_get_setting($hover_field))) {
        $color = theme_get_setting($hover_field);
        if ($type === 'text') {
          $css_vars[$selector]['--bs-btn-hover-color'] = $color;
          if (empty(theme_get_setting($active_field))) {
            $css_vars[$selector]['--bs-btn-active-color'] = $color;
          }
        }
        if ($type === 'bg') {
          $css_vars[$selector]['--bs-btn-hover-bg'] = $color;
          if (empty(theme_get_setting($active_field))) {
            $css_vars[$selector]['--bs-btn-active-bg'] = $color;
          }
        }
        if ($type === 'bd') {
          $css_vars[$selector]['--bs-btn-hover-border-color'] = $color;
          if (empty(theme_get_setting($active_field))) {
            $css_vars[$selector]['--bs-btn-active-border-color'] = $color;
          }
        }
      }
    }
  }

  $module_handler = \Drupal::service('module_handler');
  if ($module_handler->moduleExists('back_to_top')) {
      $config = \Drupal::config('back_to_top.settings');
      $settings = $config->get();

      if (!empty($settings['back_to_top_bg_color'])) {
        $css_vars['body #backtotop']['--bs-backtotop-bg'] = $settings['back_to_top_bg_color'];
        $css_vars['body #backtotop']['--bs-backtotop-border-color'] = $settings['back_to_top_bg_color'];
      }
      if (!empty($settings['back_to_top_border_color'])) {
        $css_vars['body #backtotop']['--bs-backtotop-active-border-color'] = $settings['back_to_top_border_color'];
      }
      if (!empty($settings['back_to_top_hover_color'])) {
        $css_vars['body #backtotop']['--bs-backtotop-hover-bg'] = $settings['back_to_top_hover_color'];
        $css_vars['body #backtotop']['--bs-backtotop-hover-border-color'] = $settings['back_to_top_hover_color'];
        $css_vars['body #backtotop']['--bs-backtotop-active-bg'] = $settings['back_to_top_hover_color'];
      }
      if (!empty($settings['back_to_top_text_color'])) {
        $css_vars['body #backtotop']['--bs-backtotop-color'] = $settings['back_to_top_text_color'];
        $css_vars['body #backtotop']['--bs-backtotop-hover-color'] = $settings['back_to_top_text_color'];
        $css_vars['body #backtotop']['--bs-backtotop-active-color'] = $settings['back_to_top_text_color'];
      }

  }

  if (empty($css_vars)) {
    return;
  }

  $theme_name = \Drupal::config('system.theme')->get('default');

  // Add CSS color variables.
  $page['#attached']['html_head'][] = [
    [
      '#tag' => 'style',
      '#attributes' => [
        'type' => 'text/css',
      ],
      '#value' => kamihaya_digitalagency_create_css_custom_vars($css_vars),
    ],
    $theme_name,
  ];
}

/**
 * Color palette as root css variables.
 *
 * @param array $colors
 *   Color definition.
 *
 * @return string
 *   CSS code.
 */
function kamihaya_digitalagency_create_css_vars(array $colors, array $bg_colors) : string {
  $css = [];
  foreach ($colors as $color => $selectors) {
    $selector = implode(', ', $selectors);
    $css[] = "$selector { color: $color !important; }";
  }
  foreach ($bg_colors as $color => $selectors) {
    $selector = implode(', ', $selectors);
    $css[] = "$selector { background-color: $color !important; }";
  }
  return implode(PHP_EOL, $css);
}

/**
 * Create custom css variables.
 *
 * @param array $vars
 *   Color vars definition.
 *
 * @return string
 *   CSS code.
*/
function kamihaya_digitalagency_create_css_custom_vars(array $css_vars) : string {
  $css = [];
  foreach ($css_vars as $selector => $values) {
    $vars = [];
    foreach ($values as $key => $value) {
      $vars[] = "$key: $value !important;";
      if (strpos($value, '#') === FALSE || strlen($value) !== 7 || !is_numeric(hexdec(substr($value, 1)))) {
        continue;
      }

      $rgp = _kamihaya_digitalagency_get_rgb_color(hexdec(substr($value, 1)));
      $vars[] = "$key-rgb: $rgp !important;";
    }
    if (empty($vars)) {
      continue;
    }
    $value = implode(PHP_EOL, $vars);
    $css[] = "$selector { $value }";
  }
  return implode(PHP_EOL, $css);
}

/**
 * Helper function to get RGB color from hex.
 *
 * @param string $color
 *   Hex color.
 *
 * @return string
 *   RGB color.
 */
function _kamihaya_digitalagency_get_rgb_color($color) {
  $red = (($color & 0xFF0000) >> 16);
  $green = (($color & 0x00FF00) >> 8);
  $blue = (($color & 0x0000FF));
  return "$red, $green, $blue";
}

/**
 * Implements hook_theme_suggestions_html_alter().
 */
function kamihaya_digitalagency_theme_suggestions_html_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
	$suggestions[] = 'html__' . $node->bundle();
  }
}

/**
 * Implements hook_preprocess_blazy().
 */
function kamihaya_digitalagency_preprocess_blazy(&$variables) {
  // Remove lightbox icon in blazy.
  if ( !empty($variables['icon']['lightbox'])) {
    unset($variables['icon']['lightbox']);
  }
}

/**
 * Implements hook_preprocess_views_view_grid().
 */
function kamihaya_digitalagency_preprocess_views_view_grid(&$variables) {
  $title = !empty($variables['title']) ? $variables['title'] : '';
  if (empty($title)) {
    return;
  }

  $dom = new DOMDocument();
  libxml_use_internal_errors(true);
  $dom->loadHTML($title);
  libxml_clear_errors();
  $header_tags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  foreach ($header_tags as $tag) {
    $tags = $dom->getElementsByTagName($tag);
    if ($tags->length > 0) {
      $variables['title_includes_header'] = TRUE;
      // If any header tag is found, set the flag and return.
      return;
    }
  }
}

/**
 * Implements hook_preprocess_addtoany_standard().
 *
 * This function is intentionally left empty as it is not used in this theme.
 */
function kamihaya_digitalagency_preprocess_addtoany_standard(&$variables) {
  if (!\Drupal::moduleHandler()->moduleExists('addtoany') || empty($variables['button_image'])) {
    return;
  }
  // Check if the custom universal button is set in the AddToAny settings.
  $config = \Drupal::config('addtoany.settings');
  if (empty($config) || empty($config->get('custom_universal_button'))) {
    return;
  }

  // If the custom universal button is set, generate the absolute URL for it.
  $button_path = $config->get('custom_universal_button');
  if (strpos($button_path, 'public://') === FALSE && strpos($button_path, 'private://') === FALSE) {
    return;
  }

  /* @var Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
  $file_url_generator = \Drupal::service('file_url_generator');
  // Generate the absolute URL for the button image.
  $variables['button_image'] = $file_url_generator->generateAbsoluteString($button_path);
}
