<?php

/**
 * @file
 * Functions to support views.
 */

use Drupal\Component\Utility\Html;

/**
 * Preprocess hook preprocess_views_view__VIEW_ID.
 */
function toc_ga_preprocess_views_view__child_pages__block_1(&$vars) {
  $items = [];
  $vars['link_scope'] = 'block';
  $vars['header_tag'] = 'h2';
  $theme_setings = theme_get_setting('toc_master_theme_settings');

  if (!empty($vars["rows"][0])) {
    $view = $vars["rows"][0]['#view'];
    foreach ($view->result as $result) {
      $entity = $result->_entity;
      $title = _tm_misc_get_field_content($entity, 'title');
      $link = $entity->toUrl()->toString();
      $body_formatter = _tm_text_summary(200);
      $body = strip_tags(_tm_misc_get_field_content($entity, 'body', 'render', $body_formatter));
      $body = Html::decodeEntities($body);
      $media_id = _tm_misc_get_field_content($entity, 'field_page_er_main_image');
      if (!$media_id) {
        if (!empty($theme_setings['default_child_page_image']) && $theme_setings['default_child_page_image']) {
          $media_id = $theme_setings['default_child_page_image'];
        }
      }
      $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_media_image', 'media', 'url_alt');
      $items[] = [
        'title' => $title,
        'card_link' => $link,
        'body' => $body,
        'img_url' => $image['url'] ?? '',
        'img_alt' => $image['alt'] ?? $title,
      ];
    }
  }
  if (!empty($items)) {
    $vars['items'] = $items;
  }
  $vars['card_template'] = "@molecules/tm-cards/news-card/news-card.twig";
  $vars['batch'] = 2;
}

/**
 * Preprocess for Stations list block.
 */
function toc_ga_preprocess_views_view__stations__block_1(&$vars) {
  $pid = Html::getUniqueId('st-atoz');
  $items = [];
  $vars['ac_vars'] = FALSE;
  if (!empty($vars["rows"])) {
    foreach ($vars["rows"] as $row) {
      $title = strip_tags($row['#title']);
      $aiid = Html::getUniqueId('st-atoz-' . $title);
      $items[] = [
        "pid" => $pid,
        "aiid" => $aiid,
        "label" => $title,
        "content" => $row,
      ];
    }
  }
  if (!empty($items)) {
    $vars['ac_vars'] = [
      'pid' => $pid,
      'items' => $items,
      'wrapper_class' => 'mt-3',
    ];
  }
}

function toc_ga_preprocess_views_view__service_announcements_frontend_views__service_announcements_above_banner(&$vars) {
  if (!empty($vars['items'])) {
    foreach ($vars['items'] as &$item) {
      $item['extra'] = '';
    }
  }
}
