<?php

/**
 * @file
 * Functions supporting intercept_core.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;

/**
 * Implements hook_help().
 */
function intercept_core_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the intercept_core module.
    case 'help.page.intercept_core':
      $output = '';
      $output .= '<h3>' . new TranslatableMarkup('About') . '</h3>';
      $output .= '<p>' . new TranslatableMarkup('Provides core functionality for Intercept.') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_page_attachments().
 */
function intercept_core_page_attachments(array &$attachments) {
  // Add the intercept_client consumer id.
  $consumer_id = \Drupal::state()->get('intercept_client.id');
  $consumer = \Drupal::service('entity_type.manager')->getStorage('consumer')->load($consumer_id);
  if ($consumer) {
    $consumer_token = $consumer ? $consumer->uuid() : NULL;
    $attachments['#attached']['drupalSettings']['intercept']['consumer'] = $consumer_token;
  }

  // Add user info to drupalSettings.
  $current_user = \Drupal::currentUser();
  $user = User::load($current_user->id());
  $user_timezone = new \DateTimeZone(date_default_timezone_get());
  $utc = new \DateTime('UTC');
  $user_utc_offset = $user_timezone->getOffset($utc) / 3600;
  $attachments['#attached']['drupalSettings']['intercept']['user'] = [
    'id' => $current_user->id(),
    'uuid' => $user->uuid(),
    'name' => $user->full_name,
    'roles' => $current_user->getRoles(),
    'timezone' => date_default_timezone_get(),
    'utc_offset' => $user_utc_offset,
  ];

  $attachments['#cache']['contexts'][] = 'user';
  $attachments['#cache']['tags'][] = 'user:' . $current_user->id();
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function intercept_core_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  \Drupal::service('intercept_core.utility.redirect')->userLoginFormAlter($form, $form_state);
}

/**
 * Implements hook_theme().
 */
function intercept_core_theme() {
  return [
    'intercept_field_error_message' => [
      'variables' => ['message' => NULL],
      'template' => 'intercept-field-error-message',
    ],
    'intercept_management' => [
      'variables' => ['content' => NULL],
      'template' => 'intercept-management',
      'base hook' => 'intercept_management',
    ],
    'intercept_management_section' => [
      'variables' => [
        'title' => NULL,
        'actions' => NULL,
        'content' => NULL,
      ],
      'template' => 'intercept-management-section',
      'base hook' => 'intercept_management_section',
    ],
    'intercept_management_action' => [
      'variables' => [
        'link' => NULL,
        'description' => NULL,
      ],
      'template' => 'intercept-management-action',
      'base hook' => 'intercept_management_action',
    ],
    'intercept_reservation_status' => [
      'variables' => [
        'status' => NULL,
      ],
      'template' => 'intercept-reservation-status',
    ],
    'intercept_reservation_status_legend' => [
      'variables' => [
        'statuses' => NULL,
      ],
      'template' => 'intercept-reservation-status-legend',
    ],
    'intercept_view_switcher' => [
      'variables' => [
        'links' => [],
      ],
      'template' => 'intercept-view-switcher',
    ],
    'intercept_filter_toggle' => [
      'variables' => [
        'title' => NULL,
      ],
      'template' => 'intercept-filter-toggle',
    ],
  ];
}

/**
 * Implements hook_entity_type_build().
 */
function intercept_core_entity_type_build(array &$entity_types) {
  /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
  $entity_types['user']
    ->setFormClass('customer', '\Drupal\intercept_core\Form\UserProfileForm')
    ->setLinkTemplate('customer-form', '/user/settings/{user}');
}

/**
 * Implements hook_menu_links_discovered_alter().
 */
function intercept_core_menu_links_discovered_alter(&$links) {
  // Change the title of the default user view menu link.
  if (isset($links['user.page'])) {
    $links['user.page']['title'] = new TranslatableMarkup('Overview');
  }
}

/**
 * Implements hook_preprocess_input__date().
 */
function intercept_core_preprocess_input__date(&$variables) {
  // Attach pickadate library to fix ajax submit issues.
  $variables['#attached']['library'][] = 'intercept_core/pickadate';
}

/**
 * Perform alterations before an entity form is included in the IEF widget.
 *
 * @param array $entity_form
 *   Nested array of form elements that comprise the entity form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The form state of the parent form.
 */
function intercept_core_inline_entity_form_entity_form_alter(array &$entity_form, FormStateInterface &$form_state) {
  if (array_key_exists('#form_id', $entity_form) && $entity_form['#form_id'] == 'user_customer_form' && $entity_form['#entity_type'] == 'profile') {
    $form_state->getFormObject()->alterProfileForm($entity_form, $form_state);
  }
  if ($entity_form['#entity_type'] == 'media') {
    // Hide the revision log message field on all media forms.
    $entity_form['revision_log_message']['#access'] = FALSE;
  }
}

/**
 * Implements hook_entity_extra_field_info().
 */
function intercept_core_entity_extra_field_info() {
  $extra = [];

  $extra['user']['user']['form']['customer_profile'] = [
    'label' => new TranslatableMarkup('Customer profile form'),
    'description' => new TranslatableMarkup('An inline entity form for the customer profile entity.'),
    'visible' => FALSE,
  ];

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_load().
 */
function intercept_core_user_load(array $entities) {
  // @todo This would be more efficient as a calculated field.
  $profile_storage = \Drupal::service('entity_type.manager')->getStorage('profile');
  $uids = array_keys($entities);
  $profiles = $profile_storage->loadByProperties([
    'uid' => reset($uids),
    'status' => 1,
  ]);
  foreach ($entities as $entity) {
    $uid = $entity->id();
    $profile = array_filter($profiles, function ($profile) use ($uid) {
      $profile_uid = $profile->uid->first()->getValue()['target_id'];
      return $uid == $profile_uid;
    });
    // Set defaults to use regardless of profile data.
    $entity->full_name = $entity->name->getString();
    $entity->first_name = '';
    $entity->barcode = '';

    if ($profile = reset($profile)) {

      $first_name = trim($profile->field_first_name->getString());
      if (!empty($first_name)) {
        $entity->first_name = $first_name;
      }
      $full_name = implode(' ', [
        $first_name,
        trim($profile->field_last_name->getString()),
      ]);
      if (!empty(trim($full_name))) {
        $entity->full_name = $full_name;
      }
      $entity->barcode = $profile->field_barcode->getString();
      $entity->addCacheTags($profile->getCacheTags());
    }
  }
}

/**
 * Gets the nested file attached to the image_primary field.
 */
function intercept_core_get_primary_image_file(Node $node) {
  if (!$node->hasField('image_primary')) {
    return NULL;
  }
  if (($image_primary = $node->image_primary->referencedEntities()) && ($files = $image_primary[0]->field_media_image->referencedEntities())) {
    return $files[0];
  }
  return NULL;
}
