<?php

/**
 * @file
 * Contains access_unpublished implementations.
 */

use Drupal\access_unpublished\Form\AccessUnpublishedForm;
use Drupal\access_unpublished\AccessUnpublished;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function access_unpublished_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.access_unpublished':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Grants access to view unpublished content to anyone who has a unique URL and appropriate permissions.') . '</p>';
      $output .= '<p>' . t('Visit the <a href=":project_link">Project page</a> on Drupal.org for more information.', [
        ':project_link' => 'https://www.drupal.org/project/access_unpublished',
      ]);

      return $output;
  }
}

/**
 * Implements hook_entity_access().
 */
function access_unpublished_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
  // Early exit for non-view operations to avoid unnecessary processing.
  if ($operation !== 'view') {
    return AccessResult::neutral();
  }

  // Early exit if entity is published - most common case for anonymous users.
  // Only check for published status if the entity implements
  // EntityPublishedInterface.
  if ($entity instanceof EntityPublishedInterface && $entity->isPublished()) {
    return AccessResult::neutral();
  }

  // Early exit if entity type doesn't support access unpublished.
  if (!AccessUnpublished::applicableEntityType($entity->getEntityType())) {
    return AccessResult::neutral();
  }

  // Only load services and config if we've passed the basic checks.
  /** @var \Drupal\access_unpublished\TokenGetter $tokenGetter */
  $tokenGetter = \Drupal::service('access_unpublished.token_getter');

  // Early exit if no token is present in the request.
  $token = $tokenGetter->getToken();
  if (!$token) {
    return AccessResult::neutral()->addCacheableDependency($entity);
  }

  // Build permission string and load config only when needed.
  $permission = 'access_unpublished ' .
    $entity->getEntityTypeId() .
    ($entity->getEntityType()->hasKey('bundle') ? ' ' . $entity->bundle() : '');

  // Early exit if user doesn't have permission - avoids config loading for
  // anonymous users.
  if (!$account->hasPermission($permission)) {
    return AccessResult::neutral()->addCacheableDependency($entity);
  }

  // Only load config when we actually need it.
  $config = \Drupal::config('access_unpublished.settings');

  $result = AccessResult::neutral()
    ->addCacheContexts(['url.query_args:' . $config->get('hash_key')])
    ->cachePerPermissions()
    ->addCacheableDependency($config)
    ->addCacheableDependency($entity);

  // All conditions are met, check for valid access token.
  $tokens = \Drupal::entityTypeManager()->getStorage('access_token')
    ->loadByProperties([
      'entity_type' => $entity->getEntityType()->id(),
      'entity_id' => $entity->id(),
      'value' => $token,
    ]);

  if ($tokens) {
    $tokenEntity = reset($tokens);
    $result->addCacheableDependency($tokenEntity);
    if (!$tokenEntity->isExpired()) {
      $result = AccessResult::allowed()
        ->setCacheMaxAge($tokenEntity->get('expire')->value - \Drupal::time()->getRequestTime())
        ->inheritCacheability($result);
    }
  }

  return $result;
}

/**
 * Implements hook_entity_delete().
 */
function access_unpublished_entity_delete(EntityInterface $entity) {
  /** @var \Drupal\access_unpublished\AccessTokenManager $tokenManager */
  $tokenManager = \Drupal::service('access_unpublished.access_token_manager');
  foreach ($tokenManager->getAccessTokensByEntity($entity) as $token) {
    $token->delete();
  }
}

/**
 * Implements hook_cron().
 */
function access_unpublished_cron() {
  $config = \Drupal::config('access_unpublished.settings');
  if ($config->get('cleanup_expired_tokens')) {
    $strtotime = strtotime($config->get('cleanup_expired_tokens_period'));
    /** @var \Drupal\access_unpublished\AccessTokenManager $tokenManager */
    $tokenManager = \Drupal::service('access_unpublished.access_token_manager');
    foreach ($tokenManager->getAccessTokens('expired') as $token) {
      if ($strtotime > $token->get('expire')->value) {
        $token->delete();
      }
    }
  }
}

/**
 * Implements hook_form_alter().
 */
function access_unpublished_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  \Drupal::service('class_resolver')
    ->getInstanceFromDefinition(AccessUnpublishedForm::class)
    ->formAlter($form, $form_state, $form_id);
}
