<?php

use Drupal\Core\Template\Attribute;
use Drupal\the_list_events\Entity\TheListEventECKEntity;
use Drupal\views\ViewExecutable;

/**
 * Preprocess hook views_view__engineering_works__block_1.
 */
function toc_master_preprocess_views_view__engineering_works__block_1(&$vars) {
  $items = [];
  $vars['link_scope'] = 'block';
  $vars['block_class'] = 'bl-vb cbelianr';
  $vars['header_tag'] = 'h3';
  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();
      $items[] = [
        'title' => $title,
        'block_link' => $link,
        'icon_right' => 'fas fa-chevron-right',
      ];
    }
  }
  if (!empty($items)) {
    $vars['items'] = $items;
  }
}

/**
 * Preprocess hook views_view__offers_postcode_regions_frontend_views__block.
 *
 * @see toc_master_preprocess_views_view__offers_frontend_views__block_1
 */
function toc_sr_preprocess_views_view__offers_postcode_regions_frontend_views__block(&$vars) {
  // Package up the offers header from the views config.
  $vars['offers_header'] = [
    "header_text" => '',
    "header_nodes" => [],
  ];

  foreach ($vars["header"] as $key => $handler) {
    if (!empty($handler['#node'])) {
      $entity = $handler['#node'];
      $title = _tm_misc_get_field_content($entity, 'title');
      $type = _tm_misc_get_field_content($entity, 'type');
      $media_id = _tm_misc_get_field_content($entity, 'field_of_main_image');
      $link = $entity->toUrl()->toString();
      $image = '';
      if ($type == 'dog_offer') {
        $image = _tm_misc_get_styled_images_from_media($media_id, 'thumbnail', 'field_dog_media_image', 'media', 'url_alt');
      }
      if ($type == 'offer') {
        $image = _tm_misc_get_styled_images_from_media($media_id, 'thumbnail', 'field_of_media_image', 'media', 'url_alt');
      }
      $pinned = [
        'img_url' => $image['url'] ?? '',
        'img_alt' => $image['alt'] ?? '',
        'title' => $title,
        'link' => $link,
      ];
      $vars["offers_header"]["header_nodes"][] = $pinned;
    }
    elseif (!empty($handler['#type']) && $handler['#type'] == 'processed_text') {
      // We will not try and process this text, twig will take care of this.
      $vars["offers_header"]["header_text"] = $handler;
    }
  }

  // Get the itinerary settings for the add button.
  $itinerary_config = \Drupal::config('itinerary_basket.settings');
  $add_button = $itinerary_config->get('add_itinerary_button');

  // Package up the rows for the cards.
  $items = [];
  if (!empty($vars["rows"][0])) {
    $view = $vars["rows"][0]['#view'];
    foreach ($view->result as $result) {
      $entity = $result->_entity;
      $id = $entity->Id();
      $title = _tm_misc_get_field_content($entity, 'title');
      $link = $entity->toUrl()->toString();
      $text_format = _tm_text_format(['br', 'p']);
      $content = _tm_misc_get_field_content($entity, 'field_of_short_description', 'render', $text_format);
      if (empty($content)) {
        $content = _tm_misc_get_field_content($entity, 'field_of_description', 'render', $text_format);
        if (empty($description)) {
          $content = _tm_misc_get_field_content($entity, 'field_of_long_description', 'render', $text_format);
        }
      }
      $price = _tm_misc_get_field_content($entity, 'field_of_price');
      $media_id = _tm_misc_get_field_content($entity, 'field_of_main_image');
      if ($entity->getType() == 'dog_offer') {
        $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_dog_media_image', 'media', 'url_alt');
      }
      if ($entity->getType() == 'offer') {
        $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_of_media_image', 'media', 'url_alt');
      }
      // Tags.
      $genre_terms = _tm_misc_get_field_content($entity, 'field_of_category', 'reference', [], -1);
      $tags = [];
      if ($genre_terms) {
        foreach ($genre_terms as $genre_term) {
          $tid = _tm_misc_get_field_content($genre_term, 'tid');
          $name = _tm_misc_get_field_content($genre_term, 'name');
          $form_values = [
            [
              "t" => "[data-drupal-selector='edit-ocat-".  $tid . "']",
              "s" => "checked",
              "v" => 'true',
              "e" => "focus",
            ],
          ];
          $attr = [
            'id' => 'tag-' . $id . '-' . $tid,
            'data-alt-toggle' => 'formsetsubmit',
            'data-alt-target-data' => htmlspecialchars(json_encode($form_values)),
            'data-alt-target-submit' => '.offers-ajax-submit-btn',
          ];
          $tags[] = [
            'name' => $name,
            'attr' => new Attribute($attr),
          ];
        }
      }
      // Location.
      $location = '';
      $closest_crs = _tm_misc_get_field_content($entity, 'field_of_closest_station_crs');
      if (!empty($closest_crs)) {
        $station_entity = \Drupal\nre_stations_entity_type\Entity\NreStationEckEntity::loadByCrs($closest_crs);
        $location = $station_entity ? $station_entity->getTitle() : '';
      }

      $badge_graphic_image = FALSE;
      $badge_type = 'text';
      $badge_text_top = _tm_misc_get_field_content($entity, 'field_of_badge_text');
      if (!$badge_text_top) {
        // Offer type fallback.
        $voucher_term = _tm_misc_get_field_content($entity, 'field_of_voucher_type', 'reference');
        if ($voucher_term) {
          $badge_type = _tm_misc_get_field_content($voucher_term, 'field_lt_badge_type');
          if ($badge_type === 'graphic') {
            $badge_graphic = _tm_misc_get_field_content($voucher_term, 'field_er_badge_graphic', 'reference');
            if ($badge_graphic) {
              $badge_graphic_image = _tm_misc_get_styled_images_from_media($badge_graphic->id(), 'toc_master_original', 'field_media_image', 'media', 'url_alt');
              $badge_text_top = FALSE;
            }
          }
          else {
            $badge_text_top = _tm_misc_get_field_content($voucher_term, 'field_tp_badge_text');
            if (empty($badge_text_top)) {
              $badge_text_top = _tm_misc_get_field_content($voucher_term, 'name');
            }
          }
        }
      }

      // If still there's no badge text use a default.
      if ($badge_type == 'text' && !$badge_text_top) {
        $badge_text_top = '2FOR1 Admission';
      }

      // If the tag is a discount e.g '20% off' then don't show the price.
      // This is misleading as price and percent are ambiguous together.
      if (strpos($badge_text_top, '%') !== false) {
        $price = FALSE;
      }

      // Let's swap around the top and bottom so that the larger one (bottom)
      // is used when the price is there or not.
      if ($price) {
        $badge_text_bottom = _tm_misc_format_price($price);
      }
      else {
        $badge_text_bottom = $badge_text_top;
        $badge_text_top = '';
      }

      // Badge color, coming from Offer Type. Note, image comes from offer voucher type.
      $badge_color = FALSE;
      $offer_term = _tm_misc_get_field_content($entity, 'field_of_type', 'reference');
      if ($offer_term) {
        $badge_color = _tm_misc_get_field_content($offer_term, 'field_badge_color');
      }

      $items[] = [
        'img_url' => $image['url'] ?? '',
        'img_alt' => $image['alt'] ?? '',
        'title' => $title,
        'content' => $content,
        'badge_graphic_image' => $badge_graphic_image,
        'badge_text_top' => $badge_text_top,
        'badge_text_bottom' => $badge_text_bottom,
        'badge_color' => $badge_color,
        // 'badge' => $badge_graphic_image || $badge_text_top || $price, # Deprecated, need to check GA.
        'card_link' => $link,
        'location' => $location,
        'tags' => $tags,
        'show_itinerary' => $add_button,
        'oid' => $id,
      ];
    }
  }
  if (!empty($items)) {
    $vars['items'] = $items;
  }
}

/**
 * Preprocess hook views_view__offers_postcode_regions_prefiltered__block.
 *
 * @see toc_sr_preprocess_views_view__offers_postcode_regions_frontend_views__block
 */
function toc_sr_preprocess_views_view__offers_postcode_regions_prefiltered__block(&$vars) {
  toc_sr_preprocess_views_view__offers_postcode_regions_frontend_views__block($vars);
}

/**
 * Preprocess hook views_view__the_list__block.
 *
 * @see toc_sr_preprocess_views_view__offers_postcode_regions_frontend_views__block
 */
function toc_sr_preprocess_views_view__the_list__block(&$vars) {

  // Package up the rows for the cards.
  $items = [];
  if (!empty($vars["rows"][0])) {
    $view = $vars["rows"][0]['#view'];
    $theme_setings = theme_get_setting('toc_master_theme_settings');
    /** @var \Drupal\views\ResultRow $result */
    foreach ($view->result as $result) {
      $entity = $result->_entity;
      $id = $entity->id();
      $title = _tm_misc_get_field_content($entity, 'title');
      $link = $entity->toUrl()->toString();
      $text_format = _tm_text_format(['br', 'p']);
      $content = _tm_misc_get_field_content($entity, 'field_tl_tp_description', 'render', $text_format);
      $media_id = _tm_misc_get_field_content($entity, 'field_tl_er_image');
      if ($entity->getType() == 'list_event') {
        $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_tl_media_image', 'media', 'url_alt');
        if (!$image && !empty($theme_setings['default_event_image']) && $theme_setings['default_event_image']) {
          $media_id = $theme_setings['default_event_image'];
          $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_media_image', 'media', 'url_alt');
        }
      }
      // Tags.
      $genre_terms = _tm_misc_get_field_content($entity, 'field_tl_er_categories', 'reference', [], -1);
      $tags = [];
      if ($genre_terms) {
        foreach ($genre_terms as $genre_term) {
          $tid = _tm_misc_get_field_content($genre_term, 'tid');
          $name = _tm_misc_get_field_content($genre_term, 'name');
          $form_values = [
            [
              "t" => "[data-drupal-selector='edit-field-tl-er-categories-target-id-".  $tid . "']",
              "s" => "checked",
              "v" => 'true',
              "e" => "focus",
            ],
          ];
          $attr = [
            'id' => 'tag-' . $id . '-' . $tid,
            'data-alt-toggle' => 'formsetsubmit',
            'data-alt-target-data' => htmlspecialchars(json_encode($form_values)),
            'data-alt-target-submit' => '.events-ajax-submit-btn',
          ];
          $tags[] = [
            'name' => $name,
            'attr' => new Attribute($attr),
          ];
        }
      }

      $items[] = [
        'img_url' => $image['url'] ?? '',
        'img_alt' => $image['alt'] ?? '',
        'title' => $title,
        'content' => $content,
        'card_link' => $link,
        'tags' => $tags,
        'event_id' => $id,
        'location' => '',
      ];
    }
  }
  if (!empty($items)) {
    $vars['items'] = $items;
  }
}

/**
 * Preprocess hook views_view__the_list__block.
 *
 * @see toc_sr_preprocess_views_view__offers_postcode_regions_frontend_views__block
 */
function toc_sr_preprocess_views_view__things_to_do__block(&$vars) {

  // Package up the rows for the cards.
  $items = [];
  if (!empty($vars["rows"][0])) {
    $view = $vars["rows"][0]['#view'];
    $theme_setings = theme_get_setting('toc_master_theme_settings');
    /** @var \Drupal\views\ResultRow $result */
    foreach ($view->result as $result) {
      $entity = $result->_entity;
      $id = $entity->id();
      $title = _tm_misc_get_field_content($entity, 'field_tl_places_tp_name');
      $link = $entity->toUrl()->toString();
      $text_format = _tm_text_format(['br', 'p']);
      $content = _tm_misc_get_field_content($entity, 'field_tl_places_tp_description', 'render', $text_format);
      $media_id = _tm_misc_get_field_content($entity, 'field_tl_places_er_image');
      $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_tl_media_image', 'media', 'url_alt');
      if (!$image && !empty($theme_setings['default_event_image']) && $theme_setings['default_event_image']) {
        $media_id = $theme_setings['default_event_image'];
        $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_media_image', 'media', 'url_alt');
      }

      // Tags.
      $genre_terms = _tm_misc_get_field_content($entity, 'field_tl_places_er_things_to_do', 'reference', [], -1);
      $tags = [];
      if ($genre_terms) {
        foreach ($genre_terms as $genre_term) {
          $tid = _tm_misc_get_field_content($genre_term, 'tid');
          $name = _tm_misc_get_field_content($genre_term, 'name');
          $form_values = [
            [
              "t" => "[data-drupal-selector='edit-field-tl-er-categories-target-id-".  $tid . "']",
              "s" => "checked",
              "v" => 'true',
              "e" => "focus",
            ],
          ];
          $attr = [
            'id' => 'tag-' . $id . '-' . $tid,
            'data-alt-toggle' => 'formsetsubmit',
            'data-alt-target-data' => htmlspecialchars(json_encode($form_values)),
            'data-alt-target-submit' => '.events-ajax-submit-btn',
          ];
          $tags[] = [
            'name' => $name,
            'attr' => new Attribute($attr),
          ];
        }
      }

      $items[] = [
        'img_url' => $image['url'] ?? '',
        'img_alt' => $image['alt'] ?? '',
        'title' => $title,
        'content' => $content,
        'card_link' => $link,
        'tags' => $tags,
        'event_id' => $id,
        'location' => '',
      ];
    }
  }
  if (!empty($items)) {
    $vars['items'] = $items;
  }
}

/**
 * Implements hook_views_post_render()
 *
 * @param \Drupal\views\ViewExecutable $view
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 *
 * @see _toc_master_views_post_render__offers_frontend_views__block_1
 */
function _toc_sr_views_post_render__offers_postcode_regions_frontend_views__block(ViewExecutable $view) {
  $filterables = [
    [
      'field_name' => 'field_of_er_postcode_region',
      'filter_name' => $view->filter['field_of_er_postcode_region_target_id']->options['expose']['identifier'],
    ],
    [
      'field_name' => 'field_of_type',
      'filter_name' => $view->filter['field_of_type_target_id']->options['expose']['identifier'],
    ],
    [
      'field_name' => 'field_of_category',
      'filter_name' => $view->filter['field_of_category_target_id']->options['expose']['identifier'],
    ],
  ];
  $node_type = ['dog_offer', 'offer'];
  $target_ids = [
    'field_of_er_postcode_region' => _tm_views_get_target_ids_for_view_filter_field('field_of_er_postcode_region', $node_type),
    'field_of_type' => _tm_views_get_target_ids_for_view_filter_field('field_of_type', $node_type),
    'field_of_category' => _tm_views_get_target_ids_for_view_filter_field('field_of_category', $node_type),
  ];
  $view = _tm_views_limit_filter_options_with_existing_terms($filterables, $target_ids, $view);
}

/**
 * Implements hook_views_post_render()
 *
 * @param \Drupal\views\ViewExecutable $view
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 *
 * @see _toc_master_views_post_render__offers_frontend_views__block_1
 */
function _toc_sr_views_post_render__the_list__block(ViewExecutable $view) {
  $filterables = [
    [
      'field_name' => 'field_tl_er_postcode_region',
      'filter_name' => $view->filter['field_tl_er_postcode_region_target_id']->options['expose']['identifier'],
      // This field is not in the The List Event entity but a referenced paragraph.
      'entity' => 'field_tl_sched_er_place',
    ],
    [
      'field_name' => 'field_tl_er_categories',
      'filter_name' => $view->filter['field_tl_er_categories_target_id']->options['expose']['identifier'],
    ],
  ];
  $target_ids = [
    'field_tl_er_postcode_region' => [],
    'field_tl_er_categories' => _tm_views_get_target_ids_for_view_filter_field('field_tl_er_categories', 'list_event'),
  ];
  $entityTypeManager = \Drupal::service('entity_type.manager');
  $connection = \Drupal::database();
  $query = $connection->select('the_list_events__field_tl_er_postcode_region', 'region')
    ->fields('region', ['field_tl_er_postcode_region_target_id']);
  $query->innerJoin('paragraph__field_tl_sched_er_place', 'place', 'place.field_tl_sched_er_place_target_id = region.entity_id AND place.deleted = 0');
  $query->innerJoin('paragraphs_item_field_data', 'place_data', 'place_data.id = place.entity_id');
  $query->innerJoin('node__field_tl_par_schedules', 'schedule', 'schedule.field_tl_par_schedules_target_revision_id = place_data.revision_id');
  $query->innerJoin('node_field_data', 'node', 'node.nid = schedule.entity_id AND schedule.deleted = 0');
  $tids = $query
    ->condition('region.deleted', 0)
    ->condition('node.status', 1)
    ->condition('node.type', 'list_event')
    ->distinct()
    ->execute()
    ->fetchCol();

  foreach ($entityTypeManager->getStorage('taxonomy_term')->loadMultiple($tids) as $term) {
    $target_ids['field_tl_er_postcode_region'][$term->id()] = _tm_misc_get_field_content($term, 'name');
  }
  $view = _tm_views_limit_filter_options_with_existing_terms($filterables, $target_ids, $view);
}

/**
 * Implements hook_views_post_render()
 *
 * @param \Drupal\views\ViewExecutable $view
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 *
 * @see _toc_master_views_post_render__offers_frontend_views__block_1
 */
function _toc_sr_views_post_render__things_to_do__block(ViewExecutable $view) {
  $filterables = [
    [
      'field_name' => 'field_tl_places_er_things_to_do',
      'filter_name' => $view->filter['field_tl_places_er_things_to_do_target_id']->options['expose']['identifier'],
    ],
  ];
  $target_ids = [
    'field_tl_places_er_things_to_do' => _tm_views_get_target_ids_for_view_filter_field('field_tl_places_er_things_to_do', 'places', 'the_list_events'),
  ];

  $view = _tm_views_limit_filter_options_with_existing_terms($filterables, $target_ids, $view);
}

/**
 * Preprocess hook preprocess_views_view__VIEW_ID.
 */
function toc_sr_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));
      $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/child-card/child-card.twig";
  $vars['batch'] = 2;
}

/**
 * Preprocess for Calendar - Date Range View.
 */
function toc_sr_preprocess_views_view__service_alterations_date_range__block(&$vars) {
  // Giving the class "btn-lg" makes the icon float left. Not fun!
  $vars['btn_next_class'] = 'btn btn-primary';
  $vars['btn_prev_class'] = 'btn btn-primary';

  // Set the Previous and Next button text.
  /** @var \Drupal\views\ViewExecutable $view */
  $view = $vars['view'];
  $calendar_args = $view->args[0];
  /** @var \Drupal\Core\Datetime\DrupalDateTime $previous */
  $previous = clone $calendar_args['calendar_start'];
  $previous->modify('-1 month');
  // Use calendar start because if you use calendar end it messes up when crossing
  // into months with less than 31 days. All we care about here is the Month and Year.
  $next = clone $calendar_args['calendar_start'];
  $next->modify('+1 month');
  $vars['prev_text'] = $previous->format('F Y');
  $vars['next_text'] = $next->format('F Y');
}

/**
 * Preprocess hook views_view__news_blocks__block_1.
 */
function toc_sr_preprocess_views_view__news_blocks__block_1(&$vars) {
  _toc_sr_preprocess_views_view__news_blocks($vars);
}

/**
 * Preprocess hook views_view__news_blocks__block_1.
 */
function toc_sr_preprocess_views_view__news_blocks__block_3(&$vars) {
  _toc_sr_preprocess_views_view__news_blocks($vars);
}

function _toc_sr_preprocess_views_view__news_blocks(&$vars) {
  $items = [];
  $top_item = NULL;
  $vars['link_scope'] = 'block';
  $vars['block_class'] = 'bl-ve cbelianr';
  $vars['header_tag'] = 'h2';
  $text_format = _tm_text_plain(1000);
  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');
      $cats = _tm_misc_get_field_content($entity, 'field_blog_category');
      $media_id = _tm_misc_get_field_content($entity, 'field_media_image');
      $image = _tm_misc_get_styled_images_from_media($media_id, 'card_image', 'field_media_image', 'media', 'url_alt');
      $link = $entity->toUrl()->toString();
      $tags = _tm_misc_format_tags($cats);
      $subtitle = _tm_misc_format_date_overridden($entity, 'toc_medium_date_without_time');
      if ($result->index === 0){
        $body = _tm_misc_get_field_content($entity, 'body', 'render', $text_format);
        $body = _tm_check_markup($body);
        $body = substr($body, 0, 100);

        $top_item = [
          'image_src' => $image['url'] ?? '',
          'image_alt' => $image['alt'] ?? '',
          'title' => $title,
          'block_link' => $link,
          'icon_right' => 'fas fa-chevron-right',
          'subtitle' => $subtitle,
          'body' => $body,
          'tags' => $tags,
        ];
      }
      else {
        $items[] = [
          'image_src' => $image['url'] ?? '',
          'image_alt' => $image['alt'] ?? '',
          'title' => $title,
          'block_link' => $link,
          'icon_right' => 'fas fa-chevron-right',
          'subtitle' => $subtitle,
          'tags' => $tags,
        ];
      }
    }
  }
  if ($top_item || !empty($items)) {
    $vars['top_item'] = $top_item;
    $vars['items'] = $items;
  }
}

/**
 * Preprocess for Calendar - Date Range View.
 */
function toc_sr_preprocess_views_view__service_announcements_frontend_views__service_announcements_above_banner(&$vars) {
  $vars['title'] = 'Important information';
  if (!empty($vars['items'])) {
    $count = count($vars['items']);
    $vars['title'] = "$count Service Disruption";
    if ($count > 1) {
      $vars['title'] .= 's';
    }
  }
}

/**
 * Preprocess for announcements above banner.
 */
function toc_sr_preprocess_views_view__service_announcements_frontend_views__service_announcements_banner(&$vars) {
  $vars['title'] = 'Important information';
  if (!empty($vars['items'])) {
    $count = count($vars['items']);
    $vars['title'] = "$count Service Disruption";
    if ($count > 1) {
      $vars['title'] .= 's';
    }
  }
}
