<?php

/**
 * @file
 * Functions to support views.
 */

use Drupal\Component\Utility\Html;
use Drupal\Core\Link;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;

/**
 * Preprocess for Stations list block.
 */
function toc_emr_preprocess_views_view__stations__block_1(&$vars) {
  $pid = Html::getUniqueId('st-atoz');
  $items = [];
  $vars['ac_vars'] = FALSE;
  if (!empty($vars["rows"])) {
    foreach ($vars["rows"] as $row) {
      $title = strip_tags($row['#title']);
      $aiid = Html::getUniqueId('st-atoz-' . $title);
      $items[] = [
        "pid" => $pid,
        "aiid" => $aiid,
        "label" => $title,
        "content" => $row,
      ];
    }
  }
  if (!empty($items)) {
    $vars['ac_vars'] = [
      'pid' => $pid,
      'items' => $items,
      'wrapper_class' => 'mt-3',
    ];
  }
}

/**
 * Preprocess hook news_blocks__greener_anglia_blog.
 */
function toc_emr_preprocess_views_view__news_blocks__travel_inspiration(&$vars) {
  $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();
      $media_id = _tm_misc_get_field_content($entity, 'field_er_blog_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_blog_category', 'reference', [], -1);
      $tags = [];
      if ($genre_terms) {
        $x = 0;
        $m = 4;
        foreach ($genre_terms as $genre_term) {
          if ($x < $m) {
            $x++;
            $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-travel-inspiration-cat-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' => '.travel-inspiration-ajax-submit-btn',
            ];
            $tags[] = [
              'name' => $name,
              'attr' => new Attribute($attr),
            ];
          }
        }
      }
      $items[] = [
        'img_url' => $image['url'] ?? '',
        'img_alt' => $image['alt'] ?? '',
        'title' => $title,
        'card_link' => $link,
        'tags' => $tags,
      ];
    }
  }
  if (!empty($items)) {
    $vars['items'] = $items;
  }
  $vars['batch'] = 3;
}

/**
 * Preprocess hook views_view__destinations__listing.
 */
function toc_emr_preprocess_views_view__destinations__listing(&$vars) {
  $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_summary();
      $sub_title = _tm_misc_get_field_content($entity, 'body', 'render', $text_format);
      $sub_title = _tm_check_markup($sub_title);
      $media_image = _tm_misc_get_field_content($entity, 'field_dest_er_image', 'reference');
      // Use the first image only for the view.
      $image = [
        'url' => '',
        'alt' => '',
      ];
      if ($media_image) {
        $image = _tm_misc_get_styled_images_from_media($media_image->id(),
          'card_image', 'field_media_image', 'media', 'url_alt');
      }
      // Tags.
      $genre_terms = _tm_misc_get_field_content($entity, 'field_dest_er_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-field-dest-er-category-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' => '.destinations-ajax-submit-btn',
          ];
          $tags[] = [
            'name' => $name,
            'attr' => new Attribute($attr),
          ];
        }
      }
      $items[] = [
        'img_url' => $image['url'] ?? '',
        'img_alt' => $image['alt'] ?? '',
        'title' => $title,
        'body' => $sub_title,
        'card_link' => $link,
        'tags' => $tags
      ];
    }
  }
  if (!empty($items)) {
    $vars['items'] = $items;
  }
}

/**
 * Preprocess hook views_view__service_alterations_this_week__block.
 */
function toc_emr_preprocess_views_view__service_alterations_this_week__block(&$vars) {
  $items = _toc_emr_preprocess_service_alterations_week($vars);
}

/**
 * Preprocess hook views_view__service_alterations_next_week__block.
 */
function toc_emr_preprocess_views_view__service_alterations_next_week__block(&$vars) {
  $items = _toc_emr_preprocess_service_alterations_week($vars);
}

/**
 * Helper for the above.
 */
function _toc_emr_preprocess_service_alterations_week(&$vars) {
  $items = [];
  $numb_rows = 2;
  /** @var \Drupal\views\ViewExecutable $view */
  if (!empty($vars["rows"])) {
    $view = $vars["rows"][0]['#view'];
    if (!empty($vars["rows"][0])) {
      foreach ($view->result as $key => $result) {
        $entity = $result->_entity;
        $id = $entity->Id();
        $url = $entity->toUrl()->toString();
        $subtitle = _tm_misc_get_field_content($entity, 'title');
        $dates = _tm_misc_get_field_content($entity, 'field_sa_dr_dates');
        $dates = explode(', ', $dates);
        $title = '';
        if (!empty($dates[1])) {
          $from = _tm_date($dates[0], 'd M Y');
          $to = _tm_date($dates[1], 'd M Y');
          $title = "$from to $to";
        }
        $items[] = [
          'url' => $url,
          'title' => $title,
          'subtitle' => $subtitle,
        ];
        if ($key == ($numb_rows - 1)) {
          break;
        }
      }
    }
    if (!empty($items)) {
      $vars['items'] = $items;
    }
    if ($view->total_rows > $numb_rows) {
      $more_count = $view->total_rows - $numb_rows;
      $link_text = "Plus $more_count other dates affected";
      $calendar_month = '';
      switch ($vars['id']) {
        case 'service_alterations_this_week':
          $calendar_month = 'current';
          break;
        case 'service_alterations_next_week':
          if (date('m') == date('m', strtotime('next week'))) {
            $calendar_month = 'current';
          }
          else {
            $calendar_month = 'next';
          }
          break;
      }
      static $url = [];
      if (!isset($url[$calendar_month])) {
        if ($calendar_month == 'current' || !isset($url['current'])) {
          $url['current'] = FALSE;
          $settings = \Drupal::config('service_alterations_frontend_views.settings');
          $calendar_nid = $settings->get('calendar_node');
          if ($calendar_nid) {
            $url['current'] = \Drupal::service('path_alias.manager')
              ->getAliasByPath('/node/' . $calendar_nid);
          }
        }
        if ($calendar_month != 'current') {
          $url[$calendar_month] = $url['current'];
          if ($url['current']) {
            switch ($calendar_month) {
              case 'next':
                $start = date('Y-m-d', strtotime('first day of next month'));
                $end = date('Y-m-d', strtotime('last day of next month'));
                $url[$calendar_month] .= '?date=' . $start . '--' . $end;
                break;
            }
          }
        }
      }
      $vars['more_text'] = $link_text;
      $vars['more_link'] = Url::fromUserInput($url[$calendar_month])
        ->toString();
    }
  }
}


/**
 * Preprocess hook preprocess_views_view__VIEW_ID.
 */
function toc_emr_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 hook preprocess_views_view__VIEW_ID.
 */
function toc_emr_preprocess_views_view__offers_frontend_views__block_1(&$vars) {
  $vars['header'] = [];
  $vars['offers_header'] = [];

  $offers_settings = \Drupal::config('days_out_guide_content_type.settings');
  $overwrite_badge = $offers_settings->get('overwrite_badge');
  foreach($vars['items'] as &$item) {
    if ($overwrite_badge) {
      $item['badge_text_top'] = $offers_settings->get('overwrite_badge_top');
    }
    if (isset($item['badge_text_bottom']) && $item['badge_text_bottom'] === '£0.00') {
      $item['badge_text_bottom'] = '';
    }
  }
}

/**
 * Preprocess for views_view_unformatted__stations__block_1.
 */
function toc_emr_preprocess_views_view_unformatted__stations__block_1(&$vars) {
  $items = [];
  if (!empty($vars["rows"])) {
    foreach ($vars["rows"] as $group) {
      if (!empty($group["content"]['#row'])) {
        $entity = $group["content"]['#row']->_entity;
        $url = $entity->toUrl()->toString();
        $node_title = $entity->get('title')->getString();
        $items[] = [
          'link' => [
            '#markup' => "<a href='$url' class='a-sec'>$node_title</a>",
          ],
        ];
      }
    }
  }
  $vars['items'] = $items;
  $vars['cols'] = (ceil(count($items) / 3)) ?? 1;
}

/**
 * Preprocess for views_view__service_alterations_date_range__block.
 */
function toc_emr_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-default btn-lg';
  $vars['btn_prev_class'] = 'btn btn-default btn-lg';

  $vars['prev_icon'] = 'fas fa-arrow-left';
  $vars['next_icon'] = 'fas fa-arrow-right';

  // 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 for views_view__faqs_eck.
 */

function toc_emr_preprocess_views_view__faqs_eck(&$vars) {

  if (!empty($vars['ac_vars']['items'])) {
    foreach ($vars['ac_vars']['items'] as $k => $item) {
      $content= $item['orig']['content'];
      $url = $item['orig']['url'];
      $aiid = $item['orig']['aiid'];
      $share_link = [
        '#type' => 'pattern',
        '#id' => 'tm_bits_hotlink',
        '#fields' => [
          'url' => $url,
          'button_text' => 'Share',
          'lid' => $aiid,
        ],
        '#settings' => [
          'btn_class' => 'btn-default btn-sm btn',
        ],
      ];
      $item['content'] = $content . \Drupal::service('renderer')->render($share_link);
      $vars['ac_vars']['items'][$k] = $item;
    }
  }


}
