<?php
// phpcs:ignoreFile

/**
 * @file
 * Contains assessments.module.
 */

use Drupal\anu_lms\Settings;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Implements hook_views_data_alter().
 */
function anu_lms_assessments_views_data_alter(array &$data) {
  $data['assessment_question_result']['assessment_result']['relationship'] = [
    'title' => t('Quiz result'),
    'label' => t('Quiz result'),
    'group' => 'Question result',
    'help' => t('Reference to the quiz result for question results'),
    'id' => 'standard',
    'base' => 'assessment_result',
    'base field' => 'aqrid',
    'field' => 'id',
  ];

  $data['assessment_question']['assessment_question_result']['relationship'] = [
    'title' => t('Question result'),
    'label' => t('Question result'),
    'group' => 'Question',
    'help' => t('Reference to the Question result'),
    'id' => 'standard',
    'base' => 'assessment_question_result',
    'base field' => 'aqid__target_id',
    'field' => 'id',
  ];
}

/**
 * Workaround to show translatable fields inside nested paragraphs.
 *
 * @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 anu_lms_assessments_inline_entity_form_entity_form_alter(array &$entity_form, FormStateInterface $form_state) {
  $children = Element::children($entity_form);

  foreach ($children as $field_name) {
    if (!empty($entity_form[$field_name]['#multilingual']) && $entity_form[$field_name]['#multilingual']) {
      $entity_form[$field_name]['#access'] = TRUE;
    }
  }

  // Override labels for "add new quiz" form.
  if ($entity_form['#bundle'] === 'module_assessment' && $entity_form['#entity_type'] === 'node') {
    $settings = \Drupal::service('anu_lms.settings');
    $entity_form['#ief_labels']['singular'] = strtolower($settings->getEntityLabel(Settings::ENTITY_TYPE_QUIZ));
    $entity_form['#ief_labels']['plural'] = strtolower($settings->getEntityLabel(Settings::ENTITY_TYPE_QUIZ, TRUE));
  }
}

/**
 * Implements hook_entity_form_display_alter().
 *
 * From
 * https://www.drupal.org/forum/support/module-development-and-code-questions/2017-05-14/how-to-specifymodify-form-view-mode#comment-13458568
 * Use hook_entity_form_mode_alter() after Drupal 9.2.0.
 */
function anu_lms_assessments_entity_form_display_alter(?EntityFormDisplayInterface &$form_display, array $context) {
  if ($context['entity_type'] === 'paragraph' && $context['bundle'] === 'course_modules') {
    $storage = Drupal::service('entity_type.manager')
      ->getStorage('entity_form_display');
    $quiz = $storage->load('paragraph.course_modules.quiz');
    if ($quiz) {
      $form_display = $storage->load('paragraph.course_modules.quiz');
    }
  }
}

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function anu_lms_assessments_field_widget_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] === 'course_modules') {
    $settings = \Drupal::service('anu_lms.settings');

    // Adapt section title.
    $element['subform']['field_module_assessment']['widget']['#field_title'] = $settings->getEntityLabel(Settings::ENTITY_TYPE_QUIZ, TRUE);

    $bundleName = strtolower($settings->getEntityLabel(Settings::ENTITY_TYPE_QUIZ));

    // Adapt "Add new quiz".
    $addNew = $element['subform']['field_module_assessment']['widget']['actions']['ief_add']['#value'] ?? NULL;
    if ($addNew) {
      $button_label = new TranslatableMarkup($addNew->getUntranslatedString(), ['@type_singular' => $bundleName]);
      $element['subform']['field_module_assessment']['widget']['actions']['ief_add']['#value'] = $button_label;
    }

    // Adapt "Add existing quiz".
    $addExisting = $element['subform']['field_module_assessment']['widget']['actions']['ief_add_existing']['#value'] ?? NULL;
    if ($addExisting) {
      $button_label = new TranslatableMarkup($addExisting->getUntranslatedString(), ['@type_singular' => $bundleName]);
      $element['subform']['field_module_assessment']['widget']['actions']['ief_add_existing']['#value'] = $button_label;
    }
  }
}

/**
 * Implements hook_inline_entity_form_reference_form_alter().
 *
 * Overrides "quizzes" in "add existing" form.
 */
function anu_lms_assessments_inline_entity_form_reference_form_alter(&$entity_form, &$form_state) {
  if (isset($entity_form['entity_id']['#selection_settings']['target_bundles']) && in_array('module_assessment', $entity_form['entity_id']['#selection_settings']['target_bundles']) && $entity_form['#entity_type'] === 'node') {
    $settings = \Drupal::service('anu_lms.settings');
    $bundleName = $settings->getEntityLabel(Settings::ENTITY_TYPE_QUIZ);

    // Render title.
    $button_label = new TranslatableMarkup($entity_form['#title']->getUntranslatedString(), ['@type_singular' => strtolower($bundleName)]);
    $entity_form['#title'] = $button_label;
    $entity_form['entity_id']['#title'] = $bundleName;

    // Render Save button.
    $iefReferenceSave = $entity_form['actions']['ief_reference_save']['#value'] ?? NULL;
    if ($iefReferenceSave) {
      $button_label = new TranslatableMarkup($iefReferenceSave->getUntranslatedString(), ['@type_singular' => strtolower($bundleName)]);
      $entity_form['actions']['ief_reference_save']['#value'] = $button_label;
    }

    $entity_form['#ief_labels']['singular'] = $bundleName;
    $entity_form['#ief_labels']['plural'] = $settings->getEntityLabel(Settings::ENTITY_TYPE_QUIZ, TRUE);
  }
}

/**
 * Implements hook_field_group_build_pre_render_alter().
 */
function anu_lms_assessments_field_group_form_process_build_alter(&$element) {
  // Make sure form ID is present in the form element.
  if (empty($element['form_id']['#value'])) {
    return;
  }

  if ($element['form_id']['#value'] === 'node_module_assessment_form') {
    // Get "Prevent multiple submissions" description.
    if (isset($element['field_no_multiple_submissions']['widget']['value']['#description'])) {
      $element['field_no_multiple_submissions']['widget']['value']['#description'] = \Drupal::service('anu_lms.settings')->getPhrase($element['field_no_multiple_submissions']['widget']['value']['#description']);
    }

    // Get "Hide correct answers" description.
    if (isset($element['field_hide_correct_answers']['widget']['value']['#description'])) {
      $element['field_hide_correct_answers']['widget']['value']['#description'] = \Drupal::service('anu_lms.settings')->getPhrase($element['field_hide_correct_answers']['widget']['value']['#description']);
    }
  }
}

/**
 * Implements hook_ENTITY_TYPE_access().
 *
 * Check "module_assessment" node for access.
 */
function anu_lms_assessments_node_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($entity->bundle() === 'module_assessment' && $operation === 'view') {
    /** @var \Drupal\anu_lms\Lesson $lesson_handler */
    $lesson_handler = \Drupal::service('anu_lms.lesson');
    $course = $lesson_handler->getLessonCourse($entity->id());

    // If the course exists, then check access.
    if ($course) {
      return AccessResult::forbiddenIf(!$course->access('view', $account));
    }
  }

  return AccessResult::neutral();
}
