<?php

/*
 * @file
 *
 */

use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Render\Element;
use Drupal\node\Entity\Node;

/**
 * Implements hook_help().
 */
function pe_section_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.pe_section':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('TODO') . '</p>';
      return $output;
  }
}


function loadSectionParents() {
  $parents = [];
  $query = \Drupal::service('database')->select('node_field_data', 't');
  $query->join('node__field_parent_section', 'h', 'h.entity_id = t.nid');
  $query->addField('t', 'nid');
  $query->condition('t.type', 'pe_section');
  $query->condition('t.default_langcode', 1);
  $query->condition('h.field_parent_section_target_id', 0);
  $query->addTag('node_access');
  $query->orderBy('t.title');

  if ($ids = $query->execute()->fetchCol()) {
    $parents = Node::loadMultiple($ids);
  }

  return $parents;
}

function loadSectionChildren($tid) {
  $children = [];
  $query = \Drupal::service('database')->select('node_field_data', 't');
  $query->join('node__field_parent_section', 'h', 'h.entity_id = t.nid');
  $query->addField('t', 'nid');
  $query->condition('t.type', 'pe_section');
  $query->condition('t.default_langcode', 1);
  $query->condition('h.field_parent_section_target_id', $tid);
  $query->addTag('node_access');
  $query->orderBy('t.title');

  if ($ids = $query->execute()->fetchCol()) {
    $children = Node::loadMultiple($ids);
  }

  return $children;
}


function loadSectionTree($pad = '') {
  $tree = [];
  $parents = loadSectionParents();
  foreach ($parents as $parent) {
    $tree[$parent->id()] = $parent->label();
    $children = loadSectionChildren($parent->id());
    foreach ($children as $child) {
      $tree[$child->id()] = $pad . \Drupal::entityManager()->getTranslationFromContext($child)->label();
    }
  }

  return $tree;
}