<?php

namespace Drupal\rufi_structure\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Entity\Element\EntityAutocomplete;

/**
 * Defines a route controller for watches autocomplete form elements.
 */
class SearchKeyAutoCompleteController extends ControllerBase {

  /**
   * Drupal\Core\Database\Driver\mysql\Connection definition.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * Constructs a new EvaluatingService object.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this form class.
    return new static(
      $container->get('database')
    );
  }

  /**
   * Handler for autocomplete request.
   */
  public function handleAutocomplete(Request $request) {
    $results = [];
    $input = $request->query->get('q');

    // Get the typed string from the URL, if it exists.
    if (!$input) {
      return new JsonResponse($results);
    }

    $input = Xss::filter($input);

    // Get the typed string from the URL, if it exists.
    if (strlen($input) < 3) {
      return new JsonResponse($results);
    }

    $query = $this->database->select('search_index', 'si');
    $query->fields('si', ['word']);
    $query->condition('si.word', "$input%", 'LIKE');
    $query->condition('si.type', "node_search");
    $query->distinct(TRUE);
    $keywords = $query->execute()->fetchAll();

    foreach ($keywords as $keyword) {
      $results[] = [
        'value' => $keyword->word,
        'label' => $keyword->word,
      ];
    }

    return new JsonResponse($results);
  }
}
