<?php

use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Implements hook__preprocess_views_exposed_form().
 */
function toc_sr_preprocess_views_exposed_form(&$vars) {
  // Let's invert the tags buttons for SR.
  _toc_sr_preprocess_views_exposed_form_invert_tags($vars);
}

/**
 * Implements hook_preprocess_fieldset__FIELD_ID().
 */
function toc_sr_preprocess_fieldset__region(&$vars) {
  toc_master_preprocess_fieldset__checkboxes($vars);
  _toc_sr_clear_fieldset_radioboxes($vars);
}

/**
 * Implements hook_preprocess_fieldset__FIELD_ID().
 */
function toc_sr_preprocess_fieldset__ocat(&$vars) {
  toc_master_preprocess_fieldset__checkboxes($vars);
  _toc_sr_clear_fieldset_radioboxes($vars);
}

/**
 * Unset some default classes for the filter tags.
 *
 * @param $vars
 *
 * @return void
 */
function _toc_sr_clear_fieldset_radioboxes(&$vars) {
  $vars['attributes']['class'][] = 'no-tags'; // Hide tags icon.
  // $vars['attributes']['class'][] = 'no-shd'; // Hide bottom shadow.
  $vars['attributes']['class'][] = 'mb-2';
}

/**
 * Styled Tags filters can have solid or border style. The solid style is
 * normal and bordered is inverted. SR needs them inverted, this is a quick
 * helper to apply it to all 'tags' styles radios and checkboxes in the
 * views filters form.
 *
 * @param $vars
 *
 * @return void
 */
function _toc_sr_preprocess_views_exposed_form_invert_tags(&$vars) {
  $filters = Element::children($vars['form']);
  foreach ($filters as $filter) {
    if (!empty($vars['form'][$filter]['#toc_master_styled_filters'])) {
      if ($vars['form'][$filter]['#toc_master_styled_filters'] == 'tags') {
        foreach (Element::children($vars['form'][$filter]) as $cid => $name) {
          $vars['form'][$filter][$name]["#toc_master_styled_filters_inverted"] = TRUE;
        }
      }
    }
  }
}

/**
 * Implements hook_preprocess_views_exposed_form().
 *
 * Replaces the version in TOC Master that to support the use of the Postcode
 * Regions taxonomy.
 *
 * @see _tm_views_limit_filter_options();
 * @see toc_master_preprocess_views_exposed_form__offers_frontend_views__block_1()
 */
function toc_sr_preprocess_views_exposed_form__offers_postcode_regions_frontend_views__block(&$vars) {
  $filters_tabcordion_id = Html::getUniqueId("tabcordion");
  // Preserve form for sub theme alters.
  $vars['form_original'] = $vars['form'];
  // These are Image and Tags styled elements, but come from Radios, so they are
  // within fieldsets. Hide their label for now.
  // @todo - Create a new Tags style without Tags flex legend.
  $filter_type = $vars['form']['#info']['filter-field_of_type_target_id']['value'];
  $vars['form'][$filter_type]['#attributes']['class'][] = 'fs-tags-no-label mb-0';
  // Add some auto-submit features using states.
  $vars['form'][$filter_type]['#attributes']['onchange'] = 'jQuery(".offers-ajax-submit-btn").click()';

  // Make the main search label inline, this looks best when button on same row,
  // otherwise you have to hide the label, and we are *not* doing that.
  $vars['form']['combine']['#title_display'] = 'invisible';
  $vars['form']['combine']['#size'] = 'lg'; // Input size.
  $vars['form']['combine']['#input_suffix']['#size'] = 'lg'; // Suffix size.

  // Move Value to Text which is rendered with text|raw.
  $vars['form']['actions']['reset']['#text'] = '<i class="fas fa-times-circle me-3"></i>' . $vars['form']['actions']['reset']['#value'];
  $vars['form']['actions']['reset']['#size'] = 'lg';
  //$vars['form']['actions']['reset']['#expanded'] = 1;

  $vars['form']['actions']['#element_classes'] = 'form-group-no-pad';
  // Create a new submit button for embedding in the Categories filter.
  $new_button = $vars['form']['actions']['submit'];
  $new_button['#outline'] = TRUE;
  $new_button['#value'] = 'Filter by these categories';
  $new_button['#attributes']['class'][] = 'mb-0 mt-3';
  $new_button['#id'] = _toc_rndid_ifempty($new_button, '#id');
  $first_button = \Drupal::service('renderer')->render($new_button);
  // Create a the first tab for our tabcordion.
  $filter_category = $vars['form']['#info']['filter-field_of_category_target_id']['value'];
  $first_item = _toc_master_views_filters_tabcordion_tab($vars['form'][$filter_category], $filters_tabcordion_id, '', $first_button);
  unset($vars['form'][$filter_category]);
  // Render our Nearest stations field so it can be embedded in tabcordion.
  $station_search_markup = '';
  if (!empty($vars['form']['combine_1'])) {
    $station_search = $vars['form']['combine_1'];
    $station_search_markup = \Drupal::service('renderer')->render($station_search);
    unset($vars['form']['combine_1']);
  }
  // Create a new submit button to go with the Regions filter.
  $new_button = $vars['form']['actions']['submit'];
  $new_button['#outline'] = TRUE;
  $new_button['#value'] = 'Filter by these regions';
  $new_button['#attributes']['class'][] = 'mb-0 mt-3';
  $new_button['#id'] = _toc_rndid_ifempty($new_button, '#id');
  $second_button = \Drupal::service('renderer')->render($new_button);
  // Create some markup to go in the tabcordion, with the rendered search
  // and the rendered button.
  $prefix = '';
  $suffix = $second_button;
  if ($station_search_markup) {
    $prefix = "<div class='row'><div class='col-md-6'>" . $station_search_markup . "</div><div class='col-md-6'>";
    $suffix = "$second_button</div></div>";
  }

  // Create the second tabcordion.
  $filter_region = $vars['form']['#info']['filter-field_of_er_postcode_region_target_id']['value'];
  $second_item = _toc_master_views_filters_tabcordion_tab($vars['form'][$filter_region], $filters_tabcordion_id, $prefix, $suffix);
  unset($vars['form'][$filter_region]);
  // Create the tabcordion component.
  $vars['filters_tabcordion'] = [
    '#type' => 'pattern',
    '#id' => 'bs-accordion-items',
    '#variant' => 'aci_c_nbgi',
    '#fields' => [
      'items' => [
        $first_item,
        $second_item,
      ],
      'list_prefix' => '<i class="fas fa-sliders-h"></i> Showing ',
      'list_suffix' => '',
    ],
    '#settings' => [
      'pid' => $filters_tabcordion_id,
      'toggle' => 'chevron',
    ],
  ];
  // Finally, we are using some custom ajax submit triggers, so we need
  // a submit who has an attribute that will not change on ajax reload,
  // so that we can trigger it.
  $vars['form']['actions']['submit']['#attributes']['class'][] = 'offers-ajax-submit-btn';
}

/**
 * Implements hook_preprocess_views_exposed_form().
 *
 * Replaces the version in TOC Master that to support the use of the Postcode
 * Regions taxonomy.
 *
 * @see _tm_views_limit_filter_options();
 * @see toc_master_preprocess_views_exposed_form__offers_frontend_views__block_1()
 */
function toc_sr_preprocess_views_exposed_form__the_list__block(&$vars) {
  // Preserve form for sub theme alters.
  $vars['form_original'] = $vars['form'];

  // Make the main search label inline, this looks best when button on same row,
  // otherwise you have to hide the label, and we are *not* doing that.
  $vars['form']['combine']['#title_display'] = 'invisible';
  $vars['form']['combine']['#size'] = 'lg'; // Input size.
  $vars['form']['combine']['#input_suffix']['#size'] = 'lg'; // Suffix size.

  // Move Value to Text which is rendered with text|raw.
  $vars['form']['actions']['reset']['#text'] = '<i class="fas fa-times-circle me-3"></i>' . $vars['form']['actions']['reset']['#value'];
  $vars['form']['actions']['reset']['#size'] = 'lg';
  //$vars['form']['actions']['reset']['#expanded'] = 1;

  $vars['form']['actions']['#element_classes'] = 'form-group-no-pad';

  // Create the tabcordion component.
  $filters_tabcordion_id = Html::getUniqueId("tabcordion");
  $vars['filters_tabcordion'] = [
    '#type' => 'pattern',
    '#id' => 'bs-accordion-items',
    '#variant' => 'aci_c_nbgi',
    '#fields' => [
      'items' => [],
      'list_prefix' => '<i class="fas fa-sliders-h"></i> Showing ',
      'list_suffix' => '',
    ],
    '#settings' => [
      'pid' => $filters_tabcordion_id,
      'toggle' => 'chevron',
    ],
  ];

  // Create the first tab for our tabcordion.
  $filter_category = $vars['form']['#info']['filter-field_tl_er_categories_target_id']['value'];
  if ($filter_category) {
    // Create a new submit button for embedding in the Categories filter.
    $new_button = $vars['form']['actions']['submit'];
    $new_button['#outline'] = TRUE;
    $new_button['#value'] = 'Filter by these categories';
    $new_button['#attributes']['class'][] = 'mb-0 mt-3';
    $new_button['#id'] = _toc_rndid_ifempty($new_button, '#id');
    $first_button = \Drupal::service('renderer')->render($new_button);
    $first_item = _toc_master_views_filters_tabcordion_tab($vars['form'][$filter_category], $filters_tabcordion_id, '', $first_button);
    unset($vars['form'][$filter_category]);
    if ($first_item) {
      $vars['filters_tabcordion']['#fields']['items'][] = $first_item;
    }
  }

  // Create the second tabcordion button.
  $filter_region = $vars['form']['#info']['filter-field_tl_er_postcode_region_target_id']['value'];
  if ($filter_region) {
    // Create a new submit button to go with the Regions filter.
    $new_button = $vars['form']['actions']['submit'];
    $new_button['#outline'] = TRUE;
    $new_button['#value'] = 'Filter by these regions';
    $new_button['#attributes']['class'][] = 'mb-0 mt-3';
    $new_button['#id'] = _toc_rndid_ifempty($new_button, '#id');
    $second_button = \Drupal::service('renderer')->render($new_button);
    // Create some markup to go in the tabcordion, with the rendered search
    // and the rendered button.
    $prefix = '';
    $suffix = $second_button;

    $second_item = _toc_master_views_filters_tabcordion_tab($vars['form'][$filter_region], $filters_tabcordion_id, $prefix, $suffix);
    unset($vars['form'][$filter_region]);
    if ($second_item) {
      $vars['filters_tabcordion']['#fields']['items'][] = $second_item;
    }
  }

  // Finally, we are using some custom ajax submit triggers, so we need
  // a submit who has an attribute that will not change on ajax reload,
  // so that we can trigger it.
  $vars['form']['actions']['submit']['#attributes']['class'][] = 'events-ajax-submit-btn';
}

/**
 * Override default preprocess for Offer Types image radios.
 *
 * Ensure that the correct field name in the field_of_type is used for the image.
 *
 * @param $vars
 * @param $hook
 * @param $info
 *
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 */
function toc_sr_preprocess_form_element__otype__radio(&$vars, $hook, $info) {
  // A radio button with the name of otype is not guaranteed to be the Offer Type
  // field so do some basic checking here first.
  if (isset($vars['element']['#view']) && $vars['element']['#view'] === 'offers_postcode_regions_frontend_views'
    && isset($vars['element']['#vocab']) && $vars['element']['#vocab'] === 'offer_type') {
    _toc_master_preprocess_radio_styled_tag($vars, 'field_category_image');
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function toc_sr_form_flexipass_check_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#attributes']['class'][] = 'mb-0';
  if (!empty($form['origin_station'])) {
    $form['origin_station']['#wrapper_attributes']['class'][] = 'input-group';
  }
  if (!empty($form['swap_stations'])) {
    $form['swap_stations']['#text'] = '<i class="fas fa-exchange-alt"></i><span class="sr-only">' . $form['swap_stations']['#value'] . '</span>';
    $form['swap_stations']['#attributes']['class'][] = 'btn btn-icon a-pri m-0 mx-auto d-md-block swap-stations';
  }
  if (!empty($form['destination_station'])) {
    $form['destination_station']['#wrapper_attributes']['class'][] = 'input-group';
  }
  if (!empty($form['actions']['reset'])) {
    $form['actions']['reset']['#status'] = 'link';
    $form['actions']['reset']['#text'] = $form['actions']['reset']['#text'] . ' <i class="far fa-times-circle" aria-hidden="true"></i>';
    $form['actions']['reset']['#attributes']['class'][] = 'mb-0';
    $form['actions']['reset']['#attributes']['class'][] = 'p-3';
  }
  if (!empty($form['actions']['submit'])) {
    $form['actions']['submit']['#attributes']['class'][] = 'float-end';
  }
}

/**
 * Implements hook_form_views_exposed_form_alter().
 *
 * @see toc_master/theme/templates/views/news/views-exposed-form--news-blocks--block-3.html.twig
 */
function _toc_sr_form_views_exposed_form_alter__news_blocks__block_3(&$form, FormStateInterface $form_state, $form_id) {
  foreach (Element::children($form['actions']) as $cid => $name) {
    $form['actions'][$name]['#attributes'] = [
      'class' => ['btn-md', 'flex-lg-fill', 'mb-0'],
    ];
  }
}
