<?php

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

use Drupal\Core\Entity\EntityInterface;
use Drupal\nre_stations_entity_type\Constants as NREStationEntityConstants;

/**
 * Preprocess hook for node__article().
 */
function toc_ga_preprocess_node__article(&$vars): void {
  // The entity.
  $entity = $vars['node'];
  $cats = _tm_misc_get_field_content($entity, 'field_blog_category');
  $tags = _tm_misc_format_tags($cats);
  $published_date = _tm_misc_format_date_overridden($entity, 'toc_long', 'created');
  $changed_date = _tm_misc_format_date_overridden($entity, 'toc_long', 'changed', []);
  $vars['pub_date'] = "Published on: " . $published_date;
  $vars['changed_date'] = "Last updated: " . $changed_date;
  $vars['tags'] = $tags;
}

/**
 * Preprocess hook for eck_entity__nres_ee_nre_station().
 */
function toc_ga_preprocess_eck_entity__nres_ee_nre_station(&$vars): void {
  $entity = $vars['eck_entity'];
  $station_crs = _tm_misc_get_field_content($entity, NREStationEntityConstants::FIELD_CRS);
  // 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' => 'None available',
      ],
    ];
  }

  $vars['post'] = $vars['elements']['post'] ?? '';

  $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'];
  }

  // Live Departure block.
  $station_crs = _tm_misc_get_field_content($entity, NREStationEntityConstants::FIELD_CRS);
  $ldb_block_render = _tm_misc_render_ldb_block($station_crs);

  $vars['ldb'] = [
    'pid' => 'station_live_departure_boards',
    'items' => [
      [
        'pid' => 'station_live_departure_boards',
        'aiid' => 'boards',
        'label' => '<h2 class="text-white mb-0"><i class="far fa-clock"></i> View live departures / arrivals</h2>',
        'content' => $ldb_block_render,
      ],
    ],
  ];

  // Amend station accordion.
  $vars['info_accordion'] = _toc_ga_amend_station_info_accordion_alter($vars, $entity);
  $vars['info_accordion_title'] = !empty($vars['name']) ? $vars['name'] . ' Train Station Information' : 'Train Station Information';

}

/**
 * Modifies the station accordion.
 *
 * @param array $vars
 *   Data passed to the template.
 * @param Drupal\Core\Entity\EntityInterface $entity
 *   Current NRE Station entity.
 *
 * @return mixed
 *   The modified station accordion information.
 */
function _toc_ga_amend_station_info_accordion_alter(array $vars, EntityInterface $entity): array {
  $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) {
    // Ensure accordion triggers render as headings in GA.
    $collapsible['tag_name'] = 'h3';
    if (empty($collapsible['content'])) {
      $collapsible['content']['#type'] = 'table';
      $collapsible['content']['#header'] = [];
      $collapsible['content']['#rows'] = $collapsible['content']['#rows'] ?? [];
    }
    switch ($collapsible['aiid']) {
      case 'general_info':
        $toc_code = _tm_misc_get_field_content($entity, 'field_nres_eeb_tp_operator', 'string');
        if (!$toc_code) {
          break;
        }
        \Drupal::moduleHandler()->alter('toc_name', $toc_code);

        $collapsible['content']['#rows'] = _tm_append_table_row($collapsible['content']['#rows'], $toc_code, TRUE, 'Station operator');

        break;

      case 'fares':
        $collapsible['label'] = '<i class="fas fa-ticket-alt"></i> Ticket buying and collection';
        _toc_ga_remove_entry_from_station_accordion_table($collapsible, 'Oyster cards issued here');
        _toc_ga_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 (str_contains($row[0]['data'], 'Cycle')) {
              $cycle_storage[] = $row;
              unset($collapsible['content']['#rows'][$key]);
            }
            if (str_contains($row[0]['data'], 'Car park')) {
              $car_park_rows[] = $row;
              unset($collapsible['content']['#rows'][$key]);
            }
            if (str_contains($row[0]['data'], 'Onward')) {
              $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,
          'tag_name' => 'h3',
        ];
        }

        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,
          'tag_name' => 'h3',
        ];

        $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,
          ],
          'tag_name' => 'h3',
        ];

        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'],
            ],
            'tag_name' => 'h3',
          ];
        }

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

        break;

      case 'car_park':
        $collapsible['content'] = [
          $collapsible['content'],
        ];
        if (isset($car_park_rows)) {
          $collapsible['content'][] = [
            '#type' => 'table',
            '#header' => [],
            '#rows' => $car_park_rows,
          ];
        }
        break;
    }
    if (isset($collapsible['content']['#type'])
      && $collapsible['content']['#type'] === 'table'
      && empty($collapsible['content']['#rows'])) {
      $collapsible['content'] = [];
    }
  }

  return $vars['info_accordion'];
}

/**
 * Finds a row in any table in the station accordion and removes it.
 *
 * @param array $accordion
 *   The station accordion.
 * @param string $row_header
 *   The row header text.
 */
function _toc_ga_remove_entry_from_station_accordion_table(array &$accordion, string $row_header): void {
  foreach ($accordion['content']['#rows'] as $key => $row) {
    if ($row[0]['data'] == $row_header) {
      unset($accordion['content']['#rows'][$key]);
    }
  }
}
