<?php

/**
 * @file
 * Hook implementations for the webform_workflows_element module.
 */

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\user\Entity\User;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Determine whether to show workflow log on page.
 *
 * @param string $operation
 *   The operation.
 * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
 *   The webform submission.
 *
 * @return bool
 *   True if authorized.
 */
function webform_workflows_element_check_show_log(string $operation, WebformSubmissionInterface $webform_submission): bool {

  if (!Drupal::moduleHandler()->moduleExists('webform_submission_log')) {
    return FALSE;
  }

  $account = Drupal::currentUser();
  $workflowsManager = Drupal::service('webform_workflows_element.manager');

  $webform = $webform_submission->getWebform();
  if ($webform) {
    $workflow_elements = $workflowsManager->getWorkflowElementsForWebform($webform);

    foreach ($workflow_elements as $element) {
      if (!isset($element['#show_log_' . $operation]) || $element['#show_log_' . $operation]) {
        $hasAccess = $workflowsManager->checkUserCanAccessElement($account, $webform, $element, $webform_submission);
        if ($hasAccess) {
          return TRUE;
        }
      }
    }
  }

  return FALSE;
}

/**
 * Get a rendered log table of workflow events for a submission.
 *
 * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
 *   The webform submission.
 *
 * @return array
 *   Log render array.
 *
 * @throws \Drupal\Core\Entity\EntityMalformedException
 */
function webform_workflows_element_get_rendered_log(WebformSubmissionInterface $webform_submission): ?array {
  if (!Drupal::moduleHandler()->moduleExists('webform_submission_log')) {
    return NULL;
  }

  $source_entity = $webform_submission->getSourceEntity();

  // Header.
  $header = [];

  $header['timestamp'] = [
    'data' => t('Date'),
    'field' => 'log.timestamp',
    'sort' => 'desc',
    'class' => [RESPONSIVE_PRIORITY_LOW],
  ];
  $header['uid'] = [
    'data' => t('User'),
    'field' => 'user.name',
    'class' => [RESPONSIVE_PRIORITY_LOW],
  ];
  $header['message'] = [
    'data' => t('Message'),
    'field' => 'log.message',
    'class' => [RESPONSIVE_PRIORITY_LOW],
  ];

  // Query.
  $options = ['header' => $header, 'limit' => 50];
  $logs = Drupal::service(
    'webform_submission_log.manager'
  )->loadByEntities($webform_submission, $source_entity, NULL, $options);

  // Rows.
  $rows = [];
  foreach ($logs as $log) {
    if (!in_array($log->operation, [
      'workflow status changed',
      'submission created',
    ])) {
      continue;
    }

    $row = [];

    $row['timestamp'] = Drupal::service('date.formatter')
      ->format($log->timestamp, 'short');
    $row['uid'] = [
      'data' => [
        '#theme' => 'username',
        '#account' => User::load($log->uid),
      ],
    ];
    if (isset($log->variables['@transition_id'])) {
      // phpcs:disable
      // @todo nicer formatting for these logs using technical reference
      //   $technicalRefs = explode(':', str_replace("Technical reference: ", "", $log->variables['@transition_id']));
      //      $element_id = $technicalRefs[1];
      //      $workflow_plugin_id = $technicalRefs[2];
      //      $transition_id = $technicalRefs[3];
      //      $new_state_id = str_replace(']', '', $technicalRefs[4]);
      //      $old_state_id = isset($technicalRefs[5]) ? str_replace(']', '', $technicalRefs[5]) : '';
      // phpcs:enable
      // In the meantime just hide the technical reference.
      $log->variables['@transition_id'] = '';
    }

    // @todo the following phpcs:ignore should be verified.
    // phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
    $message = new TranslatableMarkup($log->message, $log->variables);
    // 244991 244797
    $row['message'] = [
      'data' => [
        '#markup' => $message,
      ],
    ];

    $rows[] = $row;
  }

  $build['table'] = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#sticky' => TRUE,
    '#empty' => t('No log messages available.'),
  ];

  return [
    'log_fieldset' => [
      '#type' => 'details',
      '#title' => t('Workflow log'),
      '#weight' => -18,
      'log' => [
        '#type' => 'markup',
        '#group' => 'log_fieldset',
        '#markup' => Drupal::service('renderer')->render($build),
      ],
    ],

  ];
}
