<?php
// https://www.qed42.com/blog/autocomplete-drupal-8
// https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

namespace Drupal\materio_sapi\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Tags;
use Drupal\Component\Utility\Unicode;
use Drupal\search_api\Entity\Index;


/**
 * Defines a route controller for entity autocomplete form elements.
 */
class FormAutocomplete extends ControllerBase {

  /**
   * Handler for autocomplete request.
   */
  public function autocomplete(Request $request) {
    // Get the typed string from the URL, if it exists.
    if ($input = $request->query->get('q')) {
      $typed_string = Tags::explode($input);
      $typed_string = Unicode::strtolower(array_pop($typed_string));
      // \Drupal::logger('materio_sapi')->notice($typed_string);

      $index = Index::load('autocomplete');
      $query = $index->query();

      // Change the parse mode for the search.
      $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
        ->createInstance('direct');
      $parse_mode->setConjunction('OR');
      $query->setParseMode($parse_mode);

      // Set fulltext search keywords and fields.
      $query->keys($typed_string);
      $query->setFulltextFields(['name', 'synonyms']);

      // Set additional conditions.
      $query->addCondition('status', 1);
        // ->addCondition('author', 1, '<>');

      // Restrict the search to specific languages.
      // $query->setLanguages(['de', 'it']);

      // Do paging.
      $query->range(0, 10);

      // Add sorting.
      $query->sort('search_api_relevance', 'DESC');

      // Set one or more tags for the query.
      // @see hook_search_api_query_TAG_alter()
      // @see hook_search_api_results_TAG_alter()
      $query->addTag('materio_sapi_autocomplete');

      $results = $query->execute();

      \Drupal::logger('materio_sapi')->notice($results->getResultCount());
      // $items = $results->getResultItems();
      // \Drupal::logger('materio_sapi')->notice(implode(', ', array_keys($items)));

      $response = [];
      foreach ($results as $result) {
        // \Drupal::logger('materio_sapi')->notice(print_r($result->getField('tid')->getValues(),true));
        // \Drupal::logger('materio_sapi')->notice(print_r($result->getField('name')->getValues(),true));
        // \Drupal::logger('materio_sapi')->notice(implode(', ', array_keys($result)));
        $tid = $result->getField('tid')->getValues()[0];
        $term_name = $result->getField('name')->getValues()[0]->getText();
        $response[] = [
          'value' => $tid,
          'label' => $term_name,
        ];
      }
    }

    return new JsonResponse($response);
  }

}
