<?php

/**
 * @file
 * Update hooks for the module.
 */

use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\Core\Database\Database;

/**
 * Implements hook_schema().
 */
function anu_lms_schema() {
  $schema['anu_lms_progress'] = [
    'description' => 'Stores user progress across ANU LMS content.',
    'fields' => [
      'uid' => [
        'description' => 'The {users}.id this record affects.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ],
      'nid' => [
        'description' => 'The {node}.nid completed by the {users}.id.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ],
      'created' => [
        'description' => 'The Unix timestamp when the entry was created.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ],
      'changed' => [
        'description' => 'The Unix timestamp when the entry was most recently saved.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ],
    ],
    'primary key' => ['uid', 'nid'],
    'indexes' => [
      'uid' => ['uid'],
    ],
    // For documentation purposes only; foreign keys are not created in the
    // database.
    'foreign keys' => [
      'data_user' => [
        'table' => 'users',
        'columns' => [
          'uid' => 'uid',
        ],
      ],
    ],
  ];

  return $schema;
}

/**
 * Migrate modules content from nodes to paragraphs.
 */
function anu_lms_update_8001() {
  /** @var \Drupal\node\Entity\NodeInterface[] $courses */
  $courses = \Drupal::entityTypeManager()->getStorage('node')
    ->loadByProperties(['type' => 'course']);

  foreach ($courses as $course) {
    /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem[] $modules */
    $modules_references = $course->get('field_course_modules');
    if (!empty($modules_references)) {
      foreach ($modules_references as $modules_reference) {
        $lesson_nids = [];
        $quiz_nid = FALSE;

        /** @var \Drupal\node\Entity\NodeInterface $module */
        $module = Node::load($modules_reference->target_id);

        if (!empty($module)) {
          /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem[] $lessons_references */
          $lessons_references = $module->get('field_module_lessons');
          foreach ($lessons_references as $lessons_reference) {
            $lesson_nids[] = $lessons_reference->target_id;
          }

          /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $quiz_references */
          $quiz_references = $module->get('field_module_assessment');
          foreach ($quiz_references as $quiz_reference) {
            $quiz_nid = $quiz_reference->target_id;
          }

          /** @var \Drupal\paragraphs\Entity\ParagraphInterface $paragraph */
          $paragraph = Paragraph::create(['type' => 'course_modules']);
          $paragraph->set('field_module_title', $module->label());
          foreach ($lesson_nids as $nid) {
            $paragraph->field_module_lessons[] = $nid;
          }
          if (!empty($quiz_nid)) {
            $paragraph->field_module_assessment = $quiz_nid;
          }
          $paragraph->save();

          $current = $course->get('field_course_module')->getValue();
          $current[] = [
            'target_id' => $paragraph->id(),
            'target_revision_id' => $paragraph->getRevisionId(),
          ];

          $course->set('field_course_module', $current);
        }
      }

      $course->save();
    }
  }
}

/**
 * Migrate is_highlight field on image bullet list paragraphs to default color.
 */
function anu_lms_update_8002() {
  /** @var \Drupal\node\Entity\NodeInterface[] $lessons */
  $lessons = Drupal::entityTypeManager()->getStorage('node')
    ->loadByProperties(['type' => 'module_lesson']);
  foreach ($lessons as $lesson) {
    /** @var \Drupal\entity_reference_revisions\Plugin\Field\FieldType\EntityReferenceRevisionsItem[] $sections */
    $sections = $lesson->get('field_module_lesson_content')
      ->referencedEntities();
    foreach ($sections as $section) {
      /** @var \Drupal\paragraphs\Entity\Paragraph $contents */
      $contents = $section->get('field_lesson_section_content')
        ->referencedEntities();
      foreach ($contents as $content) {
        if ($content->getType() == 'lesson_img_list') {
          /** @var \Drupal\Core\Field\FieldItemList $highlight_field */
          $highlight_field = $content->get('field_lesson_img_list_highlight');
          if ($highlight_field->getString() == "1") {
            $content->set('field_lesson_highlight_color', 'yellow');
            $content->save();
          }
        }
      }
    }
  }
}

/**
 * Create a new table for storing user progress.
 */
function anu_lms_update_8220() {
  $schema = anu_lms_schema();
  \Drupal::database()->schema()->createTable('anu_lms_progress', $schema['anu_lms_progress']);
}

/**
 * Create new columns on the progress table.
 */
function anu_lms_update_8240() {
  $createdSpec = [
    'description' => 'The Unix timestamp when the entry was created.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ];
  $changedSpec = [
    'description' => 'The Unix timestamp when the entry was most recently saved.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ];
  $schema = Database::getConnection()->schema();
  $schema->addField('anu_lms_progress', 'created', $createdSpec);
  $schema->addField('anu_lms_progress', 'changed', $changedSpec);
}

/**
 * Installs new required dependency Paragraphs Browser.
 */
function anu_lms_update_9280() {
  \Drupal::service('module_installer')->install(['paragraphs_browser']);
}

/**
 * Set default definitions for anu_lms.
 */
function anu_lms_update_9282() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('anu_lms.entity_labels');

  $config->set('courses_page_labels', 'Courses page|Courses pages')->save(TRUE);
  $config->set('courses_page_label_plural', 'Courses pages')->save(TRUE);
  $config->set('course_labels', 'Course|Courses')->save(TRUE);
  $config->set('course_label_plural', 'Courses')->save(TRUE);
  $config->set('lesson_labels', 'Lesson|Lessons')->save(TRUE);
  $config->set('lesson_label_plural', 'Lessons')->save(TRUE);
  $config->set('assessment_labels', 'Quiz|Quizzes')->save(TRUE);
  $config->set('assessment_label_plural', 'Quizzes')->save(TRUE);
  $config->set('module_labels', 'Module|Modules')->save(TRUE);
  $config->set('module_label_plural', 'Modules')->save(TRUE);
}
