<?php

/**
 * @file
 * Functions to support theming modules in the Toc Master theme.
 */

use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;
use Drupal\image\Entity\ImageStyle;
use Drupal\Core\Render\Element;
use Drupal\media\Entity\Media;

/**
 * Implements hook_form_alter().
 *
 * Trainline suite booking - Desktop and exposed form.
 */
function toc_wmr_preprocess_tls_booking_form(&$vars) {
  // Simply override the button style for the form.
  $vars['el']['button_type'] = 'btn-default';
}

function toc_wmr_preprocess_tls_booking_widget(&$vars) {
  // Simply override the button style for the form.
  $vars['button_type'] = 'btn-default';
}

/**
 * Preprocess for toc_best_fares_block_content().
 *
 * @param array $vars
 *   Theme variables.
 */
function toc_wmr_preprocess_toc_best_fares_block_content(array &$vars) {
  $vars["status"] = 'outline-default';
}

/**
 * Preprocess for toc_wmr_preprocess_page_banner_random().
 */
function toc_wmr_preprocess_page_banner_random(array &$vars) {
  // Use the original image size for the bookend style banner overlay.
  $overlay_image_mid = $vars['element']['config']['overlay_image'] ?? 0;
  if ($overlay_image_mid) {
    $overlay_image = _tm_misc_get_styled_images_from_media($overlay_image_mid, '', 'field_media_image', 'media', 'image', 'poly-over crsl-img');
    if ($overlay_image) {
      $vars['element']['overlay'] = $overlay_image;
    }
  }
}

function toc_wmr_preprocess_journey_check_updates_items(array &$vars) {
  if (empty($vars['element']->getItems())) {
    $vars['top_message'] = [
      'text' => 'No problems reported',
      'icon_left' => 'far fa-info-circle',
    ];
  }
}

function toc_wmr_preprocess_journey_check_summary_status(array &$vars) {
  $vars['element']->setStatusText('Travel updates');
}

/**
 * Preprocess hook for link blocks - Advanced tickets with latest news.
 */
function toc_wmr_preprocess_link_block__latest_news_header(&$vars) {
  $template_vars = [
    'link_scope' => 'readmore',
    'block_class' => 'bl-vl cbelianr flex-fill mb-1',
    'header_tag' => 'h2',
    'readmore' => 'More news',
    'readmore_icon_right' => 'fas fa-chevron-right',
  ];
  _toc_master_preprocess_link_block($vars, $template_vars);
}

/**
 * Preprocess hook for link blocks - Advanced tickets with latest news.
 */
function toc_wmr_preprocess_link_block__adv_tickets_latest_news(&$vars) {
  $template_vars = [
    'link_scope' => 'block',
    'block_class' => 'bl-vk cbelianr flex-fill',
    'header_tag' => 'h3',
  ];
  _toc_master_preprocess_link_block($vars, $template_vars);
}

function toc_wmr_preprocess_card_block_alter(array &$suggestions, array $variables) {
  $config = $vars['element']['config'];
  $suggestions = [];

  if (!empty($config['entities'])) {
    $ids = array_column($config['entities'], 'target_id');
    // If one of the entity IDs is 21, use the 'bookearlycard' template suggestion.
    if (in_array(21, $ids)) {
      $suggestions[] = 'card_block__bookearlycard';
    }
    else {
      $suggestions[] = 'card_block__' . implode('_', $ids);
    }
  }

  if (!empty($config['machine_name'])) {
    $suggestions[] = 'card_block__' . $config['machine_name'];
  }

  return $suggestions;
}

function toc_wmr_preprocess_card_block(array &$variables) {
  if (!empty($variables['element']['entities'])) {
    foreach ($variables['element']['entities'] as &$entity) {
      if (!empty($entity['media']['id']) && $entity['media']['type'] == 'image') {
        // Load the media entity using its ID.
        $media = \Drupal::entityTypeManager()
          ->getStorage('media')
          ->load($entity['media']['id']);
        if ($media) {
          // Get the view builder for media and build a render array.
          $view_builder = \Drupal::entityTypeManager()->getViewBuilder('media');
          // Use an appropriate view mode (e.g., 'teaser') to render the media.
          $entity['media']['render'] = $view_builder->view($media, 'teaser');
        }
      }
    }
  }
}

/**
 * Implements hook_preprocess_HOOK() for the route_info_grid template.
 */
function toc_wmr_preprocess_route_information_block(&$variables) {
  // Ensure the 'items' array exists within the 'element'.
  if (isset($variables['element']['items']) && is_array($variables['element']['items'])) {

    // Loop through each item by reference (&) so we can modify it directly.
    foreach ($variables['element']['items'] as &$item) {

      // Check if this item has a 'media_id' and it's not empty.
      // NOTE: You mentioned the key was 'media_id' in the dump, so I am using that.
      // If the key is 'image', change '$item['media_id']' to '$item['image']' here.
      if (!empty($item['media_id'])) {

        // Load the Media entity using the ID.
        $media_entity = Media::load($item['media_id']);

        // If the media entity was loaded successfully...
        if ($media_entity) {
          // Get the view builder service to render the entity.
          $view_builder = \Drupal::entityTypeManager()->getViewBuilder('media');

          // Create a render array for the media entity using a specific view mode.
          // 'thumbnail' is a common default, but you can use any media view mode
          // you have configured (e.g., 'full', 'preview', etc.).
          $item['image'] = $view_builder->view($media_entity, 'thumbnail');
        }
      }
    }
  }
}
