<?php

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

use Drupal\nre_stations_entity_type\Entity\NreStationEckEntity;
use Drupal\nre_train_operating_companies\Entity\NreTrainOperatingCompanyEckEntity;

/**
 * Preprocess hook for eck_entity__link_block__$ID().
 */
function toc_wmr_preprocess_eck_entity__link_block__signup_link(&$vars) {
  $vars['image_background'] = TRUE;
  $vars['block_class'] = 'wmt-lb-signup bl-vh cbelianr bg-grey bl-lilfr py-lg-2 px-lg-3 mb-4 wmt-lb-signup ';
  $vars['title_display'] = 'noflex';
}

/**
 * Preprocess hook for eck_entity__nres_ee_nre_station().
 */
function toc_wmr_preprocess_eck_entity__nres_ee_nre_station(&$vars) {
  $entity = $vars['eck_entity'];
  $station_crs = _tm_misc_get_field_content($entity, 'field_nres_eeb_tp_crs');
  $new_live_trains_available = _twmr_misc_render_contextual_ldb_block();
  if ($new_live_trains_available) {
    $ldb_block_render = $new_live_trains_available;
  }
  else {
    $ldb_block_render = _tm_misc_render_ldb_block($station_crs, TRUE);
  }
  $vars['ldb_exposed_title'] = 'Live arrivals and departures';
  $vars['ldb_exposed_content'] = $ldb_block_render;
  $vars['ldb_use_exposed'] = TRUE;
  // A header not used in GA.
  $vars['station_info_header'] = 'Station information';
  // Use the extended header version.
  $vars['header_use_extended'] = TRUE;
  // Data for extended header.
  $office = _tm_misc_get_field_content($entity, 'field_nres_eeb_par_ticket_office', 'reference');
  if ($office) {
    $times = _tm_misc_get_field_content($office, 'field_nres_eeb_par_open', 'reference');
    if ($times) {
      $data = _tm_misc_get_field_content($times, 'field_nres_eeb_par_day_and_time', 'render', [], -1);
      if ($data) {
        $vars['ticket_office'] = $data;
      }
      $annotation = _tm_misc_get_field_content($times, 'field_nres_eeb_sta_annotation', 'render');
      if ($annotation) {
        $vars['ticket_office'][] = $annotation;
      }
    }
  }
  if (!isset($vars['ticket_office'])) {
    $vars['ticket_office'] = [[
      '#type' => 'markup',
      '#markup' => '<i class="fas fa-times"></i>',
    ]];
  }

  $vars['post'] = $vars['elements']['post'] ?? '';
  $checklist = [
    'Ticket office' => 'field_nres_eeb_par_ticket_office',
    'Step-free access' => 'field_nres_eeb_sta_step_free',
    'Prepurchase collection' => 'field_nres_eeb_par_collection',
    'Car park' => 'field_nres_eeb_par_car_parks',
    'Ticket machine' => 'field_nres_eeb_lt_ticket_mach',
    'Toilets' => 'field_nres_eeb_par_toilets',
    'Taxi-rank' => 'field_nres_eeb_sta_taxi_rank'
  ];

  $station_features = nre_stations_entity_type_get_station_features($station_crs);
  if ($station_features) {
    foreach ($station_features['features'] as &$feature) {
      if ($feature == 'Car park' && isset($vars['elements']['car_parks_entities'])) {
        $feature = $vars['elements']['car_parks_entities'];
      }
    }
    $vars['checklist'] = $station_features['features'];
  }

  // Amend station accordion.
  $vars['info_accordion'] = _toc_wmr_amend_station_info_accordion_alter($vars, $entity, $station_crs);
}

/**
 * Preprocess hook for node__attraction().
 */
function toc_wmr_preprocess_node__attraction(&$vars) {
  // Amend station accordion.
  $station_entity = NreStationEckEntity::loadByCrs($vars['first_station_crs']);
  if ($station_entity) {
    $vars['info_accordion'] = _toc_wmr_amend_station_info_accordion_alter($vars, $station_entity, $vars['first_station_crs']);
    $new_live_trains_available = _twmr_misc_render_contextual_ldb_block();
    if ($new_live_trains_available) {
      $vars['ldb_board'] = $new_live_trains_available;
    }
  }
  $vars['swap_sidebar_form'] = TRUE;
}

function _toc_wmr_amend_station_info_accordion_alter($vars, $entity, $station_crs) {
  $car_park_accordion_exists = FALSE;
  // Just a label rewrite.
  if (!empty($vars['info_accordion']['items'])) {
    foreach ($vars['info_accordion']['items'] as $k => $v) {
      if ($v['aiid'] == 'car_park') {
        $label = '<i class="fas fa-car"></i> Car parking <span class="text-danger">LIVE<i class="fal fa-wifi rot-45 fs-lg"></i></span>';
        $vars['info_accordion']['items'][$k]['label'] = $label;
        $car_park_accordion_exists = TRUE;
        break;
      }
    }
  }
  foreach ($vars['info_accordion']['items'] as $collapsible_key => &$collapsible) {
    switch ($collapsible['aiid']) {
      case 'general_info':
        $toc_code = _tm_misc_get_field_content($entity, 'field_nres_eeb_tp_operator', 'string');
        if (!$toc_code) {
          break;
        }
        $toc_entity = NreTrainOperatingCompanyEckEntity::loadByAtoc($toc_code);
        // If we have the TOC entity use its name, otherwise use the code.
        if ($toc_entity) {
          $collapsible['content']['#rows'] = _tm_append_table_row($collapsible['content']['#rows'], 'title', TRUE, 'Station operator', $toc_entity, 'field');
        } else {
          $collapsible['content']['#rows'] = _tm_append_table_row($collapsible['content']['#rows'], 'field_nres_eeb_tp_operator', TRUE, 'Station operator', $entity, 'field');
        }
        break;
      case 'fares':
        $collapsible['label'] = '<i class="fas fa-ticket-alt"></i> Ticket buying and collection';
        _toc_wmr_remove_entry_from_station_accordion_table($collapsible, 'Oyster cards issued here');
        _toc_wmr_remove_entry_from_station_accordion_table($collapsible, 'Use Oyster cards here');
        $collapsible['content']['#rows'] = _tm_append_table_row($collapsible['content']['#rows'], 'field_nres_eeb_par_smart_topup', TRUE, 'Top up Smartcards here', $entity, 'field');
        break;
      case 'interchange':
        $cycle_storage = [];
        $car_park_rows = [];
        if (!empty($collapsible['content']['#rows'])) {
          foreach ($collapsible['content']['#rows'] as $key => $row) {
            if (strpos($row[0]['data'], 'Cycle') !== FALSE) {
              $cycle_storage[] = $row;
              unset($collapsible['content']['#rows'][$key]);
            }
            if (strpos($row[0]['data'], 'Car park') !== FALSE) {
              $car_park_rows[] = $row;
              unset($collapsible['content']['#rows'][$key]);
            }
            if (strpos($row[0]['data'], 'Onward') !== FALSE) {
              $bus_connections[] = $row;
              unset($collapsible['content']['#rows'][$key]);
            }
          }
        }
        // If this value is not set, it means there's no live car park data and
        // no collapsible, so we create one.
        if (!$car_park_accordion_exists) {
          if (!empty($car_park_rows)) {
            $car_park_content = [
              '#type' => 'table',
              '#header' => [],
              '#rows' => $car_park_rows,
            ];
          } else {
            $car_park_content = [
              '#type' => 'markup',
              '#markup' => 'No car park information available.',
            ];
          }
          $vars['info_accordion']['items'][] = [
            'pid' => 'station_info_accordion',
            'aiid' => 'car_parks',
            'label' => '<i class="fas fa-car"></i> Car parking',
            'content' => $car_park_content,
          ];
        }

        if (!empty($bus_connections)) {
          $bus_content = [
            '#type' => 'table',
            '#header' => [],
            '#rows' => $bus_connections,
          ];
        } else {
          $bus_content = [
            '#type' => 'markup',
            '#markup' => 'No bus information available.',
          ];
        }
        $vars['info_accordion']['items'][] = [
          'pid' => 'station_info_accordion',
          'aiid' => 'bus_connections',
          'label' => '<i class="fas fa-bus"></i> Bus connections',
          'content' => $bus_content,
        ];

        $vars['info_accordion']['items'][] = [
          'pid' => 'station_info_accordion',
          'aiid' => 'cycle_storage',
          'label' => '<i class="fas fa-bicycle"></i> Cycle storage',
          'content' => [
            '#type' => 'table',
            '#header' => [],
            '#rows' => $cycle_storage,
          ],
        ];

        if (!empty($collapsible['content']['#rows'])) {
          $vars['info_accordion']['items'][] = [
            'pid' => 'station_info_accordion',
            'aiid' => 'other_transport',
            'label' => '<i class="fas fa-taxi"></i> Other transport options',
            'content' => [
              '#type' => 'table',
              '#header' => [],
              '#rows' => $collapsible['content']['#rows'],
            ],
          ];
        }

        unset($vars['info_accordion']['items'][$collapsible_key]);

        break;

      case 'car_park':
        $collapsible['content'] = [
          $collapsible['content'],
        ];
        $collapsible['content'][] = [
          '#type' => 'table',
          '#header' => [],
          '#rows' => $car_park_rows,
        ];
        break;
    }
  }

  return $vars['info_accordion'];
}

function _toc_wmr_remove_entry_from_station_accordion_table(&$accordion, $row_header) {
  foreach ($accordion['content']['#rows'] as $key => $row) {
    if ($row[0]['data'] == $row_header) {
      unset($accordion['content']['#rows'][$key]);
    }
  }
}

function toc_wmr_preprocess_node__destination(&$vars) {
  $vars['swap_sidebar_form'] = true;
  if (isset($vars['form'])) {
    unset($vars['form']);
  }

  $entity = $vars['node'];
  // FAQs, let's use Routes.
  $faqs = _tm_misc_destination_attraction_faqs($entity, 'field_dest_par_faqs', 'accordion');
  if (!empty($faqs)) {
    $vars['faqs'] = [
      'pid' => 'content_accordion',
      'wrapper_class' => 'acw-a mb-3',
      'items' => $faqs,
    ];
  }
  // Default area map, no marker required.
  $leaflet_map_format = _tm_leaflet_format(12, 0, 0, ['iconType' => 'html']);
  $map = _tm_misc_get_field_content($entity, 'field_dest_ge_location', 'render', $leaflet_map_format);
  $vars['map'] = $map;
  // Extra info.
  $text_format = _tm_text_format([], 0, 'input', 'full_html');
  $vars['extra'] = _tm_misc_get_field_content($entity, 'field_dest_stf_extra_content', 'view', $text_format);
  $vars['#attached']['library'][] = 'toc_wmr/content__destination';

  $vars['destinations_things_to_do']['view'] = [
    '#type' => 'view',
    '#name' => 'destinations_things_to_do',
    '#display_id' => 'block_1',
  ];
}

/**
 * Preprocess hook for node__dog_offer().
 */
function toc_wmr_preprocess_node__dog_offer(&$vars) {
  // DOG and Standard Offers vars.
  _toc_wmr_preprocessoffers($vars);
}

/**
 * Preprocess hook for node__dog_offer().
 */
function toc_wmr_preprocess_node__offer(&$vars) {
  // DOG and Standard Offers vars.
  _toc_wmr_preprocessoffers($vars);
}

/**
 * Common preprocess hook for DOG and Standard Offers.
 */
function _toc_wmr_preprocessoffers(&$vars) {
  // The entity.
  $entity = $vars['node'];
  $allowed = ['br', 'p', 'ul', 'ol', 'li', 'a', 'em', 'strong', 'h2'];
  $text_format = _tm_text_format($allowed, 0);
  $offer_description = _tm_misc_get_field_content($entity, 'field_of_description', 'render', $text_format);

  $vars['offer_description'] = $offer_description;
}
